Caching: Patterns, Invalidation and Failure Modes
Cache-aside, write-through and write-behind, TTL and LRU eviction, invalidation on update, and the three classic problems: stampede, penetration and avalanche.
A cache stores the result of an expensive operation in fast storage, usually memory, so that the next request for the same data is served without repeating the work. It is the most common answer to 'this page is slow'.
Adding a cache is easy. Keeping it correct is the real topic: what happens when the underlying data changes, when a popular entry expires, and when the cache itself fails. These notes cover the patterns and the problems.
When a cache helps
A cache is valuable when data is read much more often than it changes, when computing or fetching it is expensive, and when slightly stale data is acceptable for some period. Before adding one, three questions should be answered: how often does the data change, how stale may it be, and what is the expected hit rate?
Caches exist at several layers: the browser, the CDN, the API gateway, an application-level cache such as Redis or Memcached, and the database's own buffer cache. These notes focus on the application-level cache.
Cache-aside (lazy loading)
Cache-aside is the default pattern. The application checks the cache first. If the key is present, that is a cache hit and the value is returned immediately. If it is absent, that is a cache miss: the application reads the database, stores the result in the cache with a TTL, and returns it.
Only data that is actually requested gets cached, and a cache failure does not break the system because the application can still read the database. The costs are that the first request for each key is slow, and that cached data can be stale until it expires or is invalidated.
async function getProduct(id) {
const key = "product:" + id;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // cache hit
const product = await db.products.findById(id); // cache miss
const ttl = 300 + Math.floor(Math.random() * 60); // TTL with jitter
await redis.set(key, JSON.stringify(product), "EX", ttl);
return product;
}
async function updatePrice(id, price) {
await db.products.update(id, { price }); // 1. update the source of truth
await redis.del("product:" + id); // 2. invalidate the cache entry
}Other write patterns
- Read-through: the same as cache-aside, but the cache library itself loads from the database on a miss. Application code is simpler.
- Write-through: every write goes to the cache and the database together. The cache is always fresh, but writes are slower and data that is never read is cached anyway.
- Write-behind (write-back): the write goes to the cache and is flushed to the database asynchronously. Writes are very fast, but data can be lost if the cache fails before the flush. Suitable only for data where that risk is acceptable.
TTL and eviction
Every key should have a time to live (TTL). After the TTL the entry is removed and the next read fetches fresh data. The TTL is the upper bound on staleness: a short TTL gives fresher data and a lower hit rate; a long TTL gives the opposite.
Memory is finite, so when the cache is full it must evict something. The most common policy is LRU (least recently used), which removes the entry that has not been accessed for the longest time, on the assumption that recently used data will be used again. LFU (least frequently used) evicts the entry with the fewest accesses and suits workloads with stable popularity.
Cache invalidation
Suppose a product's price changes in the database but the cache still holds the old price. Waiting for the TTL means users see a wrong price for minutes. The fix is to invalidate on update: after writing to the database, delete the cache key. The next read misses and loads the new value.
Deleting is preferred over updating the cache value. If two updates race, writing values to the cache can leave the older one in place permanently, whereas a delete is safe to repeat. The order also matters: update the database first, then delete the key. A small race window remains, where a concurrent reader re-populates the cache with the old value just after the delete, and the TTL acts as the safety net that bounds how long such an entry can live.
Cache stampede
A very popular key expires. In the same instant thousands of requests miss the cache, and every one of them runs the same expensive query against the database. This is a cache stampede, also called the thundering herd, and it can take the database down.
- Request coalescing: only one request rebuilds the entry (using a lock or a single-flight mechanism); the others wait for its result or are served the previous value.
- TTL jitter: add a random offset to each TTL so that keys created together do not all expire together.
- Refresh ahead: for the hottest keys, refresh in the background shortly before expiry so users never see a miss.
Cache penetration and cache avalanche
Cache penetration happens when requests ask for keys that do not exist. Nothing is ever cached, so every request reaches the database. The defences are to cache the negative result ('not found') with a short TTL, and to place a Bloom filter in front of the cache that rejects IDs that cannot exist.
A cache avalanche happens when a large part of the cache disappears at once, either because many keys share an expiry time or because a cache node fails. The entire read load lands on the database. The defences are TTL jitter, cache replicas with automatic failover, and rate limiting or circuit breaking on the database path so that the system degrades instead of collapsing.
What not to cache carelessly
Some data must be exact at the moment it is used: account balances, inventory during checkout, permissions. Serving a stale value there causes real damage. Such data is either read from the source of truth at the point of decision, or cached with great care and a very short TTL. Cache the product description freely; verify the stock count in the database before confirming the order.
Scaling the cache
A single cache node is limited by its memory. A cache cluster spreads keys over many nodes, usually with consistent hashing so that adding or removing a node moves only a small share of the keys. Each node can have a replica for availability. A useful sizing guideline is that a small part of the data receives most of the traffic, so caching roughly the hottest 20 percent of items is often enough to serve the large majority of reads.
Interview summary
- Identify the read-heavy data and how stale it may be.
- Use the cache-aside pattern with a TTL on every key.
- Evict with LRU when memory is full.
- Invalidate on update: write the database, then delete the key.
- Protect against stampedes with request coalescing and TTL jitter; mention replicas for cache failure.
Summary
A cache trades freshness for speed. Cache-aside with a TTL is the default pattern, LRU handles a full cache, and deleting the key after a database update keeps data correct. A complete answer also covers the failure modes: stampede when a hot key expires, penetration from missing keys, and avalanche when many keys or a node disappear together.
Puneet Tiwari
Full Stack Developer
