Course contents

06. Caching Lesson 8 of 8

Cache Stampede

Watch a hot key expire and flood the database, then fix it with request coalescing, TTL jitter and early refresh.

14 minIntermediate7 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • When a hot key expires, every request in the rebuild window misses and repeats the same expensive work.
  • Stampedes show as periodic bursts of database load and timeouts, not a high average.
  • Coalescing merges same-key misses into one rebuild per process; locks or leases make it one per fleet.
  • Keys filled together with one TTL expire together; jitter spreads them out.
  • Refreshing hot keys early, or serving stale while revalidating, means readers never see the miss.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

A cache stampede (also thundering herd or dogpile) happens when a cached value disappears and many requests try to rebuild it at the same time. Each of them misses, each runs the same expensive query or computation, and the backend that the cache was protecting suddenly receives a burst of duplicate work. The trigger can be a hot key expiring, many keys expiring together, an invalidation, or a cold cache after a restart.

Why it exists

Cache aside makes every miss rebuild the value independently. With a few requests per second that is harmless. With hundreds, the number of requests that arrive during the rebuild window is rate × rebuild time: 500 requests per second and a 200 ms query mean about 100 identical queries per expiry. The cache hides the cost of that query most of the time, so the backend is often sized for the average, not for the herd.

How it works

The herd. The key expires. The next request misses and starts the rebuild. Until it finishes and writes the value back, every other request also misses and starts its own rebuild. The backend saturates, requests queue for connections or time out, and the first rebuild to finish refills the cache, after which everything looks healthy again until the next expiry. On a graph: idle, spike, idle, spike, at the TTL’s rhythm (TTL plus rebuild time).

Request coalescing (single-flight). A process keeps a map of keys currently being loaded. A miss for a key already in flight waits for that result instead of starting another load. Go’s singleflight package and the "promise cache" pattern implement this. It is per process: ten servers still send up to ten rebuilds. Fleet-wide alternatives are a short distributed lock (SET key:lock NX PX 5000; losers wait or serve stale), leases from the cache (described for Facebook’s memcache, NSDI 2013), or a single refresher.

TTL jitter. Keys filled at the same time with the same TTL expire at the same time, and because they are refilled together they stay in lockstep. Adding a random component to each TTL (for example 10–20%, or more for large key sets filled at once) spreads their expiries; every refill spreads them further. Jitter does not help a single hot key.

Early refresh. Rebuild a hot key before it expires while readers keep using the cached value:

  • a background refresher that reloads known hot keys on a schedule shorter than the TTL;
  • probabilistic early expiration (XFetch, Vattani et al., VLDB 2015): each reader recomputes early if now − δ·β·ln(random()) ≥ expiry, where δ is the rebuild time; the probability rises as expiry approaches, so usually one reader refreshes first;
  • stale-while-revalidate: keep the old value past its soft TTL, serve it, and let one request refresh it (HTTP standardises this as a Cache-Control extension, RFC 5861).

When to use it

  • Coalescing: always, for any cache-aside read path with expensive misses; it is cheap and local.
  • Jitter: always on TTLs, and especially after cache restarts, deploys or bulk loads that fill many keys at once.
  • Early refresh / stale-while-revalidate: for a small set of very hot or very expensive keys (homepages, configuration, aggregates).
  • Locks or leases: when even one rebuild per server is too many (large fleets, very expensive rebuilds).

When not to

  • Don’t add a distributed lock for cheap rebuilds; the lock round trip can cost more than the query.
  • Don’t serve stale data where staleness is not acceptable (permissions, balances) without a bound.
  • Don’t run a background refresher for long-tail keys; you would refresh data nobody reads.

Trade-offs

Mitigation Removes Cost Limit
Coalescing Duplicate rebuilds per process Waiters are held until the rebuild ends One rebuild per server, not per fleet
Distributed lock / lease Duplicate rebuilds across servers Extra round trip; lock expiry tuning Lock holder crash delays the rebuild
TTL jitter Synchronised expiry of many keys Slightly less predictable freshness Does not help one hot key
Early refresh The miss itself Extra background load Needs to know which keys are hot
Stale-while-revalidate The miss itself Serves slightly older data Needs a soft and a hard TTL
Bigger pool Some timeouts More identical queries in the database Moves the bottleneck into the database

Alternatives

  • No expiry plus explicit invalidation: hot keys only change when written, so they never expire on a timer.
  • Precompute and push: a job writes the homepage into the cache whenever its inputs change.
  • Load shedding and concurrency limits in front of the database, so a herd degrades gracefully instead of exhausting the pool.
  • Request collapsing at the edge: CDNs and reverse proxies can collapse concurrent misses for the same URL (for example nginx proxy_cache_lock).

Failure modes

  • Hot key expiry: the classic herd described above.
  • Cold cache: after a cache restart or failover every key misses at once; jitter cannot help the first wave, so warm critical keys and limit concurrent rebuilds.
  • Invalidation storms: a bulk update deletes many hot keys together and triggers the same burst.
  • Retry amplification: clients retry the timeouts, adding more misses to the next wave.
  • Coalescing pitfalls: a stuck leader holds every waiter; put a timeout on the in-flight load and let waiters fall back.

In production

Wrap cache-aside reads in single-flight from day one. Put jitter on every TTL. Identify the handful of keys whose rebuild is expensive and refresh them early or serve stale while revalidating. Cap concurrent database work so a herd queues instead of collapsing the pool, and do not retry pool timeouts immediately. Alert on database query bursts that line up with TTLs, and on cache hit-ratio dips. Practise the incident in the Failure Lab: Cache Stampede.

Common misconceptions

  • "Our average database load is low, so stampedes are not a problem." Stampedes are bursts; averages hide them.
  • "TTL jitter fixes stampedes." It fixes synchronised expiry of many keys, not a single hot key.
  • "A bigger connection pool fixes it." It lets more duplicates run at once; the database does the same work many times.
  • "Coalescing gives exactly one rebuild." Only per process; a fleet still sends one per server.

Interview angle

When you propose a cache, expect "what happens when a hot key expires?" Explain the herd with numbers (rate × rebuild time), then layer: single-flight per server, a lock or lease for the fleet, jitter for many keys, early refresh or stale-while-revalidate for the hottest ones, and protection for the database during cold starts. Mentioning that retries amplify the problem shows operational experience.

Model assumptions

The simulation is a simplified model, not a benchmark. Users arrive as a Poisson stream and are spread round robin over two API servers (300 workers each) that share one cache. A rebuild is a 200 ms database query (lognormal, cv 0.3) on a pool of 20 connections, about 100 rebuilds per second; waiting more than 300 ms for a connection fails the request. Cache entries live 3 seconds; with jitter, a random extra of up to 100%. The cache starts empty at the beginning of each run, like after a deploy, which is what synchronises the 100 category keys. Coalescing is per API server: concurrent misses for the same key on one server share one query and the others wait for it. The early-refresh Refresher is a scripted illustration; the engine has no background refresher, probabilistic early expiration or stale-while-revalidate. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. One key everybody reads

    Every visitor loads the homepage, which is built by an expensive 200 ms query and cached under a single key for 3 seconds. Two API servers share the cache.

    Almost every read is a hit. But every 3 seconds the key expires, and for the ~200 ms it takes to rebuild it, every request that arrives misses, and each one starts the same query. At 60 requests per second that is a handful of identical queries per expiry: wasteful, but harmless.

    Scene: Users read the homepage through a load balancer and two API servers that share one cache. Every 3 seconds the key expires and a few requests rebuild it with the same 200 ms database query. Nothing fails.

    Key idea: When a hot key expires, every request that arrives before it is rebuilt misses and rebuilds it too.

  2. 2. The herd arrives

    A campaign brings 500 requests per second. Now each expiry lets around 50 requests miss within a few hundred milliseconds, and all of them send the same query to a database with 20 connections. The first 20 run; the rest wait for a connection, and those that wait more than 300 ms fail.

    The pattern is the tell-tale sign of a cache stampede (thundering herd): the database is idle most of the time, then hammered for a moment every 3 seconds or so (the TTL plus the rebuild time), with a burst of timeouts each time. Average load looks fine; P99 does not.

    Scene: At 500 requests per second, each expiry sends dozens of identical queries to the 20-connection database at once. Many wait for a connection and some time out, in bursts every few seconds; between bursts the database is idle.

    Key idea: A stampede is many identical rebuilds at once. It shows up as periodic bursts of database load and timeouts, not as a high average.

  3. 3. One rebuild, everyone waits for it

    We turn on request coalescing (single-flight) in both API servers. When a request misses and the server is already loading that key, it waits for the result instead of sending another query.

    Each expiry now costs at most two queries, one per API server, and the timeouts disappear. The waiting requests are a little slower (they wait for the in-flight rebuild), so P99 still shows a bump. To get down to exactly one query across all servers you need a distributed lock or lease, or a refresher (later in this lesson).

    The same incident is in the Failure Lab: /system-design/failure-lab/cache-stampede.

    Scene: Both API servers coalesce misses: when the homepage key expires, each server sends one query and the other requests wait for it. At most two queries reach the database per expiry and nothing fails.

    Key idea: Coalescing turns N identical rebuilds into one per server; the others wait for its result.

  4. 4. Many keys, one deadline

    Now the site serves 100 category pages at 800 requests per second, each cached for 3 seconds with coalescing still on. Coalescing only merges requests for the same key; it does nothing when many different keys expire together.

    And they do: the cache started empty (as after a deploy or a flush), so all 100 pages were filled within a moment and, with the same TTL, they expire in the same moment, are refilled together, and expire together again. The database sees waves every ~3 seconds, above what 20 connections can serve, and sits idle in between. P95 rises with each wave.

    Scene: Users read 100 different category pages. All keys expire at nearly the same moment every 3 seconds, so the database receives waves of rebuild queries and is idle between them; latency rises during each wave.

    Key idea: Keys filled together with the same TTL expire together: a synchronised stampede across many keys.

  5. 5. Spread the deadlines

    We add TTL jitter: each key lives 3 seconds plus a random extra of up to 100%, so between 3 and 6 seconds. Keys that were filled together now expire at different times, and every refill spreads them further.

    The waves flatten into a steady trickle: the peak rebuild rate roughly halves and P95 drops. (Part of the drop comes from the longer average TTL; most of it from no longer expiring in lockstep.) Jitter is cheap, but note what it does not fix: a single hot key still expires; that is what coalescing is for.

    Scene: Each cache entry now expires at a random time between 3 and 6 seconds. Database rebuilds are spread out evenly instead of arriving in waves, and latency is lower.

    Key idea: Random TTL jitter desynchronises expiry across keys; combine it with coalescing for hot keys.

  6. 6. Refresh before it expires

    The best miss is the one that never happens. With early refresh, a hot key is reloaded before its TTL runs out while readers keep getting the cached value, so the key never goes missing.

    The animation is a scripted illustration (the engine has no refresher): a background Refresher reloads the key at about 80% of its TTL and overwrites the cache entry. Other forms of the same idea: probabilistic early expiration (XFetch: each reader recomputes early with a probability that rises as expiry approaches, so one request usually refreshes first) and stale-while-revalidate (serve the old value and refresh in the background).

    Scene: An illustration of early refresh: a Refresher reads the value from the database and writes it into the cache shortly before the entry would expire, every 2.4 seconds. Readers keep hitting the cache. Live traffic continues with jittered TTLs and coalescing.

    Key idea: Refresh hot keys ahead of expiry, or serve stale while one request revalidates, so readers never see a miss.

  7. 7. Layers of stampede protection

    Stampedes come from many misses for the same work at the same time. Layer the defences: coalesce misses (single-flight per process, a lock or lease across processes), jitter TTLs so keys do not expire together, refresh early or serve stale for the hottest keys, and make sure the database can survive a cold cache (limit concurrent rebuilds, warm critical keys after deploys).

    Don’t add retries: during a stampede each retry is one more miss in the queue. Practise it in the Failure Lab scenario /system-design/failure-lab/cache-stampede.

    Scene: Users read 100 category pages through two coalescing API servers and a cache with jittered TTLs. Rebuilds reach the database steadily and nothing fails.

    Key idea: Coalesce same-key misses, jitter TTLs, refresh hot keys early, and never let retries feed a stampede.