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-Controlextension, 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.