A popular cache key expires or is invalidated. In the next few hundred milliseconds every concurrent request sees a miss and independently recomputes the value against the origin. The origin (usually a database) receives an N-fold spike instead of a single refresh. Latency climbs, connection pools saturate, and the system that the cache was meant to protect becomes the bottleneck. This is the cache stampede (also called thundering herd or dogpile effect). It is a recurring production failure mode, not a theoretical one.
How Naive Cache-Aside Creates the Problem
The classic cache-aside pattern is simple: on read, check the cache; on miss, query the database, store the result, and return it. Under low concurrency this works. Under realistic load it does not, for two reasons.
First, expiration is synchronized. When many keys are written with the same TTL, or when a popular key is deleted, every process observes the miss at the same moment. Second, there is no coordination. Each process assumes it is the only one that must refill the key. The result is multiplicative load exactly when the system is least able to absorb it.
Facebook documented the concrete impact. In the 2013 NSDI paper Scaling Memcache at Facebook, a hot key produced peak database load of roughly 17 000 queries per second. After the mitigation described below, the same keys produced 1 300 queries per second. Instagram engineering later described the same pattern on cluster start-up: an empty cache plus live traffic produced an immediate stampede against the backend. Both organizations treated the problem as a first-class reliability issue rather than an occasional edge case.
The failure is not limited to application-level caches. Edge caches, CDN layers, and even in-process maps exhibit the same behavior when a popular object expires.
Proven Mitigations from Production Systems
Four techniques appear repeatedly in production systems and primary literature. They are complementary; most high-scale deployments combine at least two of them.
Request Coalescing / Single-Flight Locks
Only one request is allowed to recompute a given key; the others wait or serve a stale value. Facebook implemented this inside memcached via leases. On a miss the server returns a 64-bit lease token and limits issuance to one token every 10 seconds per key. Other clients are told to wait briefly and retry. When the lease holder writes the value, subsequent retries hit the cache. The same idea appears as
proxy_cache_lock in NGINX (introduced in 1.1.12) and as the single-flight / promise pattern used by Instagram.
Instagram’s approach is elegant for languages with futures: on a miss, atomically insert a Promise into the cache and start the backend work. Concurrent callers find the Promise rather than a miss and wait on it. Only one backend call occurs. In Redis the common implementation is
SET key NX EX ttl as a short-lived mutex, with careful ownership so a crashed holder cannot leave the lock forever.
Stale-While-Revalidate
Serve the slightly expired value immediately while one background request refreshes it. RFC 5861 defines the HTTP
Cache-Control extension stale-while-revalidate=N. A response that is still within the freshness lifetime is served normally; for N seconds after it becomes stale the cache may return the stale copy while revalidating asynchronously. After the window the object is treated as fully expired. NGINX approximates the same behavior with proxy_cache_use_stale updating together with background update. The user never sees a cache miss latency spike, and the origin sees only a single refresh.
Probabilistic Early Expiration (XFetch)
Instead of waiting for the hard expiry cliff, each reader independently decides, with rising probability, to refresh the value a short time before it expires. The optimal algorithm is XFetch, from the 2015 VLDB paper Optimal Probabilistic Cache Stampede Prevention (Vattani, Chierichetti, Lowenstein). The decision is:
``
if time() - delta beta ln(rand()) >= expiry then recompute
`
where delta is the observed recomputation time, beta is a tuning parameter (1.0 is the paper’s recommended default), and rand() is in (0, 1]. Most readers continue to serve the cached value; statistically one reader refreshes early. The paper proves the exponential distribution is optimal for balancing early refresh against stampede size. Because the decision is local, no distributed lock is required for warm keys.
TTL Jitter
Add a small random offset to every TTL so that keys written together do not expire together. A uniform or truncated-normal jitter of a few percent of the base TTL is usually sufficient. This is the cheapest mitigation and should be applied by default; it does not, however, protect a single hyper-hot key that is read continuously.
Practical Implementation Patterns
A production-grade combination for most application caches is:
- Jittered TTLs on every write.
- XFetch (or a simple probabilistic early refresh) for known-hot keys.
- A short-lived distributed lock (or single-flight) as the back-stop for cold misses.
- Stale-while-revalidate semantics so that readers never block on the refresh.
Minimal Redis single-flight sketch (illustrative; production code needs lock ownership and timeout handling):
`redis
-- On miss
SET lock:{key} 1 NX EX 10
-- Only the winner proceeds to the database
-- Others retry GET or serve stale after a short backoff
`
For XFetch the stored payload must include the value, the measured delta, and the absolute expiry. On every read the local process evaluates the formula above and, if it triggers, recomputes and overwrites. Pair it with a lock only for the cold-start case, because XFetch has nothing to refresh when the key is absent.
At the edge, NGINX configuration that combines locking and stale serving looks like:
`nginx
proxy_cache_lock on;
proxy_cache_lock_timeout 5s;
proxy_cache_lock_age 5s;
proxy_cache_use_stale updating error timeout;
`
The lock ensures only one upstream request populates a missing key; use_stale updating lets others receive the previous value while the lock holder works.
Limitations and Failure Modes
Each technique introduces new failure modes.
- Locks without a TTL become deadlocks when the holder crashes. Always set an expiry slightly longer than the worst-case recomputation time, and prefer ownership tokens so only the holder can release the lock.
- Waiting clients consume threads or connection slots. Under extreme load the waiters themselves can exhaust resources even if only one request hits the origin.
- Stale-while-revalidate serves data that may be seconds or tens of seconds old. This is acceptable for many read-heavy workloads but not for strongly consistent or financial data.
- XFetch stores extra metadata (
delta, expiry) and can trigger slightly more recomputations than a pure lock. On cold keys it provides no protection.
Jitter alone does nothing for a single key that is continuously hot.
Monitoring must therefore watch both cache hit rate and origin query rate around TTL boundaries, plus lock wait times and background refresh success. A sudden drop in hit rate coinciding with a spike in origin queries is the classic stampede signature.
Implications for Reliability and Operations
Stampede protection is a reliability control, not a performance optimization. The cost of an unprotected hot key is an origin outage that can cascade to every service sharing that database. The techniques above convert an unbounded N-fold spike into a bounded single refresh (or a small probabilistic number of refreshes). They also make cache behavior predictable during deployments, cold starts, and mass invalidations.
Because the mitigations are local or require only a short-lived mutex, they compose with existing cache-aside code and with CDNs that already implement RFC 5861. The operational change is mainly configuration and a small amount of library code rather than a new architectural tier.
What to Do Next
Start with the cheapest controls that remove synchronized expiry: add TTL jitter on every write path and enable stale-while-revalidate (or the equivalent use_stale updating) wherever the cache layer supports it. For any key whose recomputation is expensive or whose traffic is known to be high, add either XFetch or a single-flight lock. Instrument origin query rate and cache-miss rate so that the next stampede is visible in metrics before it is visible to users. Finally, treat the Facebook lease numbers and the VLDB optimality result as existence proofs that the problem is solvable at large scale; the same patterns apply to far smaller systems.
FAQs
What is a cache stampede?
A cache stampede occurs when many concurrent requests miss the same expired or missing cache key and all recompute the value against the origin at once, producing a sudden load spike.
How did Facebook reduce stampede load?
In the 2013 NSDI paper they extended memcached with leases that are issued at most once every 10 seconds per key. Other clients wait and retry. Measured peak database load on herd-prone keys fell from approximately 17 000 to 1 300 queries per second.
What is XFetch?
XFetch is the probabilistic early-expiration algorithm from the 2015 VLDB paper Optimal Probabilistic Cache Stampede Prevention. Each reader independently decides to refresh a key slightly before its TTL using an exponential distribution, so the hard expiry cliff almost never occurs under continuous traffic.
When should I use a lock versus stale-while-revalidate?
Use a lock (or single-flight) when you must guarantee exactly one recomputation and can tolerate brief waiting. Use stale-while-revalidate when serving slightly stale data is acceptable and you want zero added latency for readers.
Does TTL jitter alone solve the problem?
No. Jitter prevents many keys from expiring in the same instant, but a single continuously hot key can still stampede. Combine jitter with one of the other techniques.
Is stale-while-revalidate safe for all data?
No. RFC 5861 explicitly allows serving stale responses for a bounded window. It is appropriate for cacheable, eventually-consistent data. Strongly consistent or security-sensitive values should not rely on it.
Conclusion
Cache stampedes are caused by synchronized misses plus uncoordinated recomputation. Production systems have solved the problem for more than a decade with leases, single-flight, stale-while-revalidate, probabilistic early refresh, and TTL jitter. Implementing the combination appropriate to your consistency and latency requirements turns an unbounded origin spike into a controlled single refresh and removes one of the most common ways a cache can become a liability.
Sources
- Nishtala et al., Scaling Memcache at Facebook, 10th USENIX Symposium on Networked Systems Design and Implementation (NSDI ’13), April 2013. https://www.usenix.org/conference/nsdi13/technical-sessions/presentation/nishtala (PDF: https://www.usenix.org/system/files/conference/nsdi13/nsdi13-final170_update.pdf)
- Instagram Engineering, Thundering Herds & Promises, 16 April 2019. https://instagram-engineering.com/thundering-herds-promises-82191c8af57d
- Vattani, Chierichetti, Lowenstein, Optimal Probabilistic Cache Stampede Prevention, Proceedings of the VLDB Endowment 8(8), 2015, pp. 886–897. https://doi.org/10.14778/2757807.2757813
- RFC 5861, HTTP Cache-Control Extensions for Stale Content, May 2010. https://www.rfc-editor.org/rfc/rfc5861
- NGINX documentation,
proxy_cache_lock` and related directives, ngx_http_proxy_module. https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_cache_lock