Tuesday, 1 December 2026

Caching Strategies and Cache Invalidation in Distributed Systems

  

1. Fundamentals of Caching

Caching is a fundamental technique used across modern computing systems to improve performance, reduce latency, minimize backend workload, and avoid repeatedly executing expensive operations. From CPU caches and operating system page caches to database, application, API, and CDN caches, caching exists at multiple layers of the technology stack.

 

However, introducing a cache also introduces challenges around data freshness, consistency, and cache invalidation. Choosing the wrong caching strategy can increase latency, waste memory, and even cause data loss or inconsistent application behavior.

 

This article explores the fundamental concepts of caching, different caching strategies, and the challenges involved in keeping cached data consistent with its source of truth. It also examines how to choose an appropriate caching strategy based on application requirements and read/write access patterns.

 

1.1 What Is a Cache and How Does It Work?

A cache is a high-speed storage layer that temporarily stores a subset of data retrieved from a slower or more expensive data source.

 

The cached data is generally a copy of information available in an underlying system, such as a database, file system, or remote service. Instead of repeatedly accessing the original source, applications can retrieve frequently requested data directly from the cache.

 

A cache typically has three characteristics:

-       Faster access: Retrieving data from a cache is generally faster than accessing the original data source.

-       Limited storage: Caches usually have less storage capacity than the underlying data source because they use faster but more expensive storage.

-       Temporary storage: Cached data is retained only for a certain period or until it is explicitly removed or replaced.

 

Consider an application that retrieves customer information from a relational database. Without caching, every request requires a database query, even when multiple requests are retrieving the same customer information.

 

With caching, the application first checks whether the requested customer information is already available in the cache.

 

The process works as follows:

-       A client sends a request to retrieve customer information.

-       The application checks the cache using the customer ID as the cache key.

-       If the information exists in the cache, the application retrieves it and returns the response.

-       If the information does not exist, the application queries the database.

-       The application stores the retrieved information in the cache.

-       Subsequent requests for the same customer can retrieve the information directly from the cache.

 

For example, consider a customer record:

{
  "customerId": 101,
  "name": "John",
  "city": "Bangalore"
}

The first request retrieves the customer record from the database and stores it in Redis.

 

Request 1:

Application → Redis → Cache Miss

Application → Database → Fetch Customer

Application → Redis → Store Customer

Application → Client → Return Response

 

When another request arrives for the same customer:

 

Request 2:

Application → Redis → Cache Hit

Application → Client → Return Response

 

The second request avoids the database query entirely.

 

This approach reduces repeated database access and improves response times, particularly when the same information is requested frequently.

 


   

1.2 Why Do We Need Caching?

Caching is primarily introduced to improve data retrieval performance and reduce the cost of repeatedly accessing or generating information.

 

There are several reasons why caching is useful.

 

1.2.1 Reducing Data Retrieval Latency

Latency is the time taken to retrieve information or complete an operation.

 

Accessing data from different storage layers involves different levels of latency. For example, retrieving information from CPU registers or memory is significantly faster than retrieving it from a remote database or external service.

 

Consider an application that retrieves user profile information from a database hosted in another geographical region. Every request involves network communication, database processing, and response transmission.

 

If the same information is frequently requested, storing it in a nearby cache can eliminate repeated network communication with the database.

 

For example:

Operation

Illustrative latency

Retrieve from local memory

0.1 ms

Retrieve from Redis

1 ms

Retrieve from remote database

20 ms

Retrieve from external API

100 ms

        

By retrieving frequently accessed information from a faster storage layer, applications can significantly reduce response times.

 

1.2.2 Avoiding Expensive Computations

Not all caching is about avoiding database queries. Sometimes generating the required information is itself expensive.

 

Consider an e-commerce application that displays recommended products based on customer behavior.

 

Generating recommendations might involve:

-       Analyzing customer browsing history.

-       Processing purchase history.

-       Running machine learning algorithms.

-       Combining information from multiple databases.

-       Ranking products based on relevance.

 

These operations may take several seconds to complete. If the same recommendations are requested repeatedly, executing the entire computation for every request is unnecessary.

 

Instead, the application can calculate the recommendations once, store the result in a cache, and reuse it for subsequent requests.

 

For example:

First Request:

Customer Request
       |
       v
Recommendation Service
       |
       v
Process Customer History
       |
       v
Generate Recommendations
       |
       v
Store Results in Cache
       |
       v
Return Recommendations

   

Subsequent Requests:

 

Customer Request
       |
       v
Check Cache
       |
       v
Retrieve Recommendations
       |
       v
Return Response

This approach avoids repeatedly performing expensive computations and improves application response times.

 

1.2.3 Reducing Database and Backend Workload

In high-traffic applications, the same information may be requested thousands or millions of times.

 

Without caching, every request reaches the underlying database or backend service, increasing the overall workload.

 

Consider an application receiving 100,000 requests per minute for product catalog information. If every request reaches the database, the database must process all 100,000 requests.

 

Now suppose the application introduces a cache with a 90% cache hit ratio.

- Total requests: 100,000.

- Cache hits: 90,000.

- Cache misses: 10,000.

- Database requests: 10,000.

 

The database workload is reduced by 90%.

 

Reducing database workload has several benefits:

- Fewer database queries.

- Lower CPU and memory utilization.

- Reduced database connection usage.

- Less network traffic between application and database.

- Lower infrastructure and operational costs.

 

Caching is particularly useful for read-heavy workloads where the same information is requested frequently but does not change often.

 

1.2.4 Improving Application Scalability

Scalability refers to a system's ability to handle increasing workloads without a proportional degradation in performance.

 

As the number of users and requests increases, backend services and databases can become bottlenecks.

 

Caching helps address this problem by serving frequently requested information without involving the original data source for every request.

 

Consider an application with multiple application instances accessing a shared database.

 

Without caching:

 

Every application instance sends requests directly to the database.

 

With a distributed cache:

Multiple application instances can access the same cached information, reducing repeated database operations.

 

This allows the backend to support a larger number of application requests with the same database capacity.

 

However, caching does not automatically guarantee scalability. The cache itself must be designed to handle the expected request volume, memory requirements, and concurrent access patterns.

 

   

1.3 Cache Hit, Cache Miss, and Cache Hit Ratio

To understand cache performance, it is important to understand three fundamental concepts: cache hit, cache miss, and cache hit ratio.

 

a. Cache Hit

A cache hit occurs when an application requests data and the requested information is already available in the cache. The application retrieves the information directly from the cache without accessing the original data source.

 

For example:

Application → Cache
                 |
                 v
            Data Found
                 |
                 v
            Return Data

   

Cache hits are desirable because they avoid accessing slower data sources.

 

b. Cache Miss

A cache miss occurs when the requested information is not available in the cache.

 

This can happen because:

- The information has never been cached.

- The cache entry has expired.

- The entry was explicitly invalidated or evicted.

- The cache was restarted or lost its contents.

 

When a cache miss occurs, the application generally retrieves the information from the original data source and may populate the cache for future requests.

 

Application → Cache
                 |
                 v
             Data Missing
                 |
                 v
              Database
                 |
                 v
            Fetch Data
                 |
                 v
            Update Cache
                 |
                 v
            Return Data

c. Cache Hit Ratio

The cache hit ratio measures the percentage of requests successfully served from the cache. It is calculated using the following formula:

 

   


Consider an application receiving 10,000 cache requests.

-       Cache hits: 8,000.

-       Cache misses: 2,000.

-       Total requests: 10,000.

 

Cache Hit Ratio = (8000 / 10000) * 100 = 80%

 

A higher cache hit ratio generally indicates that the cache is effectively serving frequently requested data.

 

However, a high hit ratio does not always mean the caching implementation is optimal. The cost of cache misses, cache lookup latency, data freshness requirements, and memory consumption must also be considered.

 

1.4 Cache Hierarchy Across Different Layers

Caching is not limited to application-level systems. It exists throughout the computing stack.

 

Different layers maintain their own caches to reduce access latency and avoid repeatedly retrieving information from slower storage or remote systems.

 

Let's examine some commonly used caching layers.

 

1.4.1 CPU and Memory Caches

Modern processors use multiple levels of hardware cache to reduce the time required to access data from main memory (RAM).

 

CPU caches store frequently accessed instructions and data close to the processor cores.

 

The commonly used cache levels are:

-       L1 Cache: The smallest and fastest cache, typically private to each CPU core. It is commonly divided into instruction and data caches.

-       L2 Cache: Larger than L1 but generally slower. Depending on the processor architecture, it may be private to a core or shared by a group of cores.

-       L3 Cache: Generally larger than L1 and L2 and often shared across multiple CPU cores.

 

When a processor needs data, it searches the cache hierarchy before accessing main memory.

 

For example:

-       The processor checks L1 cache.

-       If the data is unavailable, it checks L2.

-       If it is still unavailable, it checks L3.

-       If all cache levels miss, it retrieves the data from main memory.

   


This hierarchy reduces average memory access latency and improves processor performance.

 

1.4.2 Operating System and Disk Caches

Operating systems use memory to cache frequently accessed files and disk blocks.

 

When an application reads a file, the operating system may retain the file's contents in memory so that subsequent reads can be served without accessing the physical storage device.

 

For example, when an application repeatedly reads the same configuration file, the operating system can serve subsequent reads from its page cache rather than reading the file from an SSD or HDD.

 

Common examples include:

-       Page Cache: Stores recently accessed file data in RAM.

-       Buffer Cache: Caches disk blocks or storage data structures, depending on the operating system and storage implementation.

-       Filesystem Metadata Cache: Stores frequently accessed filesystem information, such as directory entries and inode metadata.

 

These mechanisms reduce disk I/O and improve file access performance.

 

1.4.3 Database and Distributed Caches

Databases use caching internally to avoid repeatedly reading information from physical storage.

 

For example, relational databases such as PostgreSQL and MySQL maintain buffer pools or shared buffers containing frequently accessed database pages.

 

When a query needs a database page, the database first checks whether the page is already available in memory. If it is available, the database can avoid reading it from disk.

 

Apart from internal database caching, applications also use external distributed caching systems such as:

-       Redis.

-       Memcached.

-       Amazon DynamoDB Accelerator (DAX).

 

These systems store frequently accessed application data outside the database. For example, an application can retrieve customer information from Redis instead of executing the same database query repeatedly.

 

Unlike database buffer pools, which cache internal database pages, distributed caches typically store application-level data such as objects, serialized responses, query results, or computed values.

 

1.4.4 Application and API Caches

Applications frequently cache information that requires expensive processing or repeated communication with backend services.

 

For example, consider an application that provides a customer dashboard containing:

-       Customer profile information.

-       Order history.

-       Payment summaries.

-       Product recommendations.

 

Generating the dashboard might require multiple database queries and service calls. Instead of executing all these operations for every request, the application can cache the complete dashboard response or individual components.

 

Application caching can be implemented using:

-       In-memory caches within an application instance.

-       Distributed caches such as Redis.

-       Cached API responses.

 

API caching is particularly useful when multiple clients repeatedly request the same information.

 

For example, an API returning country and state information does not need to retrieve the same reference data from a database for every request. The application can cache the response and serve subsequent requests directly from the cache.

 

One important distinction is that an in-memory application cache is usually local to a particular application instance, whereas a distributed cache can be shared across multiple instances.

 

1.4.5 CDN, DNS, and Browser Caches

Caching also plays an important role in reducing network latency and improving the performance of web applications.

 

CDN caching

A Content Delivery Network (CDN) stores copies of static content, such as images, JavaScript files, CSS files, and videos, at geographically distributed edge locations.

 

When a user requests an image, the CDN can serve it from an edge location closer to the user rather than retrieving it from the origin server.

 

For example, a user in India accessing a website hosted in the United States may receive images from a CDN edge location in India.

 

This reduces network latency and decreases the load on the origin server.

 

DNS caching

DNS caching stores the results of domain name lookups.

 

When a user accesses a website, the DNS resolver translates the domain name into an IP address.

 

Instead of performing the same DNS lookup repeatedly, the result can be cached for a specified period based on its Time-to-Live (TTL).

 

This reduces DNS lookup overhead and improves connection establishment time.

 

Browser caching

Web browsers cache resources such as images, stylesheets, JavaScript files, and other HTTP responses.

 

When a user revisits a website, the browser may reuse locally cached resources instead of downloading them again.

 

HTTP caching headers such as the following control browser caching behavior:

-       Cache-Control: Specifies caching policies and directives.

-       Expires: Specifies an expiration date for a cached response.

-       ETag: Identifies a particular version of a resource.

-       Last-Modified: Indicates when a resource was last modified.

 

For example:

Cache-Control: public, max-age=3600

 

This tells compliant HTTP caches that the response can be considered fresh for 3,600 seconds (one hour), subject to other applicable caching directives.

 

Together, CDN, DNS, and browser caching reduce network communication and improve website performance.

 

1.5 Cache Expiration and Time-to-Live (TTL)

Caching data indefinitely is generally not practical because the underlying information may change over time.

 

For example, consider an e-commerce application that caches product prices.

 

If the product price changes in the database but the cache continues serving the old value, users may see incorrect pricing information. To address this problem, caches commonly support Time-to-Live (TTL). TTL defines how long a cache entry remains valid before it expires.

 

For example, suppose an application stores customer information in Redis with a TTL of 30 minutes.

Cache Key: customer:101

Value:
{
  "customerId": 101,
  "name": "John",
  "city": "Bangalore"
}

TTL: 1800 seconds

   

Once 30 minutes have elapsed, the cache entry expires and is no longer available as a valid cache entry. When the application requests the information again, it retrieves the latest available information from the database and populates the cache again.

 

TTL helps balance two competing requirements:

-       Data freshness: How recently the cached information must reflect changes in the source.

-       Performance: How long the application can continue serving cached information without retrieving it again.

 

For example:

Type of data

Illustrative TTL

Country and state reference data

24 hours

Product catalog

30 minutes

Customer profile

10 minutes

Frequently changing inventory

30 seconds

 

Real-time stock prices

Very short or no caching, depending on requirements

 

These are illustrative values, not universal recommendations.

 

The appropriate TTL depends on how frequently the data changes, how stale the application can tolerate it becoming, and the cost of retrieving it again.

 

It is also important to understand that TTL expiration does not necessarily mean the entry is physically deleted at that exact instant. Cache implementations may use lazy expiration, background expiration, or a combination of both.

 

TTL is one way to manage cache freshness. Other techniques, such as explicit invalidation and event-driven invalidation, are covered in the cache invalidation section.

        

1.6 When Caching Is Beneficial and When It Should Be Avoided

Caching can improve performance significantly, but introducing a cache does not automatically make an application faster. In some situations, caching can add unnecessary overhead, increase infrastructure costs, and introduce additional consistency challenges.

 

Before introducing a cache, it is important to evaluate the data access patterns and application requirements.

 

1.6.1 When Should We Use Caching?

Caching is generally beneficial in the following situations.

 

a. Frequently accessed data

If the same information is requested repeatedly, caching can avoid retrieving it from the original source every time.

 

Examples include user profiles, product catalogs, configuration settings, and reference data.

 

b. Expensive database queries

Queries involving multiple joins, aggregations, large datasets, or complex filtering can be expensive to execute repeatedly. Caching their results can significantly reduce database workload.

 

c. Expensive computations

Operations such as machine learning predictions, report generation, and complex business calculations can benefit from caching their previously computed results.

 

d. Read-heavy workloads

Applications where reads significantly outnumber writes are good candidates for caching. For example, news websites, product catalogs, and content platforms often serve the same information to many users.

 

e. Geographically distributed applications

Caching data closer to users through CDNs or regional caching layers can reduce network latency and improve response times.

1.6.2 When Should We Avoid Caching?

There are situations where caching may not provide meaningful benefits or may even negatively affect performance.

 

a. Frequently changing data

If information changes continuously and must always reflect the latest state, caching may introduce unacceptable staleness.

 

Examples include real-time financial transactions, rapidly changing inventory, and critical live monitoring data.

 

Caching may still be possible in some of these scenarios, but it requires carefully designed freshness and consistency guarantees.

 

b. Infrequently accessed data

If information is rarely requested, storing it in a cache may waste valuable memory.

 

For example, caching millions of records that are accessed only once may provide very little benefit.

 

c. Highly unique requests

Consider a search application where every user submits a different search query. If almost every request produces a unique result, the cache hit ratio may be very low. In such cases, cache lookups and storage overhead may outweigh the benefits.

 

d. Operations with side effects

Caching is generally suitable for operations that return reusable results without producing unintended side effects.

 

Consider an API that retrieves account information while also updating an access counter or recording an audit event. Caching the complete operation's result and skipping subsequent executions could prevent those side effects from occurring. Such operations need to be designed carefully before introducing caching.

 

5. When cache overhead exceeds the benefit

A cache introduces its own lookup latency, network communication, serialization/deserialization overhead, memory consumption, and operational complexity.

 

Consider the following example:

- Database query latency: 60 ms.

- Cache lookup latency: 10 ms.

- Cache hit ratio: 5%.

- Total requests: 1,000,000.

 

Without caching: 1,000,000 X 60 = 60,000,000 ms

With caching:

-       Cache hits: 50,000.

-       Cache misses: 950,000.

-       Time is (50,000 X 10) + (950,000 X 70) = 67,000,000ms

 

In this simplified example, caching increases the aggregate request-processing time because the hit ratio is too low and every cache lookup adds overhead.

 

This demonstrates why caching decisions should be based on actual workload characteristics rather than assuming that introducing a cache will always improve performance.

 

In summary, Caching is a fundamental performance optimization technique used across hardware, operating systems, databases, applications, and distributed systems.

 

Its primary objective is to reduce repeated access to slower data sources and avoid unnecessary computation by storing frequently used information in faster storage layers.

 

However, the effectiveness of caching depends on access patterns, cache hit ratio, data freshness requirements, and the overhead introduced by the cache itself.

 

Understanding these fundamentals provides the foundation for exploring different caching strategies and how applications manage read and write operations efficiently.  

        

2. Caching Strategies and Access Patterns

Caching is not simply about storing frequently accessed information in a faster storage layer. An important design decision is determining how data moves between the application, cache, and primary data source during read and write operations.

 

Different applications have different access patterns. Some applications read the same information thousands of times but update it occasionally, while others continuously generate new information and rarely read it again.

 

For example, an e-commerce product catalog is typically read frequently but updated relatively infrequently. On the other hand, an application that processes financial transactions may have a significantly higher volume of writes, where data correctness and durability are critical.

 

Using the same caching strategy for both applications may not produce the desired results.

 

Caching strategies define how an application retrieves information from a cache, how missing data is loaded, and how updates are propagated to the underlying data source.

 

In this section, we will explore the major caching strategies, understand their read and write behavior, and examine how to select an appropriate strategy based on application workload characteristics.

 

2.1 Understanding Read and Write Access Patterns

Before selecting a caching strategy, it is important to understand how an application accesses its data.

 

An access pattern describes how frequently data is read, written, updated, or deleted by an application.

 

The two primary access operations are:

-       Read: Retrieving existing information from a data source.

-       Write: Creating new information or modifying existing information in a data source.

 

The frequency and distribution of these operations influence how caching should be implemented.

 

a. Read-Heavy Workloads

A read-heavy workload occurs when an application performs significantly more read operations than write operations.

 

For example, consider an e-commerce application displaying product information.

 

Thousands of customers may view the same product details, but the product description, specifications, and category information may change only occasionally.

 

In such scenarios, retrieving product information from the database for every request is unnecessary. The application can cache frequently accessed product information and serve subsequent requests directly from the cache.

 

Typical examples include:

-       Product catalogs and product descriptions.

-       Customer profiles.

-       News articles and blog content.

-       Application configuration and reference data.

-       Frequently accessed reports and dashboard results.

 

Read-heavy workloads generally benefit from strategies such as Cache-Aside and Read-Through because they populate the cache when information is requested and reuse it for subsequent reads.

 

b. Write-Heavy Workloads

A write-heavy workload occurs when an application performs significantly more write operations than read operations.

 

Consider an application that continuously collects sensor readings from thousands of devices.

 

The application may receive millions of new readings, but individual readings might rarely be accessed after they are stored.

 

Caching every write in memory may be unnecessary because the data is unlikely to be reused.

 

In some scenarios, however, applications can benefit from temporarily buffering writes in memory and asynchronously persisting them to the database.

 

Typical examples include:

-       Real-time event ingestion.

-       Logging and telemetry systems.

-       High-volume transaction processing.

-       IoT sensor data collection.

-       Systems processing large numbers of updates.

 

Write-heavy workloads may benefit from Write-Around or Write-Back strategies, depending on whether the data needs to be cached and how much durability is required.

 

c. Mixed Read and Write Workloads

Some applications perform substantial read and write operations.

 

For example, a social media application allows users to publish posts, update profiles, and interact with content while other users continuously retrieve the same information.

 

In such applications, caching must support both efficient reads and appropriate write propagation.

 

A combination of strategies may be necessary. The following table summarizes the common workload characteristics.

 

Workload

Characteristics

Example

Read-heavy

Frequent reads, occasional writes

Product catalog

Write-heavy

Frequent writes, fewer reads 

Event ingestion

Read-once, write-once

Data is written and rarely accessed again   

Application logs

 

Mixed workload

Frequent reads and writes

Social media

Read-intensive, expensive computation

Repeated requests for costly results

Analytics dashboards

 

 

Understanding these access patterns is the first step toward selecting an appropriate caching strategy.

 

2.2 Cache-Aside (Lazy Loading)

Cache-Aside is one of the most commonly used caching strategies in application development.

 

In this approach, the application is responsible for interacting with both the cache and the primary data source.

 

The cache operates independently of the database, and the application explicitly manages cache lookups, cache population, and cache updates or invalidation.

 

It is also known as Lazy Loading because information is loaded into the cache only when an application requests it.

 

How Cache-Aside Works

Consider an application that retrieves customer information using a customer ID. When a request arrives, the application first checks whether the requested customer information exists in the cache.

 

There are two possible scenarios.

 

Scenario 1: Cache Hit

-       The application receives a customer information request.

-       It checks the cache using the customer ID.

-       The requested information is available in the cache.

-       The application retrieves the information and returns it to the client.

-       The database is not involved in this request.

 

Scenario 2: Cache Miss

-       The application receives a customer information request.

-       It checks the cache using the customer ID.

-       The requested information is not available.

-       The application queries the database.

-       The database returns the customer information.

-       The application stores the retrieved information in the cache.

-       The application returns the information to the client.

 



 

Implementation Example

Consider the following simplified Java implementation using a cache and a repository abstraction.

public Customer getCustomer(Long customerId) {

    // Check cache first
    Customer customer = cache.get(customerId);

    if (customer != null) {
        return customer;
    }

    // Cache miss: retrieve from database
    customer = customerRepository.findById(customerId)
            .orElseThrow();

    // Populate cache
    cache.put(customerId, customer);

    return customer;
}

The application explicitly controls the entire process. When customer information is requested for the first time, the application retrieves it from the database and stores it in the cache.

 

Subsequent requests can retrieve the same information directly from the cache.

 

Handling Write Operations

In Cache-Aside, write operations are generally performed directly against the database. After successfully updating the database, the application invalidates the corresponding cache entry.

 

For example:

 

public void updateCustomer(Customer customer) {

    // Update source of truth
    customerRepository.save(customer);

    // Invalidate cached customer
    cache.evict(customer.getId());
}

   

The next read request results in a cache miss, causing the application to retrieve the latest available information from the database and populate the cache again. An alternative is to update the cache after updating the database.

        

Advantages

-       Simple to implement and widely supported.

-       The application has complete control over cache behavior.

-       Only requested data is loaded into the cache.

-       The cache can store application-specific objects or aggregated results that differ from the database data model.

-       The application can continue operating using the database if the cache becomes unavailable, although performance may degrade significantly.

 

Disadvantages

-       The application must explicitly manage cache lookups, population, and invalidation.

-       The first request for an uncached item experiences additional latency.

-       Cache and database inconsistencies can occur during concurrent updates.

-       If multiple requests simultaneously experience a cache miss, they may execute the same database query, creating a cache stampede.  

 

When to Use Cache-Aside

Cache-Aside is particularly suitable for read-heavy applications where the same information is requested repeatedly.

 

Examples include:

-       Customer profile services.

-       Product catalog services.

-       Application configuration services.

-       Frequently accessed reference data.

-       Aggregated API responses.

 

It is a good general-purpose caching strategy when the application needs explicit control over how information is cached.

 

2.3 Read-Through Caching

Read-Through caching is similar to Cache-Aside, but there is an important architectural difference.

 

In Cache-Aside, the application is responsible for retrieving missing information from the database and populating the cache.

 

In Read-Through caching, the cache itself is responsible for loading missing information from the underlying data source.

 

The application communicates with the cache, and the cache handles the interaction with the database when the requested information is unavailable.

 

How Read-Through Works?

Consider the same customer information example.

-       The application requests customer information from the cache.

-       The cache checks whether the requested information exists.

-       If the information exists, the cache returns it directly.

-       If the information is missing, the cache invokes its configured data loader.

-       The data loader retrieves the information from the database.

-       The cache stores the retrieved information.

-       The cache returns the information to the application.

 

The application does not need to implement separate cache-miss handling logic because the cache abstraction handles it.

 

   


Implementation Example

Consider a Java application using a loading cache abstraction.

LoadingCache<Long, Customer> customerCache =
    Caffeine.newBuilder()
        .maximumSize(10000)
        .expireAfterWrite(Duration.ofMinutes(30))
        .build(customerId ->
            customerRepository.findById(customerId)
                .orElseThrow()
        );

The application retrieves customer information using:

Customer customer = customerCache.get(customerId);

If the customer is already cached, the cached value is returned. If it is missing, the configured loader retrieves the information from the repository and automatically populates the cache.

 

This is an example of Read-Through behavior implemented through a loading cache abstraction.

 

Advantages

-       Cache-miss handling is centralized in the cache layer.

-       Application code becomes simpler.

-       Cache population is handled automatically.

-       Only requested information is loaded.

-       It works well for frequently accessed information.

 

Disadvantages

-       The initial request for uncached information still experiences database retrieval latency.

-       The cache must have access to an appropriate data-loading mechanism.

-       The application has less direct control over the loading process.

-       Data synchronization and invalidation still need to be addressed when the underlying database changes.

 

When to Use Read-Through Caching?

Read-Through caching is useful when:

-       The application repeatedly accesses the same records.

-       A consistent loading mechanism is required across multiple application components.

-       The cache provider supports integration with the underlying data source.

-       Developers want to reduce repetitive cache-miss handling code.

 

It is commonly useful for customer records, product information, configuration data, and frequently accessed reference information. 

        

2.4 Write-Through Caching

So far, we have primarily discussed caching strategies that focus on reading information.

 

However, updating cached information is equally important.

 

Write-Through caching addresses this by ensuring that every write operation passes through the cache before being persisted to the primary data source.

 

In this strategy, the application writes data to the cache, and the cache synchronously propagates the update to the underlying database.

 

The application receives a successful response only after the required write operations have completed.

 

How Write-Through Works?

Consider an application that updates a customer's address.

-       The application receives a customer update request.

-       The application sends the updated customer information to the cache.

-       The cache updates the cached information.

-       The cache synchronously writes the updated information to the database.

-       Once the database write succeeds, the operation is acknowledged to the application.

 


The key characteristic is that the cache and database are updated as part of the same synchronous write workflow. This helps maintain consistency between the cached copy and the primary data source, assuming all writes go through the cache and failures are handled correctly.

 

Implementation Example     

A simplified implementation could look like this:

public void updateCustomer(Customer customer) {

    // Write to cache
    cache.put(customer.getId(), customer);

    // Synchronously update database
    customerRepository.save(customer);
}
   

This example illustrates the general idea, but it is not a fully safe production implementation.

 

For example, if the cache update succeeds but the database write fails, the cache may contain information that was never persisted. A robust implementation must handle failures, rollback or invalidate the cache entry, and consider concurrent updates.

 

Advantages

-       The cache is updated whenever the application performs a successful write.

-       Subsequent reads can retrieve the latest successfully persisted value from the cache.

-       It reduces the possibility of stale cached information when all writes follow the same path.

-       It works well with Read-Through caching for applications with frequent reads and occasional updates.

 

Disadvantages

-       Every write requires updating both the cache and database.

-       Write latency increases because the database operation must complete before acknowledging success.

-       Cache and database updates are not automatically an atomic transaction.

-       Database failures require careful error handling and cache recovery.

 

When to Use Write-Through Caching

Write-Through is useful when:

-       Data is frequently read after being updated.

-       Keeping cached information aligned with persisted data is important.

-       The application requires synchronous persistence.

-       The additional write latency is acceptable.

 

Examples include customer profiles, product information, and application configuration services.

 

A common combination is Read-Through + Write-Through, where reads automatically load missing information and writes synchronously update the cache and database.

 

2.5 Write-Around Caching

Write-Around caching is a strategy in which write operations bypass the cache and are performed directly against the primary data source.

 

Unlike Write-Through caching, where every write updates both the cache and database, Write-Around only introduces data into the cache when it is subsequently requested through a read operation.

 

This strategy is particularly useful when applications generate large volumes of data that are not frequently accessed after being written.

 

How Write-Around Works?

Consider an application that stores user activity logs. The application continuously receives new log records and writes them to a database. However, most log records are rarely accessed immediately after being created.

 

Caching every newly written log record would consume memory without providing much benefit.

 

With Write-Around caching, the process works as follows:

-       The application receives a write request.

-       The application writes the information directly to the database.

-       The cache is not updated.

-       When a subsequent read request arrives, the application checks the cache.

-       If the information is unavailable, the application retrieves it from the database.

-       The application optionally populates the cache with the retrieved information.

 


Implementation Example

Consider an application that stores customer activity information.

 

public void saveActivity(Activity activity) {

    // Write directly to database
    activityRepository.save(activity);

    // Cache is intentionally not updated
}

   

When the application subsequently retrieves the activity:

 

public Activity getActivity(Long activityId) {

    // Check cache
    Activity activity = cache.get(activityId);

    if (activity != null) {
        return activity;
    }

    // Cache miss: retrieve from database
    activity = activityRepository.findById(activityId)
            .orElseThrow();

    // Populate cache
    cache.put(activityId, activity);

    return activity;
}

The first write does not consume cache memory. Only information that is subsequently requested gets an opportunity to enter the cache.

 

Advantages

-       Write operations do not introduce additional cache update overhead.

-       Unpopular data does not unnecessarily occupy cache memory.

-       It is suitable for write-heavy applications where newly written information is rarely accessed.

-       It can be combined with Cache-Aside or Read-Through caching.

 

Disadvantages

-       The first read after a write generally results in a cache miss.

-       Frequently accessed newly written data may experience unnecessary database reads.

-       If an older version of the record is already cached, writing directly to the database without invalidating the existing cache entry can result in stale data being served.

 

The last point is particularly important. Write-Around does not mean that existing cached entries can be ignored. Applications must still invalidate or otherwise manage previously cached versions when the underlying data changes.

 

When to Use Write-Around Caching

Write-Around is useful when:

-       Data is written frequently but read infrequently.

-       Newly created information is unlikely to be accessed immediately.

-       Avoiding unnecessary cache population is important.

-       The application needs to reduce cache memory consumption.

 

Examples include:

-       Application logs.

-       Audit records.

-       Historical event data.

-       Chat messages that are rarely revisited.

-       Bulk data ingestion systems.

 

A common combination is Write-Around + Read-Through or Write-Around + Cache-Aside. The application writes directly to the database and loads information into the cache only when it is requested.

 

2.6 Write-Back (Write-Behind) Caching

Write-Back, also known as Write-Behind caching, is a strategy in which write operations are initially performed against the cache and propagated to the primary data source asynchronously.

 

Unlike Write-Through caching, the application does not wait for the database write to complete before receiving an acknowledgment.

 

The cache temporarily holds the updated information and persists it to the database later.

 

This approach can significantly improve write performance, especially when applications generate a large number of updates.

 

How Write-Back Works?

Consider an application that receives thousands of updates every second. Writing every update synchronously to the database can introduce substantial database workload and increase write latency.

 

With Write-Back caching, the process works as follows:

-       The application receives a write request.

-       The application writes the updated information to the cache.

-       The cache acknowledges the write operation immediately after accepting it.

-       The cache stores the pending update for later persistence.

-       A background process asynchronously writes the updated information to the database.

-       Once persistence succeeds, the pending write is marked as completed.

 

The most important characteristic is that the application does not wait for the database write to finish.

 


Implementation Example

Consider an application that maintains frequently updated usage counters.

 

A simplified implementation could look like this:

 

public void incrementUsage(Long customerId) {

    // Update cache immediately
    cache.increment(customerId);

    // Database persistence happens asynchronously
    backgroundWriter.schedule(customerId);
}

  A background worker periodically retrieves pending updates and persists them to the database.

 

public void flushPendingUpdates() {

    Map<Long, Long> updates = cache.getPendingUpdates();

    updates.forEach((customerId, count) -> {

        usageRepository.incrementUsage(
            customerId, count
        );

    });
}

   

This is a conceptual example. A production implementation needs durable pending-write tracking, retry handling, acknowledgment management, and protection against lost or duplicated updates.

 

Write Coalescing and Batching

One important advantage of Write-Back caching is the ability to combine multiple updates before persisting them. Consider a customer usage counter that receives 1,000 increment operations within a short period.

 

Without Write-Back:

 

Update 1    → Database
Update 2    → Database
Update 3    → Database
...
Update 1000 → Database

   

The database receives 1,000 individual update operations. With Write-Back and write coalescing:

 

Update 1
Update 2
Update 3
...
Update 1000
    |
    v
Cache Counter = 1000
    |
    v
Background Worker
    |
    v
Database: Increment by 1000

   

Instead of performing 1,000 database updates, the application can persist a single aggregated update. This reduces database operations and can improve throughput.

 

However, this optimization is appropriate only when the application can safely combine updates without changing the required business semantics.

 

Advantages

-       Write operations can be acknowledged without waiting for database persistence.

-       Reduces synchronous database workload.

-       Supports batching and write coalescing.

-       Improves write throughput for suitable workloads.

-       Can absorb temporary spikes in write traffic.

 

Disadvantages

-       Data may be lost if the cache fails before pending updates are persisted.

-       Database information may temporarily lag behind the cache.

-       Applications need mechanisms for retrying failed writes.

-       Duplicate writes must be handled carefully.

-       Recovery and reconciliation become more complex.

-       The cache becomes an important part of the write path and may require durable storage and replication.

 

When to Use Write-Back Caching

Write-Back is useful when:

-       Applications generate high volumes of write operations.

-       Immediate database persistence is not required.

-       Multiple updates can be combined.

-       The application can tolerate temporary differences between the cache and database.

-       Reliable buffering and recovery mechanisms are available.

 

Examples include:

-       Usage counters and metrics aggregation.

-       High-volume event ingestion.

-       Analytics data collection.

-       Systems that batch database updates.

 

Important: Write-Back should not be used casually for critical business transactions. If the application acknowledges a write before the data is durably recorded, a cache failure can result in permanent data loss. Durable queues, write-ahead logs, replicated storage, and recovery mechanisms may be necessary.

 

2.7 Cache Warming and Preloading

Most caching strategies discussed so far load information when an application requests it.

 

This means that when a cache is initially empty, the first requests result in cache misses. The application must retrieve the information from the database and populate the cache before subsequent requests can benefit from caching.

 

For applications with predictable access patterns or strict performance requirements, waiting for users to populate the cache may not be ideal.

 

Cache Warming, also known as Cache Preloading, addresses this problem by proactively loading frequently accessed information into the cache before users request it.

 

How Cache Warming Works?

Consider an e-commerce application that expects a significant increase in traffic during a major shopping event. The application already knows which products are likely to receive the most attention.

 

Instead of waiting for customers to request these products individually, the application can retrieve their information from the database and populate the cache in advance.

 

The process works as follows:

-       Identify frequently accessed or business-critical information.

-       Retrieve the required information from the primary data source.

-       Populate the cache with the retrieved information.

-       Make the application available to users.

-       Serve subsequent requests from the preloaded cache.

 

Example: E-Commerce Product Catalog

Suppose an e-commerce platform expects millions of users during a festival sale. The platform identifies its top 10,000 products based on historical browsing and purchase information. Before the sale begins, a scheduled background job retrieves these products from the database and loads them into Redis.

 

When users start browsing the website, the frequently requested products are already available in the cache. This reduces initial cache misses and prevents a sudden increase in database queries.

 

Common Cache Warming Techniques

a. Scheduled Preloading

A scheduled job periodically loads frequently accessed information into the cache. For example, an application can preload configuration settings every morning before business hours.

 

b. Predictive Preloading

The application uses historical access patterns or predictions to identify information likely to be requested in the future. For example, a shopping platform can preload products expected to become popular during a promotional campaign.

 

c. Startup Cache Warming

An application loads essential information into its cache during startup before accepting user traffic. This is useful for relatively small datasets, such as application configuration and reference information.

 

d. Event-Driven Warming

When an important business event occurs, the application proactively loads relevant information into the cache. For example, when a new promotional campaign is published, its associated product information can be loaded before customers begin accessing it.

 

Advantages

-       Reduces initial cache misses.

-       Improves response times for predictable workloads.

-       Helps prevent sudden database traffic spikes.

-       Provides better performance during planned high-traffic events.

 

Disadvantages

-       Requires additional processing before the information is actually requested.

-       Can consume cache memory for information that may never be accessed.

-       Cache warming jobs may compete with normal database workloads.

-       Predictive preloading can load unnecessary information.

-       Maintaining preloaded information requires appropriate refresh and invalidation mechanisms.

 

When to Use Cache Warming

Cache warming is particularly useful when:

-       Application traffic follows predictable patterns.

-       Certain information is almost guaranteed to be requested.

-       The application experiences sudden traffic spikes.

-       Initial cache misses can significantly affect user experience.

-       Performance requirements are strict.

 

Examples include e-commerce promotions, news websites, frequently accessed dashboards, application startup configuration, and scheduled reporting systems.

 

2.8 Choosing the Right Caching Strategy Based on Workload Characteristics

Selecting an appropriate caching strategy requires understanding how frequently information is accessed, how frequently it changes, how quickly changes must become visible, and what happens if the cache becomes unavailable.

 

There is no universally best caching strategy. Each approach offers different advantages and introduces different trade-offs.

 

Consider the following practical scenarios.

 

Scenario 1: E-Commerce Product Catalog

An e-commerce application maintains millions of product records. Product descriptions, specifications, and category information are frequently accessed by customers but updated relatively infrequently.

 

Recommended strategy: Cache-Aside or Read-Through + Write-Through.

-       Frequently requested product information is stored in Redis.

-       Subsequent requests retrieve product information from the cache.

-       Product updates trigger cache invalidation or coordinated cache updates.

-       Less frequently accessed products are not unnecessarily loaded into memory.

 

This approach reduces database workload while maintaining reasonable data freshness.

 

Scenario 2: Usage Counters and Analytics Aggregation

Consider an application that continuously increments usage counters for customers, products, or services. Persisting every individual increment directly to the database can generate unnecessary database workload.

 

Recommended strategy: Write-Back.

-       Updates are initially recorded in a cache or durable buffering layer.

-       Multiple updates can be combined.

-       A background worker periodically persists aggregated changes to the database.

 

This can significantly reduce database write operations. However, the application must account for durability, retries, and recovery before acknowledging updates.

 

Beyond read and write frequency, consider the following questions:

-       Data freshness: How long can the application tolerate serving stale information?

-       Read/write ratio: Is the application predominantly read-heavy, write-heavy, or mixed?

-       Access frequency: Is the same information requested repeatedly?

-       Write durability: Can the application tolerate losing an update before it reaches the database?

-       Consistency requirements: Must every reader immediately observe a successful update?

-       Cache capacity: Is there sufficient memory to store the expected working set?

-       Failure handling: What happens when the cache or database becomes unavailable?

-       Operational complexity: Can the development and operations teams support the chosen approach?

 

A good caching design balances performance improvements against the additional complexity introduced by maintaining another copy of application data.

 

In summary, Caching strategies determine how information flows between the application, cache, and primary data source.

 

Cache-Aside and Read-Through primarily address how data is retrieved and loaded into the cache, while Write-Through, Write-Around, and Write-Back define how write operations interact with the cache and database.

 

Cache Warming complements these strategies by proactively loading information before it is requested.

 

The right strategy depends on application access patterns, data freshness requirements, write durability, and consistency expectations. In real-world distributed systems, combining multiple caching strategies is often more effective than relying on a single approach.

 

Ultimately, the goal is not simply to maximize the cache hit ratio, but to improve overall system performance without compromising data correctness, reliability, or maintainability.

 

3. Cache Invalidation and Consistency Challenges

Caching significantly improves application performance by reducing repeated database access, avoiding expensive computations, and serving frequently requested information from faster storage.

 

However, caching introduces another important responsibility: ensuring that the information stored in the cache remains consistent with the underlying data source.

 

Consider an e-commerce application that caches product information, including product names, descriptions, and prices.

 

Initially, the product price is ₹1,000 in the database and the same value is stored in Redis. Later, an administrator updates the product price to ₹1,200 in the database. The database now contains ₹1,200, but Redis still contains ₹1,000.

 

If the application retrieves the product information from Redis, customers will continue seeing the old price. This is an example of stale data, where the cached information no longer reflects the latest information available in the source of truth.

 

This problem becomes more challenging when applications use multiple caches, distributed application instances, and geographically separated data centers.

 

In this section, we will explore cache invalidation techniques, consistency challenges, common caching problems, and approaches for maintaining consistent information across distributed systems.

 

3.1 What Is Cache Invalidation and Why Is It Difficult?

Cache invalidation is the process of marking cached information as no longer valid so that applications do not continue using outdated data.

 

When cached information becomes invalid, the application must either remove the corresponding cache entry or ensure that subsequent requests do not use the outdated version. When another request arrives, the application can retrieve the latest available information from the primary data source and populate the cache again.

 

Understanding the Cache Invalidation Problem

Consider an application that retrieves product information using a product ID. Initially, the database and cache contain the same information.

   

After some time, the price of the product changed from 1000 to 1200 in the database, but the application may continue serving the old, cached value. To prevent this, the application needs a cache invalidation mechanism.

 

How Cache Invalidation Works

One common approach is to invalidate the corresponding cache entry whenever the database record is updated.

 

The process works as follows:

-       The application receives a product update request.

-       It updates the product price in the database.

-       After the database update succeeds, it invalidates the corresponding cache entry.

-       The next request checks the cache and finds that the entry is missing.

-       The application retrieves the latest product information from the database.

-       The application stores the updated information in the cache.

 


 


 

This ensures that subsequent requests do not continue using the invalidated entry.

 

Why Is Cache Invalidation Difficult?

Cache invalidation sounds straightforward when an application maintains a single cache entry for a single database record. However, real-world applications often maintain multiple cached representations of the same underlying information.

 

Consider a product whose information is used in several places:

-       Product details API.

-       Product search results.

-       Category listings.

-       Shopping cart calculations.

-       Recommendation services.

-       Analytics dashboards.

 

When the product price changes, invalidating only the product details cache may not be sufficient. Other cached responses may also contain the old price. This introduces a dependency problem.

 

The application must identify every cached result that depends on the information being changed.

 

There are several reasons why this becomes difficult:

 

a. Multiple dependencies

A single database record may contribute to several cached objects, API responses, or computed results.

 

b. Distributed application instances

Multiple application instances may maintain their own local caches. Invalidating one cache does not automatically invalidate the others.

 

c. Concurrent updates

Multiple requests may update the same record simultaneously, resulting in race conditions or stale cache entries being recreated.

 

d. Timing differences

A database update and cache invalidation are separate operations. Failures between these operations can leave stale information.

 

e. Complex data relationships

An update to one database record may affect several aggregated results, reports, and related entities.

 

This is why cache invalidation is often considered one of the most challenging aspects of caching.

 

3.2 Common Cache Invalidation Techniques

There are several approaches to invalidating cached information. The appropriate technique depends on how frequently data changes, how quickly changes must become visible, and how the application manages communication between the database and cache.

 

Let's explore the commonly used approaches.

 

3.2.1 Time-Based Expiration (TTL)

Time-to-Live (TTL) is one of the simplest cache invalidation techniques. Each cached entry is assigned an expiration duration. Once the duration expires, the cache entry is no longer considered valid.

 

Consider an application that caches customer information for 30 minutes. When the customer information is initially retrieved, the application stores it in Redis with a TTL of 1,800 seconds. If the database record changes after 10 minutes, the cache may continue serving the old information until the TTL expires.

 

Once the entry expires, the next request retrieves the information from the database and populates the cache again.

 

Advantages

-       Simple to implement.

-       Supported by most caching systems.

-       Does not require explicit invalidation for every update.

-       Automatically limits how long an entry remains valid.

 

Disadvantages

-       Cached information may remain stale until expiration.

-       Frequently changing data may require very short TTL values.

-       Short TTL values increase database requests.

-       Different cache entries may expire at different times, creating unpredictable cache misses.

 

When to use it?

TTL is useful for information that does not require immediate consistency, such as reference data, application configuration, product catalogs, and frequently accessed read-only information. It is also commonly used as a fallback expiration mechanism even when explicit invalidation is implemented.

 

3.2.2 Explicit Cache Invalidation

Explicit invalidation is an approach where the application directly removes or updates the corresponding cache entry when the underlying data changes.

 

Unlike TTL, which waits for an expiration period, explicit invalidation attempts to make the cache entry unavailable immediately after a successful database update.

 

Consider a customer profile service. When a customer updates their address, the application updates the database and removes the corresponding customer cache entry.

 

There are two common approaches:

a. Delete-based invalidation

The application removes the existing cache entry. The next read causes a cache miss and loads the latest information.

 

b. Update-based invalidation

The application updates the cached value with the newly persisted information. This avoids an additional database read on the next request, but requires careful handling of concurrent updates and cache failures.

 

Advantages

-       Cache entries can be invalidated immediately after successful updates.

-       Avoids waiting for TTL expiration.

-       Provides fine-grained control over cache management.

-       Can reduce stale data for frequently updated records.

 

Disadvantages

-       The application must know which cache entries need invalidation.

-       Cache and database operations can fail independently.

-       Related cached results may be overlooked.

-       Concurrent operations can reintroduce stale values.

 

When to use it?

Explicit invalidation is useful when an application knows exactly which cache entries are affected by a database update. Examples include customer profile updates, product information changes, user preference updates, and application configuration changes.

 

3.2.3 Event-Driven Cache Invalidation

In large distributed applications, the service that updates information may not directly know every cache that depends on that information.

 

For example, a product service may update product information, while several other services maintain their own cached copies. In such situations, event-driven invalidation provides a more scalable approach.

 

Instead of directly communicating with every cache, the application publishes an event whenever relevant information changes. Other services subscribe to these events and invalidate or refresh their corresponding cache entries.

 

How Event-Driven Invalidation Works?

Consider an e-commerce platform with three services:

-       Product Service.

-       Search Service.

-       Recommendation Service.

 

When a product price changes, the Product Service updates the database and publishes a ProductUpdated event. The Search Service and Recommendation Service receive the event and invalidate their corresponding cached information.

 

 

The process works as follows:

-       The Product Service receives a product update request.

-       It updates the product information in the database.

-       It publishes a ProductUpdated event containing the product identifier and relevant metadata.

-       The event is delivered through a messaging platform such as Kafka or RabbitMQ.

-       The Search Service receives the event and invalidates its product cache.

-       The Recommendation Service receives the event and invalidates its corresponding cached information.

-       Subsequent requests retrieve the latest information.

 

A simplified event might look like this:



Advantages

- Supports cache invalidation across multiple services.

- Reduces direct dependencies between services.

- Allows multiple consumers to react independently.

- Supports asynchronous processing.

- Works well with event-driven and microservices architectures.

 

Disadvantages

- Cache invalidation is not necessarily immediate.

- Event delivery can fail or be delayed.

- Duplicate events may be delivered.

- Consumers must handle retries and out-of-order events.

- Additional infrastructure and operational complexity are introduced.

 

An important implementation consideration is the Transactional Outbox Pattern.

 

Suppose a service updates the database successfully but crashes before publishing the corresponding event. The database contains the new information, but downstream caches never receive the invalidation notification. The Transactional Outbox Pattern addresses this by recording the business update and the event in the same database transaction. A separate publisher subsequently delivers the event to the messaging system.

 

This improves the reliability of event publication.

 

When to use it?

Event-driven invalidation is useful in microservices architectures where multiple services maintain independent caches of shared business information.

 

Examples include product catalog platforms, customer data platforms, inventory systems, and distributed analytics applications.

 

3.3 Cache Consistency Between the Cache and the Source of Truth

One of the most important challenges in caching is maintaining consistency between the cached information and the underlying data source.

 

In most applications, the database is considered the source of truth, while the cache maintains a temporary copy of selected information to improve retrieval performance.

 

Whenever information changes in the database, the application must ensure that cached copies do not continue serving outdated information beyond the acceptable freshness period.

 

Understanding Cache Consistency

Consider an application that maintains customer account information. Initially, the database and Redis contain the following information:

 

Customer ID: 101

Account Status: ACTIVE

Version: 1

 

Now suppose the customer account is suspended. The database is updated:

 

Customer ID: 101

Account Status: SUSPENDED

Version: 2

 

However, Redis still contains:

 

Customer ID: 101

Account Status: ACTIVE

Version: 1

 

If the application retrieves account information from Redis, it may incorrectly allow the customer to perform operations that should no longer be permitted. This can become a business correctness or security problem.

 

Types of Cache Consistency

Depending on application requirements, different consistency guarantees can be used.

 

a. Strong Consistency

Strong consistency requires that reads observe the latest successfully committed update according to the system's consistency model.

 

For example, after an account is suspended successfully, subsequent account-status checks must not return the previous active status.

 

This is particularly important for:

-       Financial transactions.

-       Account authorization.

-       Payment processing.

-       Inventory reservation.

-       Critical business configuration.

 

Caching data with strong consistency requirements is challenging because a cache and database are generally separate systems.

 

One approach is to bypass the cache for critical reads and retrieve the information directly from the authoritative data source.

 

Another approach is to use carefully coordinated cache updates, version checks, and consistency controls.


 

 

b. Eventual Consistency

Eventual consistency allows cached information to remain temporarily outdated after an update.

 

However, provided that updates and invalidation events are successfully processed and no newer update supersedes them, the cache eventually converges to the latest committed state.

 

For example, a product description might take a few seconds to become consistent across all application instances.

 

This may be acceptable for product catalog information, recommendation results, and certain analytics dashboards.

 

c. Read-Your-Writes Consistency

Read-your-writes consistency ensures that a user can observe their own successful updates when they subsequently read the same information.

 

Consider a customer updating their profile picture. After the update succeeds, the same customer should see the new picture rather than an older cached version.

 

Other users may temporarily see the previous version, depending on the consistency guarantees.

 

This can be implemented using mechanisms such as:

-       Updating or invalidating the user's cache after a successful write.

-       Routing subsequent reads to an authoritative source.

-       Using version numbers to prevent reads from returning older data.

 

3.4 Cache Stampede, Cache Penetration, and Cache Avalanche

Apart from stale data and invalidation problems, caching systems can experience several operational issues that affect application availability and performance.

 

Three commonly discussed problems are:

-       Cache stampede.

-       Cache penetration.

-       Cache avalanche.

 

Although their symptoms may appear similar, their causes and solutions are different.

 

3.4.1 Cache Stampede

A cache stampede occurs when a frequently accessed cache entry expires or becomes unavailable, causing many concurrent requests to retrieve the same information from the underlying data source simultaneously. This can create a sudden increase in database workload.

 

Consider an application that caches a popular product's information for 30 minutes. During this period, thousands of requests are served from Redis.

 

When the cache entry expires, multiple application requests arrive almost simultaneously. Since the information is no longer available, all these requests experience a cache miss. Each request independently queries the database to retrieve the same product information.

 

The database suddenly receives thousands of identical queries, even though a single query would have been sufficient to populate the cache. This behavior is also commonly called the Thundering Herd Problem.

 

Example

Suppose:

-       5,000 requests arrive for a popular product.

-       The product cache entry expires.

-       All 5,000 requests experience a cache miss.

-       All 5,000 requests query the database.

 

Instead of processing one query and reusing its result, the database processes thousands of duplicate queries. This can overload the database and increase response times across the application.

 

How to prevent cache stampede?

Several techniques can reduce this problem.

 

a. Request Coalescing / Single-Flight

Allow only one request to retrieve missing information from the database while other requests wait for that result.

 

For example:

 

Request 1 ──┐
Request 2 ──┤
Request 3 ──┼──> Single Loader ──> Database
Request 4 ──┤         |
Request 5 ──┘         v
                   Populate Cache
                        |
                        v
                  Share Result
   

Instead of executing five database queries, the application executes one query and shares its result with all waiting requests.

 

This can be implemented using local synchronization mechanisms or distributed coordination, depending on the architecture.

 

b. Distributed Locking

When multiple application instances share a distributed cache, a distributed lock can ensure that only one instance performs the expensive cache refresh operation. Other instances wait briefly, retry the cache lookup, or use an existing acceptable stale value.

 

c. TTL Jitter

Instead of assigning exactly the same TTL to many cache entries, introduce a random variation in expiration times.

 

For example:

Product A: 30 minutes

Product B: 32 minutes

Product C: 28 minutes

Product D: 31 minutes

 

This reduces the possibility of many entries expiring simultaneously. TTL jitter is particularly useful when large numbers of cache entries are populated together.

 

d. Stale-While-Revalidate

Allow the application to serve an older cached value temporarily while refreshing the entry in the background. This avoids forcing every request to wait for the database refresh.

 

It is suitable only when serving slightly stale information is acceptable.

 

3.4.2 Cache Penetration

Cache penetration occurs when an application repeatedly receives requests for information that does not exist in the underlying data source. Because the requested information does not exist, it cannot be populated into the cache as a normal data record.

 

Consequently, every request results in a cache miss and reaches the database. Consider an application that retrieves customer information using a customer ID.

 

An attacker or malfunctioning client repeatedly sends requests using nonexistent customer IDs.

 

For example:

customer:999999

customer:888888

customer:777777

customer:666666

 

The cache does not contain these records, and the database also returns no results. Every request reaches the database.

 

This can generate unnecessary database traffic and potentially become a denial-of-service risk.

 

How to prevent cache penetration?

a. Cache Negative Results

Instead of caching only existing records, the application can temporarily cache the fact that a requested record does not exist.

 

For example:

Cache Key: customer:999999

Cache Value: NOT_FOUND

TTL: 60 seconds

 

When the same customer ID is requested again within the expiration period, the application returns the cached negative result without querying the database.

 

Negative caching should use a relatively short TTL because a record that does not exist now may be created later.

 

b. Bloom Filters

A Bloom filter is a space-efficient probabilistic data structure used to test whether an element might exist in a set.

 

Before querying the database, the application checks whether the requested identifier might exist.

 

There are two possible outcomes:

-       If the Bloom filter says the identifier definitely does not exist, the application can reject the request without querying the database.

-       If the Bloom filter says the identifier might exist, the application continues with the normal cache and database lookup.

A Bloom filter can produce false positives, meaning it may indicate that an element exists when it does not.

 

However, a correctly implemented standard Bloom filter does not produce false negatives for elements that have been inserted and not subsequently removed or otherwise invalidated.

 

This makes it useful for filtering large numbers of nonexistent identifiers.

 

c. Input Validation and Rate Limiting

Applications should validate incoming identifiers, reject malformed requests, and apply rate limits to prevent abusive traffic. These techniques do not replace caching mechanisms but help reduce unnecessary backend requests.

 

3.4.3 Cache Avalanche

A cache avalanche occurs when a large number of cached entries expire or become unavailable around the same time.

 

Unlike cache stampede, which commonly involves many requests for the same expired entry, a cache avalanche can affect many different entries simultaneously.

 

Consider an application that starts at 9:00 AM and loads 100,000 records into Redis. Suppose every entry is assigned a TTL of exactly one hour. At approximately 10:00 AM, a large number of entries expire together.

 

Incoming requests for these records generate cache misses, causing a sudden increase in database traffic.

 

A cache avalanche can also occur when the entire cache cluster becomes unavailable due to a restart, infrastructure failure, or network problem. In such situations, application instances may simultaneously fall back to the database.

 

How to prevent cache avalanche?

a. TTL Randomization

Assign different expiration times to cache entries rather than using identical TTL values.

 

For example, instead of assigning exactly 60 minutes to every entry, use a randomized duration between 50 and 70 minutes. This spreads cache expiration across a longer period.

 

b. Cache High Availability

Deploy cache clusters with appropriate replication, failover, and recovery mechanisms to reduce the likelihood of a complete cache outage.

 

c. Rate Limiting and Load Shedding

When the database experiences excessive load, applications can limit incoming requests or reject lower-priority requests to protect critical operations.

 

d. Controlled Cache Warming

After a cache restart or recovery, gradually repopulate frequently accessed information instead of loading everything simultaneously.

 

e. Circuit Breakers and Database Protection

Circuit breakers and concurrency limits can prevent application instances from overwhelming an already struggling database.

 

Comparing the Three Problems

Problem

Primary cause

Typical symptom

Common solution

Cache Stampede

One popular key expires and receives concurrent requests

Duplicate database queries for the same key

Single-flight, locking, stale-while-revalidate

 

Cache Penetration

Requests target nonexistent data

Repeated cache misses for invalid keys

Negative caching, Bloom filters

Cache Avalanche

Many keys expire together or cache becomes unavailable

Sudden increase in database traffic

TTL jitter, high availability, controlled warming

 

Understanding the difference is important because applying the wrong mitigation technique may not address the underlying problem.

 

3.5 Race Conditions and Concurrent Cache Updates

In distributed applications, multiple requests can access and modify the same cached information simultaneously.

 

When these operations are not properly coordinated, the cache may end up storing an older value even though a newer value has already been persisted in the database.

 

This is known as a race condition. Race conditions are particularly common in Cache-Aside implementations because database updates and cache operations are separate actions.

 

Understanding a Cache Update Race Condition

Consider a customer record initially containing:

 

Database: Customer City = Bangalore

Cache:    Customer City = Bangalore

 

Two requests arrive simultaneously:

- Request A updates the customer's city to Hyderabad.

- Request B reads the customer information.

 

The following sequence can occur:

-       Request B checks Redis and finds a cache miss because the entry was previously invalidated or expired.

-       Request B queries the database and reads the old value: Bangalore.

-       Request A updates the database to Hyderabad.

-       Request A invalidates the cache.

-       Request B stores its previously retrieved value, Bangalore, in Redis.

-       Subsequent requests retrieve Bangalore from Redis.

 

The database contains Hyderabad, but the cache contains Bangalore.

     

This is particularly dangerous because the application appears to have performed the correct invalidation operation, but a concurrent request reintroduced stale information immediately afterward.

 

How to Prevent Race Conditions?

Several techniques can help reduce the likelihood of stale cache updates.

 

a. Version-Based Updates

Associate a version number with each cached record. Before updating the cache, compare the version of the retrieved information with the currently stored version.

 

Reject an update if it would replace a newer version with an older one.

 

For example:

Existing cache:

Customer 101, Version 5

 

Incoming update:

Customer 101, Version 4

 

Result:

Reject the incoming update.

 

This prevents older data from overwriting a newer cached version, provided version comparisons and updates are performed atomically.

 

b. Atomic Cache Operations

Use atomic operations supported by the caching system.

 

For example, Redis supports commands and scripting mechanisms that allow conditional updates to be performed atomically.

 

A Lua script can compare versions and update the cache only when the incoming version is newer.

 

c. Distributed Locking

A distributed lock can coordinate concurrent operations involving the same cache key. Only one operation is allowed to perform the protected update at a time.

 

However, locking introduces additional complexity, including lock expiration, ownership, failure recovery, and deadlock prevention.

 

d. Write Ordering and Coordination

Applications can coordinate database updates and cache invalidation so that older reads cannot overwrite newer values.

 

For particularly important data, the application may bypass the cache and read directly from the authoritative source.

 

Concurrent Cache Updates in Multi-Instance Applications

Consider an application running on three instances, all accessing the same Redis cluster.

 

             Application
                  |
        +---------+---------+
        |         |         |
       App 1     App 2     App 3
        |         |         |
        +---------+---------+
                  |
                 Redis
                  |
               Database
   

If two application instances attempt to update the same customer record simultaneously, the application must ensure that the final cache value corresponds to the latest accepted database update.

 

A simple sequence of GET, followed by a comparison, followed by SET is not sufficient because another instance may modify the value between those operations.

 

Atomic compare-and-set operations, version checks, and appropriate concurrency controls are important in these situations.

 

3.6 Cache Invalidation Challenges in Distributed Systems

Cache invalidation becomes significantly more complicated when an application runs across multiple services, application instances, and geographical regions.

 

In a simple application, there may be only one application instance and one cache. When information changes, the application can invalidate the corresponding cache entry directly.

 

However, distributed applications often maintain multiple copies of the same information across different services and infrastructure components.

 

Understanding Distributed Cache Invalidation

Consider an e-commerce platform consisting of multiple microservices:

-       Product Service manages product information.

-       Search Service provides product search functionality.

-       Recommendation Service generates product recommendations.

-       Inventory Service manages product availability.

-       Pricing Service manages product prices.

 

Each service may maintain its own cache to improve performance. When a product price changes, the Pricing Service updates its database. However, the same product information may also exist in the caches maintained by the Search and Recommendation services.

 

Invalidating the cache in the Pricing Service alone does not guarantee that other services will stop serving outdated information.

 

This introduces several challenges.

 

3.6.1 Cache Invalidation Across Multiple Services

Each service may maintain independent cached copies of shared business information. When the underlying information changes, every dependent service must be notified.

 

For example:

Product Price Updated
         |
         v
    Pricing Service
         |
         v
      Database
         |
         v
   Publish Event
         |
         v
     Event Bus
      /      \
     v        v
 Search     Recommendation
 Service       Service
     |            |
     v            v
 Invalidate    Invalidate
 Cache         Cache

Event-driven invalidation can help coordinate these updates without requiring the Pricing Service to communicate directly with every dependent service. However, event delivery delays, duplicate messages, and failed consumers must be handled.

 

3.6.2 Network Failures and Communication Delays

Distributed systems depend on network communication between application instances, caches, databases, and messaging systems.

 

Suppose a service successfully updates its database but cannot communicate with Redis because of a network interruption.

 

The database contains the latest information, but the cache may still contain the previous value.

 

Similarly, an invalidation event may be delayed because a messaging consumer is temporarily unavailable.

 

Applications must therefore account for:

-       Temporary network failures.

-       Unavailable cache nodes.

-       Delayed event delivery.

-       Failed invalidation requests.

-       Automatic retry and recovery.

 

A common approach is to combine explicit invalidation or event-driven invalidation with TTL as a fallback mechanism. Even if an invalidation event is lost or delayed, the cache entry will eventually expire.

 

However, TTL is not a substitute for immediate invalidation when strict freshness is required.

 

3.6.3 Out-of-Order Events

In distributed systems, events may not always be processed in the same order in which they were generated.

 

Consider the following sequence:

-       Product price changes from ₹1,000 to ₹1,200.

-       An event is published with version 2.

-       Product price changes again from ₹1,200 to ₹1,500.

-       Another event is published with version 3.

 

Suppose the consumer processes version 3 first and version 2 afterward. If the consumer blindly applies every event, the older information may overwrite the newer information.

 

The resulting cache could contain ₹1,200 even though the database contains ₹1,500. To address this, applications can include version numbers or sequence identifiers in events.

 

{
  "eventType": "ProductUpdated",
  "productId": 101,
  "price": 1500,
  "version": 3
}

   

The consumer checks the incoming version before updating its cached information. Older events are ignored when a newer version has already been processed. For invalidation-only events, consumers can simply invalidate the affected key.

3.6.4 Cache Failure and Recovery

Distributed cache systems are generally designed for high availability, but failures can still occur.

 

For example, a Redis cluster may experience:

-       Node failures.

-       Network partitions.

-       Memory exhaustion.

-       Failover events.

-       Temporary unavailability during maintenance.

 

If the cache becomes unavailable, applications may attempt to retrieve everything directly from the database. This can significantly increase database traffic.

 

Therefore, distributed cache designs should consider:

-       Cache replication and failover.

-       Connection timeouts.

-       Retry limits.

-       Circuit breakers.

-       Database connection limits.

-       Controlled fallback behavior.

-       Cache recovery and warming.

 

A cache failure should not automatically become a database failure.

 

3.6.5 Cache Invalidation and the CAP Trade-Off

Distributed caching also involves trade-offs between consistency and availability during network partitions.

 

For example, consider two geographical regions maintaining separate copies of customer information. If communication between the regions becomes unavailable, each region may be unable to determine whether the other region has processed a newer update.

 

The system must decide whether to continue serving potentially stale information or reject certain requests until consistency can be restored. For noncritical information, continuing to serve slightly stale data may be acceptable. For critical information, such as account authorization or payment status, refusing to serve an uncertain cached value may be the safer choice.

 

This illustrates why distributed caching decisions must be aligned with the application's consistency and availability requirements.

3.7 Multi-Level Cache Invalidation and Maintaining Consistency Across Nodes

Modern applications frequently use multiple caching layers rather than relying on a single cache.

 

For example, an application may use:

-       An in-memory cache inside each application instance.

-       A distributed cache such as Redis.

-       A database's internal buffer cache.

-       A CDN or HTTP cache for responses delivered to clients.

 

Each layer improves performance at a different level. However, maintaining consistency across these layers introduces another challenge: invalidating cached information at every relevant level whenever the underlying data changes.

 

Understanding Multi-Level Caching

Consider an application deployed across three application instances. Each instance maintains its own local in-memory cache, while all instances share a Redis cluster. The database acts as the source of truth.

 

The architecture can be represented as:

 

              Client Requests
                     |
          +----------+----------+
          |          |          |
         App 1      App 2      App 3
          |          |          |
       L1 Cache   L1 Cache   L1 Cache
          |          |          |
          +----------+----------+
                     |
                  L2 Cache
                   Redis
                     |
                  Database

   

Here:

-       L1 Cache: Local in-memory cache maintained by each application instance.

-       L2 Cache: Shared distributed cache accessible by multiple application instances.

-       Database: Primary data source and source of truth.

 

When an application receives a request, it first checks its local L1 cache. If the information is unavailable, it checks Redis. If the information is missing from Redis, the application retrieves it from the database and populates the appropriate cache layers. This reduces repeated network communication with Redis and the database.

 

The Multi-Level Invalidation Problem

Suppose customer information is cached in all three application instances and Redis.

 

Initially:

 

Database: Bangalore

App 1 L1: Bangalore
App 2 L1: Bangalore
App 3 L1: Bangalore

Redis L2: Bangalore

Now a request updates the customer's city to Hyderabad. The application updates the database and invalidates the Redis entry. However, what happens to the local L1 caches?

 

If they are not invalidated, the application instances may continue serving Bangalore even though Redis and the database no longer contain that value.

 

This demonstrates an important principle: Invalidating a shared distributed cache does not automatically invalidate local caches maintained by individual application instances.

 

Approaches to Maintaining Multi-Level Cache Consistency

Several approaches can help coordinate invalidation across multiple cache layers.

 

a. Publish Invalidation Events

Whenever information changes, the application publishes an invalidation event. All application instances subscribe to the event and remove the corresponding local cache entry.

 

For example:

 

Customer Updated
       |
       v
    Database
       |
       v
 Publish Invalidation Event
       |
       v
     Message Bus
       |
   +---+---+
   |   |   |
   v   v   v
 App1 App2 App3
   |   |   |
   v   v   v
 Clear Local L1 Caches

   

This allows multiple application instances to invalidate their local caches independently. Redis can also be invalidated through the same event-processing mechanism.

 

b. Use Short TTL for Local Caches

Local in-memory caches can have shorter expiration periods than distributed caches. For example:

Cache layer

Illustrative TTL

Application L1 cache

30 seconds

Distributed L2 cache

10 minutes

 

Even if an invalidation event is missed, the local cache will eventually expire. However, this approach only bounds the stale-data window; it does not provide immediate consistency.

 

c. CDN and Browser Cache Invalidation

Multi-level caching is not limited to application instances and Redis. Web applications may also cache information in CDNs and browsers.

 

Consider an application that updates a product image. The new image is available on the origin server, but the CDN and browser may continue serving the previously cached image.

 

HTTP caching mechanisms provide several approaches:

-       CDN cache purge to remove cached resources from edge locations.

-       Versioned URLs to reference updated static resources.

-       Cache-Control headers to control browser caching.

-       ETag and conditional requests to validate cached resources.

-       Short expiration periods for frequently changing resources.

 

For example, instead of overwriting /images/product-101.jpg, the application can publish a new version: /images/product-101-v2.jpg. Since the URL has changed, browsers and CDNs treat it as a different resource.

 

This technique is commonly known as cache busting and is widely used for static assets such as JavaScript, CSS, and images.

 

3.8 Best Practices for Building Reliable Cache Invalidation Mechanisms

After understanding the different invalidation techniques and distributed caching challenges, it is useful to consolidate some practical design principles. The following practices help build more reliable caching implementations.

 

a. Define Data Freshness Requirements

Not all cached information needs the same freshness guarantee.

 

For example, application configuration may tolerate a few minutes of delay, while account authorization information may require much stricter consistency.

 

Define freshness requirements separately for each category of data.

 

b. Combine Explicit Invalidation with TTL

Explicit invalidation helps remove outdated information immediately after an update. TTL provides a fallback when invalidation fails or is delayed.

 

Using both mechanisms can reduce the risk of stale entries remaining indefinitely.

 

c. Make Invalidation Operations Idempotent

An invalidation operation should be safe to execute multiple times.

 

For example, deleting the same Redis key multiple times should not cause an error that prevents further processing.

 

This is important when using asynchronous messaging systems that may deliver duplicate events.

 

d. Use Version Numbers for Concurrent Updates

Version numbers help identify stale updates and prevent older information from replacing newer cached values. This is particularly useful when multiple application instances or event consumers update the same cache.

 

e. Handle Cache Failures Gracefully

Applications should define what happens when Redis or another caching system becomes unavailable.

 

Depending on the business requirement, the application may:

-       Fall back to the database.

-       Serve an acceptable stale value.

-       Reject noncritical requests temporarily.

-       Apply concurrency limits to protect the database.

 

f. Prevent Cache Stampedes

Use request coalescing, TTL jitter, distributed coordination, or stale-while-revalidate mechanisms to avoid sending large numbers of duplicate requests to the database.

 

g. Monitor Cache Performance and Consistency

Monitoring should cover more than just the cache hit ratio.

 

Important metrics include:

-       Cache hit and miss rates.

-       Cache lookup latency.

-       Cache eviction rate.

-       Cache memory utilization.

-       Cache entry expiration rate.

-       Database load during cache misses.

-       Invalidation event processing delay.

-       Failed invalidation events.

-       Cache refresh failures.

 

These metrics help identify performance degradation and consistency problems before they significantly affect users.

 

Summary

Caching is a fundamental technique for improving application performance, reducing latency, and minimizing the workload on databases and backend services. By keeping frequently accessed data closer to the application, caching helps systems respond faster and handle higher traffic without continuously relying on expensive data sources. However, caching is not simply about storing data temporarily; it requires careful decisions about what to cache, where to cache it, how long to retain it, and how to access and update it efficiently.

 

Different caching strategies, such as Cache-Aside, Read-Through, Write-Through, Write-Around, and Write-Back, address different application access patterns and performance requirements. Each strategy introduces its own trade-offs in terms of latency, data freshness, write performance, and complexity. Similarly, cache invalidation and consistency become increasingly challenging as applications scale across multiple services, instances, and caching layers. Techniques such as TTL, explicit invalidation, event-driven updates, versioning, and protection against cache stampedes help manage these challenges.

 

There is no universally best caching strategy. The right approach depends on the application's workload, data access patterns, consistency requirements, freshness expectations, and system architecture. A well-designed caching solution balances performance with correctness, reliability, and operational complexity. Ultimately, the goal is not just to make applications faster, but to build systems that remain responsive, scalable, and predictable even under heavy workloads and changing data.


                                                                                System Design Questions