When caches go wrong

Topic 4 of 9 in Week 4: Caching, queues and content delivery10 min readIntermediateFree course

Overview

Caches make systems fast, which means the systems quietly come to depend on them. A database sized for a 95% hit rate can’t survive a sudden 0% hit rate. This lesson covers the classic ways caches fail and the standard defences, a favourite topic for interview deep dives.

Stampede (thundering herd)

Cache stampede. Without protection, a hot key expires, four concurrent requests all miss and all query the database, which becomes overloaded. With single flight, the requests go to the cache, which takes one lock: one request refreshes the value with a single database query while the others wait or get the stale value. Also: refresh hot keys early, add random jitter to TTLs, and serve stale data while revalidating.

A popular key expires. In the next few milliseconds thousands of requests miss, and every one of them runs the same expensive query. The database slows down, queries take longer, more requests pile up, and the system can collapse.

Defences:

  • Single flight (request coalescing): only one request per key rebuilds the value; the rest wait for it. Implement with a per-key lock in Redis (SET lock:key 1 NX PX 5000) or in-process.
  • Serve stale while revalidating: keep the old value slightly past expiry; return it immediately while one background request refreshes it.
  • Refresh ahead: refresh hot keys before they expire, either on a schedule or when a read sees the TTL is nearly up (probabilistic early expiration).
  • TTL jitter: so related keys don’t expire in the same instant.

Penetration

Requests for keys that don’t exist always miss the cache and always hit the database. It can be accidental (a client bug looping on a deleted ID) or an attack (random IDs).

Defences:

  • Negative caching: cache “not found” for a short time.
  • Input validation: reject IDs that can’t be valid before touching anything.
  • Bloom filter: a compact in-memory structure that can say “definitely doesn’t exist” for keys not in the set, so those requests skip the database.
  • Rate limiting per client.

Hot keys

A cache cluster spreads keys across nodes, but a single key lives on a single node. When one key gets a huge share of traffic (a celebrity’s profile, a live match score, the home page), that node saturates its CPU or network while others idle.

Defences:

  • Local caching of the hot key in each app server’s memory for a second or two, so the shared cache sees one read per server rather than one per request.
  • Replicas: read hot keys from cache replicas as well as the primary.
  • Key splitting: store copies under score:final#1 … score:final#10 and pick one at random on read.
  • Push it to the edge: a CDN with a short max-age absorbs most of the traffic.

Avalanche

Many keys become unavailable at once:

  • Mass expiry: a cache warmed in one batch with identical TTLs expires in one batch.
  • Cache failure: a cache node or the whole cluster goes down, or is restarted empty.

Defences:

  • jitter TTLs,
  • replicate cache shards with automatic failover, and spread nodes across zones,
  • protect the database: connection limits, rate limits, load shedding and circuit breakers (week 6), so it degrades instead of collapsing,
  • a local cache layer as a second line.

Cold start

A new cache, or one restarted after a deploy or failure, is empty. Every request misses until it warms up. Defences:

  • Warm the cache before sending traffic (preload the most popular keys),
  • ramp traffic up gradually to new cache nodes,
  • use consistent hashing so adding a node invalidates only a small share of keys (week 3).

Consistency bugs

Caches also fail by being wrong:

  • a missed invalidation leaves stale data indefinitely (so always keep a TTL),
  • a race re-caches an old value after a delete,
  • different servers’ local caches disagree.

For data where staleness is harmful, read from the source at the moment it matters (checkout, payment), and use the cache only for browsing.

In an interview

When you add a cache for a hot path, pre-empt the follow-up: “For the hot keys, like a viral post, I’d use single-flight refresh and a one-second local cache on each server so Redis doesn’t become a hotspot. If Redis fails, the database is protected by a circuit breaker and rate limits, and we serve slightly stale data from the local cache.”

Recap

Caches can fail by stampede (many rebuilds of one key), penetration (lookups for missing keys), hot keys (one node overloaded), avalanche (many keys or nodes lost at once) and cold starts. Single flight, serve-stale, refresh ahead, negative caching, local caches, TTL jitter, replication and database protection are the standard defences. Design so that a cache failure makes the system slower, not dead.

Exercise

Survive the big match

A sports app caches the live score page for each match in Redis with a 5-second TTL. During a cup final, 2 million users refresh the same match page. Every 5 seconds the database CPU spikes to 100% and some requests time out. Then one Redis node fails and the whole site slows down. (a) Name the two failure modes. (b) Propose at least four changes that would prevent them.

Text
(a) Failure modes:

(b) Changes:
1.
2.
3.
4.

Summary

  • A stampede happens when a popular key expires and many requests rebuild it at once; fix with locks (single flight), early refresh or serving stale data.
  • Penetration is repeated lookups for keys that don't exist; cache 'not found' results and validate inputs, or use a Bloom filter.
  • A hot key overloads one cache node; replicate it, cache it locally, or split it.
  • An avalanche is many keys expiring or a cache cluster failing at once; add TTL jitter, replicate caches and protect the database.
  • Design the database to survive a cold or failed cache, or limit traffic until the cache warms up.