Caching in Distributed Systems
What is Caching?
Caching is the process of storing copies of frequently accessed data or expensive computation results in a fast temporary store (typically in memory). When a request arrives, the system checks the cache first: on a cache hit, it returns the value in sub-millisecond time without touching the primary database; on a cache miss, it fetches from the source, stores a copy in the cache for future reads, and returns it to the client.
Benefits of Caching
In distributed systems, caching plays a crucial role in reducing latency, improving throughput, and ensuring scalability. Let’s break down these benefits:
-
Reduced Latency: By storing frequently accessed data closer to the user, caches reduce the time it takes to retrieve that data. This is particularly important in distributed systems, where data might be spread across multiple nodes or even geographic locations.
-
Improved Throughput: Caching reduces the load on primary data sources, such as databases. By handling more requests directly from the cache, the system can process a higher volume of requests in the same period, leading to better overall performance.
-
Scalability: Distributed systems often need to scale to handle growing amounts of data and user requests. Caching helps manage this by preventing bottlenecks that can occur when too many requests are sent to a single source. By distributing the load across cache layers, systems can scale more effectively.
Types of Caching
-
Client-Side Caching: This type of caching happens on the user’s device or close to the user. It is often implemented in web browsers or applications to store data that doesn’t change frequently, such as images, scripts, or web pages.
-
Server-Side Caching: In this approach, caches are placed on the server side, closer to the data sources like databases or API servers. Examples include database query caching and application-level caching where computed results are stored.
-
Edge Caching: Edge caching is implemented in Content Delivery Networks (CDNs). Data is cached at the “edge” of the network, closer to the end-users. This is particularly useful for static content and is a common strategy for improving the performance of globally distributed systems.
-
Distributed Caching: This involves using a distributed cache that spans multiple servers or nodes. Data is cached across these nodes, ensuring that no single point of failure exists and that the cache itself is scalable. Technologies like Redis, Memcached, and Apache Ignite are popular choices for distributed caching — and also let stateless servers behind a load balancer share session and lookup state without sticky sessions.
Caching Patterns
-
Cache-Aside (Lazy Loading): The application checks the cache first, falls back to the database on a miss, and writes the result into the cache. Only data that is actually requested gets cached, and a cache outage degrades gracefully to database reads.
-
Write-Through Caching: Every write goes through the cache and synchronously updates the underlying database before returning. This keeps the cache and database closely in sync, at the cost of higher write latency.
-
Write-Behind (Write-Back) Caching: Data is written to the cache first and acknowledged immediately, then flushed asynchronously to the database in batches. This maximizes write throughput (and removes temporal coupling to slow disk writes) but risks losing buffered writes if the cache node crashes before flushing.
| Pattern | Read Behavior | Write Latency | Consistency | Crash Risk |
|---|---|---|---|---|
| Cache-Aside | App checks cache, loads DB on miss | Fast (writes go to DB + invalidate) | Eventually consistent until TTL/invalidation | Low — DB is source of truth |
| Write-Through | High hit rate for recently written keys | Higher (sync write to cache + DB) | High — cache stays fresh on writes | Low — DB updated before ack |
| Write-Behind | High hit rate | Lowest (returns after cache write) | Eventually consistent during flush lag | Higher — un-flushed writes lost on node crash |
Cache Invalidation
-
Time-to-Live (TTL) Invalidation
Time-to-Live is a common and straightforward cache invalidation strategy. Each cached item is associated with a TTL value, which is a predefined period after which the cache entry is automatically considered stale and removed or refreshed. For example, if a web page’s TTL is set to 60 seconds, the cache will invalidate that page’s data after 60 seconds, ensuring that fresh data is loaded for subsequent requests.
-
Write-Through Caching with Invalidation
In write-through caching, every update to the cache also triggers an update to the underlying data store, ensuring that the cache and the data store are always in sync. Cache invalidation in this context means that any update operation automatically invalidates the corresponding cache entry, ensuring that subsequent reads will retrieve the latest data.
-
Event-Driven Invalidation
In event-driven invalidation, cache invalidation is triggered by specific event messages (or CDC document messages) that indicate changes in the underlying data. For instance, if a product’s price is updated in a database, an event is emitted to invalidate or refresh the corresponding cache entry. This approach works well when changes are infrequent but need quick reflection in the cache.
-
Manual Invalidation
Manual invalidation involves explicitly removing or updating cache entries based on specific triggers or actions initiated by users or administrators. This method is typically used in scenarios where cache updates are infrequent or where automated invalidation strategies are not feasible.
Cache Eviction
When the cache reaches its storage limit, some data must be evicted to make room for new data.
-
Least Recently Used (LRU)
LRU is one of the most popular cache eviction strategies. It works on the principle that data that hasn’t been accessed recently is less likely to be needed in the near future. When the cache reaches its capacity, LRU evicts the least recently used data, making space for new entries.
-
Most Recently Used (MRU)
MRU is the opposite of LRU. It assumes that the most recently used data is less likely to be accessed again soon. MRU evicts the most recently used data first, making room for new entries.
-
Least Frequently Used (LFU)
LFU keeps track of how often each data entry in the cache is accessed. When eviction is needed, the data that has been accessed the least frequently is removed first.
-
First In, First Out (FIFO)
FIFO evicts the oldest data first, regardless of how frequently it has been accessed. This method operates on a simple queue basis, where the first item added to the cache is the first one to be evicted when space is needed.
-
Random Replacement (RR)
As the name suggests, RR evicts data at random when the cache is full. While this might seem inefficient, in some cases, it can perform surprisingly well, particularly when there is no clear access pattern.
Challenges and Considerations
While caching can significantly improve the performance of distributed systems, it also introduces challenges:
-
Consistency: Ensuring that cached data stays fresh relative to the source of truth is an inherent availability-vs-consistency trade-off (closely related to the CAP theorem).
-
Cache Coherency: In distributed caches, coherency involves keeping different cache nodes in sync. Without proper management, different nodes might return different data for the same query.
-
Cache Stampede (Thundering Herd) & Cache Penetration: When a hot key expires under heavy load, thousands of concurrent requests can miss simultaneously and hammer the primary database. Mitigate stampedes with request coalescing (singleflight locks) and jittered TTLs; mitigate penetration (queries for non-existent keys) with Bloom filters or short negative caching.
-
Scalability of the Cache Itself: As the system grows, the cache system must also scale to handle the increasing volume of data and requests. This often requires sharding and replication with consistent hashing.
Key Takeaways
- Caching in distributed systems reduces latency and improves throughput by storing frequently accessed data closer to users.
- Different types of caching, such as client-side, server-side, edge, and distributed caching, serve various use cases.
- Choosing the right caching strategy—whether write-through, write-behind, or a combination—is essential for system performance and data consistency.
- Challenges in caching include maintaining consistency, managing cache coherency, and planning for the scalability of the cache system itself.