LumenForgee

Cache stampedes: why a cache can make an outage worse

A cache is supposed to protect the database. Under the wrong conditions it does the opposite: a popular key expires, hundreds of requests miss at the same moment, and all of them ask the database for the same expensive result. That burst is a cache stampede, and it tends to happen exactly when the system is already busy.

Contents
  1. How a stampede happens
  2. Request coalescing
  3. Refresh before expiry
  4. TTL design and cold starts
  5. Measuring cache health
  6. Invalidation on write
  7. Worked example: taming a catalogue endpoint
  8. Common pitfalls
  9. FAQ
  10. Checklist
  11. Primary sources

Key facts

  • A cache stampede (or thundering herd) occurs when many requests miss the same key at once and all recompute it.
  • Request coalescing lets one request recompute a value while concurrent requests wait for that result.
  • Adding random jitter to time-to-live values prevents many keys from expiring at the same instant.
  • HTTP's stale-while-revalidate (RFC 5861) lets caches serve a stale response while refreshing it in the background.

How a stampede happens

Consider a product listing page whose data takes 400 ms to compute and is cached for five minutes. Under normal load, one request per five minutes pays the cost and everyone else is served from cache. At the moment the key expires, however, every request arriving in the next 400 ms misses. At 500 requests per second, that is 200 concurrent recomputations of the same value.

Those recomputations compete for database connections and CPU, so each one takes longer than 400 ms, so more requests miss in the meantime. The database slows down for unrelated queries too. When the first recomputation finishes and fills the cache, the burst subsides — until the next popular key expires.

The same pattern appears after a deployment that clears an in-process cache, after a cache cluster restart, or when a cache node fails and its keys are redistributed. In each case, the cache's normal hit rate hid how much load the database would face without it.

Request coalescing

The most direct fix is to ensure only one caller recomputes a missing key. Within one process, a single-flight mechanism keeps a map of in-progress computations: the first caller starts the work, later callers for the same key wait on the same result. Across processes, a short-lived lock in the shared cache does the same — the caller that acquires the lock recomputes; the others wait briefly and read the result, or serve a stale value.

  • Give the lock a short expiry so a crashed worker does not block the key forever.
  • Bound how long waiters wait; if the recomputation takes too long, serve stale data or a degraded response rather than piling up requests.
  • Coalesce per key, not globally, so one slow key does not block others.

Refresh before expiry

Coalescing limits the stampede; early refresh prevents the miss altogether. Store the value with its computation time and logical expiry, and let a request that reads it shortly before expiry trigger a background refresh while still returning the cached value. Probabilistic early expiration refines this: each read has a small, increasing chance of refreshing as the expiry approaches, which spreads refreshes over time without coordination.

HTTP caches offer the same idea through Cache-Control: max-age=300, stale-while-revalidate=60. A CDN or reverse proxy serves the stale response for up to 60 seconds after expiry while it revalidates in the background, so users rarely wait for a recomputation.

TTL design and cold starts

Stampede protection techniques
TechniquePreventsNote
Jittered TTLsMany keys expiring togetherAdd, for example, ±10% randomness to each TTL
Stale-while-revalidateUsers waiting for recomputationRequires acceptable staleness
Request coalescingDuplicate recomputationPer key, with bounded waits
Cache warmingCold start after deploy or restartPre-load the hottest keys before taking traffic
Negative cachingRepeated misses for absent dataCache not-found results briefly

Cold starts deserve explicit handling. If an in-process cache is empty after each deploy, a rolling deployment can produce a sequence of small stampedes. Shared caches, warming the most popular keys before a pod is marked ready, or gradual traffic shifting all reduce the effect.

Measuring cache health

Hit rate alone is misleading. A 99% hit rate can hide a stampede if the 1% of misses arrive at the same moment for the same key. Watch concurrent recomputations per key, database load correlated with cache expiry events, the age of served values, and how much traffic is served stale. Load tests should include cache expiry, cache restarts and deploys, not only a warm steady state.

Invalidation on write

Time-based expiry is not the only way values leave a cache. Many systems also invalidate entries when the underlying data changes, so users see updates quickly. Invalidation creates its own stampede risk: a bulk update that touches thousands of products can invalidate thousands of keys at once, and the next wave of reads recomputes them all together.

Two techniques soften this. First, prefer updating the cached value over deleting it when the writer already has the new data, so readers never see a miss. Second, when deletion is necessary, spread it: process invalidation events from a queue at a controlled rate, or mark entries as stale and let early refresh replace them gradually.

Driving invalidation from the database change stream rather than from application code also helps consistency, because every committed change produces exactly one event — including changes made by scripts and other services that never call the application's cache logic.

Whichever invalidation model is used, test it under realistic write bursts. Bulk imports, price updates and migrations are exactly the moments when invalidation volume spikes, and they are often scheduled at night when nobody is watching the cache and database dashboards closely.

Worked example: taming a catalogue endpoint

A catalogue API serves category pages from Redis with a fixed TTL of 300 seconds. Every five minutes, database CPU spikes and p99 latency for unrelated endpoints doubles.

  1. TTLs are jittered between 270 and 330 seconds, which spreads expiries for the 2,000 category keys.
  2. Each value is stored with a logical expiry 30 seconds earlier than the physical TTL; the first read after the logical expiry triggers an asynchronous refresh while returning the cached value.
  3. Refreshes take a per-key lock in Redis with a 10-second expiry, so only one worker recomputes each key.
  4. The CDN in front of the API uses stale-while-revalidate=60 for anonymous traffic.
  5. New pods pre-load the 200 most requested categories before passing readiness.

Database CPU becomes flat over the five-minute cycle, and recomputations per key drop to one per refresh. The values served are at most about half a minute older than before — a trade-off the product team accepted explicitly.

Common pitfalls

  • Fixed TTLs on many keys created at the same time.
  • Unbounded waits behind a recomputation lock.
  • Locks without expiry that block a key after a worker crash.
  • Judging cache health by average hit rate only.
  • Deploys that empty in-process caches on every pod at once.
  • Serving stale data where staleness is not acceptable, without asking.

FAQ

Is a bigger cache the answer?

Not for stampedes. Size affects how many keys fit; stampedes are about how misses on hot keys are handled.

Should we cache in-process or in a shared cache?

Often both: a small in-process cache for the hottest data and a shared cache behind it. Each layer needs its own expiry and stampede strategy.

What if data must never be stale?

Then invalidate on write through events or change data capture and keep coalescing for misses. Stale-while-revalidate is for data where short staleness is acceptable.

Checklist

  • Jittered TTLs for groups of keys created together.
  • Per-key request coalescing with bounded waits and lock expiry.
  • Early or probabilistic refresh for hot keys.
  • stale-while-revalidate where staleness is acceptable.
  • Cache warming before pods receive traffic.
  • Metrics for recomputations per key and served-value age.

Primary sources

  1. RFC 5861 — HTTP Cache-Control Extensions for Stale Content
  2. RFC 9111 — HTTP Caching
  3. A. Vattani, F. Chierichetti, K. Lowenstein — Optimal Probabilistic Cache Stampede Prevention (VLDB 2015)
  4. Redis documentation — Distributed locks with Redis
  5. Go package golang.org/x/sync/singleflight

Related research