When a cache goes cold, every request that used to be a cache hit becomes a database query at the same moment. A database sized for a 15% miss rate is suddenly asked to serve 100% of the reads, its queue grows by more requests each second than it can ever work through, and clients time out and retry, which adds still more load.
That cascade is a cache stampede. The fixes all do one of three things: send fewer duplicate queries (coalescing, leases), spread refills out in time (jittered expiry, early refresh, warming), or protect the database while it is overloaded (serving stale data, load shedding).
Key takeaways
- The database sees traffic × (1 − hit rate). If a database can handle 400 queries a second and the service gets 2,000 requests a second, anything below an 80% hit rate means the queue grows without limit.
- At a 0% hit rate in the worked example below, the backlog grows by 1,600 requests every second. Half a second in, a new request already waits 2 seconds.
- The incident outlasts the outage. A 30-second cache failure leaves a backlog that takes at least 8 minutes to drain, even if the cache returns at its normal 85% hit rate.
- Match the fix to the trigger. Coalescing helps hot keys, jittered expiry helps keys that were loaded together, warming helps a cold start, and shedding is the backstop for all of them.
What is a cache stampede?
A cache stampede is a burst of identical work that happens because many requests see the same cache miss together. The 2015 VLDB paper "Optimal Probabilistic Cache Stampede Prevention" defines it as a situation "that occurs when a popular cache item expires, leading to multiple requests seeing a cache miss and regenerating that same item at the same time" (Vattani, Chierichetti and Lowenstein, VLDB 2015). The authors list other names for it: dog-piling, cache miss storm and cache choking.
The paper also points out why it gets worse as it goes. The number of requests that miss together "depends not only on the request rate, but also on the time needed to recompute the item", and extra recomputations slow the system down, "in turn causing even more requests to be part of the stampede". It is a feedback loop, not a one-off spike.
A stampede has three common triggers, and they need different fixes:
| Trigger | What happens | Example |
|---|---|---|
| Cold start or flush | The whole cache is empty, so every key misses at once | A deploy restarts the cache nodes, or someone runs a flush command |
| Hot key expiry | One popular key expires and many requests regenerate it together | A home-page query with a 5-minute TTL |
| Synchronised expiry | Many keys were loaded at the same time with the same TTL, so they all expire together | A cache warmed after an outage, every key set to 1 hour |
Facebook's engineers describe a related case they call a thundering herd. In their usage it happens "when a specific key undergoes heavy read and write activity", because the writes keep invalidating the cached value and "many reads default to the more costly path" (Nishtala et al., Scaling Memcache at Facebook, NSDI 2013). People use "stampede" and "thundering herd" loosely. The mechanics below apply to both.
How much traffic reaches the database when the cache disappears?
The database sees the requests the cache did not absorb:
database load = request rate × (1 − hit rate)
This uses the same example as how to find the bottleneck in a system design. A service handles 2,000 requests a second. Postgres has a pool of 8 connections and each query takes 20 ms, so it can complete 8 ÷ 0.020 = 400 queries a second. At the usual 85% hit rate, Postgres sees 300 a second, which is 75% utilisation.
Here is what happens as the hit rate falls:
| Cache hit rate | Postgres load | Utilisation | What it means |
|---|---|---|---|
| 85% | 300/s | 75% | Normal. Average query time is about 24 ms |
| 80% | 400/s | 100% | The break-even point. Above this hit rate the queue drains, below it the queue only grows |
| 60% | 800/s | 200% | Backlog grows by 400 requests a second |
| 0% | 2,000/s | 500% | Backlog grows by 1,600 requests a second |
The break-even hit rate is 1 − capacity ÷ request rate = 1 − 400 ÷ 2,000 = 80%. That is a number worth knowing for any cached read path: the lower your database's capacity is compared with your peak traffic, the more your system depends on the cache staying warm. The cache stops being an optimisation and becomes part of the capacity plan.
How fast does the queue build when the cache is cold?
Take the worst case: the hit rate drops to 0% and 2,000 queries a second arrive at a database that finishes 400 a second. Treat the pool as a first-in, first-out queue and ignore random variation, which is called a fluid approximation. The backlog grows by 2,000 − 400 = 1,600 requests every second.
A request that arrives behind a backlog of Q waits Q ÷ 400 seconds before it starts. That gives a simple pattern:
| Time since the cache went cold | Backlog | Wait for a new request |
|---|---|---|
| 0.5 s | 800 | 2 s |
| 1 s | 1,600 | 4 s |
| 5 s | 8,000 | 20 s |
| 10 s | 16,000 | 40 s |
Now add what real clients do. Say the client timeout is 2 seconds. From about half a second in, every new request waits at least that long. Two things follow:
- The database does work nobody wants. If the queue is first in, first out and the database does not cancel queries from clients that have disconnected, then from about 2.5 seconds in, almost every query it finishes belongs to a client that has already given up. The database is 100% busy and the useful output is close to zero.
- Retries make it worse. Once the first timeouts arrive, each client that retries adds another request. If every timed-out request is retried once, the database is offered roughly 2,000 new requests plus about 2,000 retries a second, around 4,000 a second. AWS's guidance on retries puts it directly: "When failures are caused by overload, retries that increase load can make matters significantly worse. They can even delay recovery by keeping the load high long after the original issue is resolved" (Amazon Builders' Library, Timeouts, retries and backoff with jitter).
Why does the incident outlast the outage?
Suppose the cache fails for 30 seconds and then comes back. The backlog at that moment is 1,600 × 30 = 48,000 requests. Once the cache returns, Postgres goes back to 300 queries a second, which leaves 400 − 300 = 100 a second of spare capacity to drain the queue. Clearing 48,000 requests at 100 a second takes 480 seconds, or 8 minutes.
That is the best case, because a restarted cache is empty and refills gradually, so for a while the hit rate is well below 85%. Recovery is the slow part of a stampede, and it is why you plan for the cache being cold instead of only for the cache being down.
These are model numbers, not measurements. Real service times vary, real arrivals come in bursts, and some databases cancel abandoned queries. Those details change the size of the effect, not its direction.
What does this look like in the StackMonkey simulator?
The StackMonkey home page has a small read-through demo with a Redis cache in front of a Postgres pool. The Simulate Cache Outage button sets Redis to a 0.0% hit ratio, marked as dead, and the Postgres connection pool jumps to 100 of 100, marked as saturated. The event log reports a read-through stampede starving the Postgres pool, and the wait queue behind the pool starts to climb.
The home-page demo is a scripted visualisation with its own fixed values, so its numbers will not match the 2,000 requests a second example above. What carries over is the shape: nothing is wrong with the database itself, and one component going away saturates it anyway. To model your own design, build it in the StackMonkey simulator, switch the cache off, and see which component's queue fills first. The simulator's queueing engine is checked against published queueing results (M/M/1, M/M/c/K, M/G/1, M/D/1 and closed loops).
How do you prevent a cache stampede?
Six sections follow, and each one changes a different term in the load equation.
Coalesce duplicate requests
Request coalescing means that when many requests miss on the same key at once, only one of them goes to the database and the rest wait for its result. Go's singleflight package is a standard example: it "provides a duplicate function call suppression mechanism" and makes sure "only one execution is in-flight for a given key at a time" (golang.org/x/sync/singleflight).
Little's Law shows how many duplicates there are to remove. Duplicate queries for one key equal that key's request rate times the time the query takes. The VLDB paper gives its own example: "if the cache item is accessed 10 times per second, and the recomputation of the item takes 3 seconds, then 30 requests will recompute the item."
Using the earlier numbers, a hot key at 500 requests a second with a healthy 20 ms query has 500 × 0.02 = 10 requests overlapping. When the database is overloaded and each query takes 2 seconds, that becomes 500 × 2 = 1,000 duplicates for one key. With coalescing it stays at one. This is also the feedback loop from earlier, in numbers: a slower database creates more duplicates, which makes it slower.
Limit: coalescing only helps in proportion to how concentrated traffic is. If 2,000 requests a second are spread evenly over 20,000 keys, each key gets 0.1 requests a second, and 0.1 × 0.02 = 0.002 requests overlap, so there is almost nothing to merge. Skewed traffic, where a few keys take most requests, benefits most.
Use leases or locks on regeneration
A lease lets one client regenerate a missing value while the others wait or are told to retry. Facebook's memcache servers issue a token for a key "only once every 10 seconds per key", and a request for the key inside that window gets "a special notification telling the client to wait a short amount of time". For keys particularly susceptible to thundering herds, they report that the peak database query rate fell from 17,000 a second without leases to 1,300 a second with leases (Nishtala et al., NSDI 2013).
The VLDB paper lists the trade-off of simple locking: the requests that do not get the lock "have no cache item to return", so each one has to wait, fail, or be served an old value.
Add jitter to expiry times
If many keys are loaded together with the same TTL, they expire together. Say 100,000 keys are loaded at once with a 1-hour TTL. At the 1-hour mark, up to 100,000 refills are demanded in the same second, which is 100,000 ÷ 400 = 250 seconds of Postgres's entire capacity.
Add a random offset to each TTL. With ±10% jitter on a 3,600-second TTL, expiries spread across a 720-second window, so the demand averages 100,000 ÷ 720 ≈ 139 refills a second: 35% of Postgres's capacity, instead of 250 seconds' worth of it demanded at once. This assumes every key is requested again, which is the upper bound. The same AWS article makes the point about clients: without jitter, "they can line up and trigger their requests at the same time."
Refresh early, at random
Probabilistic early expiration, often called XFetch, lets each request decide on its own, with a probability that rises as expiry approaches, whether to recompute the value early. The VLDB paper describes it as a countermeasure where processes "randomly ask for a regeneration before the expiration time of the item", and gives algorithms it calls "theoretically optimal". The aim is that a hot key is refreshed by one request shortly before it expires, instead of by many requests at once after it has.
Serve stale data while you refresh
If slightly old data is acceptable, serve it while one request refreshes it in the background. HTTP caches have a standard form of this. RFC 5861 defines stale-while-revalidate, where, for a response with Cache-Control: max-age=600, stale-while-revalidate=30, "caches MAY serve the response in which it appears after it becomes stale" for the stated number of seconds. After that window passes without revalidation, it "SHOULD NOT continue to be served stale, absent other information" (RFC 5861). The RFC is about HTTP caches. In an application cache, the same pattern is something you build yourself: store a soft expiry next to the value and refresh once when it passes.
Limit: this is a choice about correctness. It suits product listings and feeds, and it does not suit account balances or inventory counts.
Warm the cache before sending traffic, and shed load while it fills
After a restart or a failover, do not point full traffic at an empty cache. Fill the hot keys first. The arithmetic gives you a floor: refilling 100,000 keys from a database that does 400 queries a second takes 100,000 ÷ 400 = 250 seconds if the warm-up has the whole database, and 500 seconds if you give it half (200 a second). Real traffic will compete, so plan for longer, and send traffic gradually as the hit rate climbs.
While the cache is cold, protect the database by shedding load. AWS describes the idea this way: a server near overload should "start rejecting excess requests", so that it can "keep latency low for the requests that the server decides to accept" (Amazon Builders' Library, Using load shedding to avoid overload).
In the example, hold Postgres at 80% utilisation by admitting 320 queries a second. By the M/M/c (Erlang C) model, the average time per admitted query is about 25.7 ms, and 46% of them wait briefly for a connection. The cost is that 2,000 − 320 = 1,680 requests a second, 84% of traffic, get a fast error or a degraded answer instead of a slow timeout. That is a harsh number, which is why shedding is the backstop and not the plan.
Which fix matches which trigger?
| Trigger | Fixes that address it |
|---|---|
| Cold start or flush | Warm the cache, send traffic gradually, shed load while it fills |
| Hot key expiry | Request coalescing, leases, early refresh, stale-while-revalidate |
| Synchronised expiry | Jittered TTLs, staggered warm-up |
| Cache node failure | Replicas or consistent hashing so only part of the keyspace goes cold, plus shedding |
| Retries amplifying overload | Capped exponential backoff with jitter, retry budgets, timeouts shorter than the queue wait |
To pressure-test a design against all of these, run a cache outage at your expected peak, not at average load. If utilisation at the database goes above 100% when the cache is cold, you have found a design decision to make: a bigger pool, a replica, a second cache tier, or a shedding rule. The URL shortener template is a read-heavy design where this exercise is easy to try (open it in the simulator), and the rate limiter template shows one way to cap traffic at the edge.
Frequently asked questions
Is a cache stampede the same as a thundering herd?
The terms overlap and sources use them differently. The VLDB paper defines a stampede as many requests regenerating the same expired item at once. Facebook's paper uses "thundering herd" for a key under heavy read and write activity where writes keep invalidating the cached value. In both cases, many requests take the slow path together, so the same fixes (coalescing, leases, early refresh) apply.
Does a bigger database connection pool fix a cold cache?
Only if the database has the CPU, memory and I/O to use more connections. In the example, doubling the pool from 8 to 16 connections raises capacity from 400 to 800 queries a second, but a cold cache still sends 2,000, which is 250% utilisation. A bigger pool moves the break-even hit rate from 80% to 60% (1 − 800 ÷ 2,000). It does not remove the problem, and more concurrent queries can slow each one down, so treat 800 as a ceiling, not a promise.
Should I just set longer TTLs?
A longer TTL lowers the miss rate in steady state, and it does nothing for a cold start or a node failure, where the keys are simply gone. It can also make synchronised expiry worse if all the keys are loaded at the same moment, because they all expire at the same moment. Longer TTLs work with jitter, not instead of it.
How do I test a design for this before production?
Follow these steps, then repeat them after every change:
- Work out the database's capacity (workers ÷ query time) and your peak request rate.
- Compute the break-even hit rate: 1 − capacity ÷ request rate.
- Run the design with the cache switched off at peak load.
- Watch which queue fills first, as in the bottleneck walkthrough.
- Add one fix (a bigger pool, a replica, coalescing, shedding) and rerun.
A simulator lets you do this on a whiteboard-sized design before you build it, and StackMonkey runs in the browser with no signup.
About this article
Written by the team that builds StackMonkey. The worked-example numbers were computed for this article from the formulas named below. The 2,000 requests a second example reuses the one in our bottleneck article, so the two can be read together. Descriptions of the demo on the StackMonkey home page come from its source code. If you find an error, email [email protected] and we will correct it and note the change here. More about the project is on the about page.
Sources
- Andrea Vattani, Flavio Chierichetti and Keegan Lowenstein, "Optimal Probabilistic Cache Stampede Prevention", Proceedings of the VLDB Endowment 8(8), 2015. VLDB.
- Rajesh Nishtala et al., "Scaling Memcache at Facebook", NSDI 2013. USENIX.
- "Timeouts, retries, and backoff with jitter", Amazon Builders' Library. builder.aws.com.
- "Using load shedding to avoid overload", Amazon Builders' Library. builder.aws.com.
- M. Nottingham, "HTTP Cache-Control Extensions for Stale Content", RFC 5861, 2010. rfc-editor.org.
- Go Authors,
golang.org/x/sync/singleflight. pkg.go.dev.
The worked-example figures were computed with a fluid (deterministic) approximation for the backlog, and the M/M/c (Erlang C) formula for queueing delay, assuming Poisson arrivals and exponential service times. The model assumes a first-in, first-out queue and no query cancellation.
