A cache stampede is a failure pattern in which many concurrent requests miss the same cache entry at the same moment and each one independently recomputes the value from the slower backend. In server performance work it is also called the dogpile effect, and it is one of the most common reasons a well-cached site suddenly collapses under ordinary traffic.
The danger lies in load amplification: a single expired key can turn one expensive database query into hundreds of identical queries within milliseconds. Servers that comfortably handle peak traffic with a warm cache can reach resource saturation in seconds once a popular entry expires, which is why stampede protection is a standard design requirement for any shared caching layer.
How a cache stampede develops
A cache stampede develops when a hot key expires while request concurrency is high. Every request that arrives between the expiry and the moment a fresh value is written finds nothing in the cache, so each one follows the cache-aside read path: query the origin, build the value, write it back.
The size of the stampede depends on two quantities: the arrival rate for the key and the regeneration time. A key requested 500 times per second with a two-second rebuild produces roughly 1,000 duplicate recomputations before the first result lands. Because each duplicate competes for the same database connections and CPU, the rebuild itself slows down, which widens the window and admits even more misses.
This positive feedback loop is what separates a stampede from a normal cache miss. The table below traces the typical sequence on an unprotected system.
| Phase | What happens | Visible symptom |
|---|---|---|
| Expiry | A popular key reaches its TTL | Cache hit ratio dips slightly |
| Miss burst | Concurrent requests all query the origin | Database connections climb sharply |
| Contention | Duplicate queries compete for locks and CPU | Response time and tail latency rise |
| Saturation | Worker pools and connection limits fill | Timeouts and 502 or 504 errors |
| Recovery or cascade | A value is finally cached, or other keys expire too | Either fast recovery or a prolonged outage |
Conditions that make stampedes likely
Stampedes are not random; they follow from predictable combinations of traffic and configuration. The highest risk appears where an expensive value is shared by many users and expires on a fixed schedule.
- Synchronized expiry: many keys written at the same time with the same TTL expire together, for example after a deployment or a cache flush.
- Cold start: a restarted Redis or Memcached node, or a newly added server, begins with an empty cache.
- Expensive regeneration: aggregate queries, external API calls or full-page rendering that take hundreds of milliseconds or more.
- Traffic spikes: a newsletter, a broadcast mention or a scheduled sale concentrates requests on a few URLs.
The common factor is many requests per regeneration window. A key read once per minute cannot stampede, while a homepage fragment read thousands of times per second almost certainly will without protection.
Mitigation techniques and their trade-offs
Stampede mitigation works by ensuring that only one request rebuilds a value or that rebuilding happens before the entry expires. Each technique accepts a different compromise between freshness, complexity and latency.
| Technique | Mechanism | Main trade-off |
|---|---|---|
| Mutex or lock | First miss acquires a short lock and rebuilds; others wait or retry | Waiting requests add latency; lock TTL must be tuned |
| Request coalescing | Concurrent misses in one process share a single in-flight fetch | Protects one node only, not the whole cluster |
| Stale-while-revalidate | Serve the expired value while one request refreshes it | Users briefly receive slightly outdated data |
| Probabilistic early expiration | Each read may refresh early with rising probability near expiry | Some extra recomputation; requires tuning |
| TTL jitter | Add random spread to expiry times | Prevents mass expiry but not single hot-key stampedes |
| Background refresh | A worker rebuilds hot keys on a schedule | Extra infrastructure and wasted work on unused keys |
Probabilistic early expiration, often called the XFetch approach, lets a request recompute a value before its TTL with a probability that grows as expiry approaches and scales with the measured rebuild cost. It needs no coordination between servers, which makes it attractive in large clusters.
At the HTTP layer, reverse proxies offer equivalent controls. Varnish uses grace mode and request coalescing, while NGINX provides proxy_cache_lock and proxy_cache_use_stale updating. The stale-while-revalidate directive of the Cache-Control header, defined in RFC 5861, expresses the same idea for shared caches and CDNs.
Cache stampede compared with related problems
A cache stampede is one of several cache-related overload patterns, and naming them correctly matters because the fixes differ. The comparison below separates the stampede from its closest neighbors in server performance.
| Pattern | Trigger | Primary remedy |
|---|---|---|
| Cache stampede | Hot key expires under high concurrency | Locking, stale serving, early refresh |
| Cache penetration | Requests for keys that never exist | Negative caching or Bloom filters |
| Cache avalanche | Many keys expire at once or a cache node fails | TTL jitter, replication, cache warming |
| Thundering herd | Many waiting clients wake for one event | Single-waiter wakeup, backoff |
The distinguishing feature of a stampede is duplicate regeneration of the same value, not merely a large number of requests.
Choosing a protection strategy
The right protection depends on how stale data may be and how costly regeneration is. Most production systems combine at least two techniques, typically jittered TTLs everywhere plus locking or stale serving for the hottest keys.
| Situation | Recommended approach | Reason |
|---|---|---|
| Content site homepage | Stale-while-revalidate with grace period | Seconds of staleness are acceptable |
| Pricing or stock levels | Distributed lock with short wait | Stale values could mislead customers |
| Expensive analytics query | Background refresh before expiry | Rebuild takes too long for a request |
| Large key population | TTL jitter of 10 to 20 percent | Spreads expiry without per-key logic |
| After deployment or flush | Cache warming of top URLs | Avoids a cold-start stampede |
Load testing with tools such as Apache JMeter or k6 should include a test that expires hot keys under load. A system that performs well only with a warm cache has an untested failure mode that real traffic will eventually find.
Common implementation mistakes
Stampede protection often fails because of small implementation details rather than the choice of technique.
- Locks without a timeout: if the rebuilding process crashes, every other request waits indefinitely.
- Unbounded waiting: waiters that poll without a deadline exhaust the PHP worker pool or thread pool.
- Process-local coalescing only: twenty application servers still send twenty identical queries.
- Purging instead of invalidating softly: a hard delete removes the stale value that could have been served.
Monitoring should track origin queries per cache key and lock wait times, not only the overall hit ratio. A hit ratio of 99 percent can hide a stampede on the single key that matters most.
In simple terms
Imagine a busy office with one coffee machine and a sign that says the pot is empty. If everyone who sees the sign starts brewing a new pot at the same time, the machine jams and nobody gets coffee. A cache stampede is the same thing on a server: a saved answer runs out, and hundreds of visitors all ask the database to rebuild it at once.
The fix is simple in principle. Let one person brew the new pot while everyone else either waits a moment or drinks the slightly older coffee. Servers do this with locks, with short periods of serving older data, or by refreshing the answer before it runs out.
A practical example
A regional news website caches its homepage article list in Redis with a fixed 60-second TTL. Building the list requires a database query of about 800 milliseconds. During an election evening, traffic reaches roughly 2,000 homepage requests per second, and every minute the site shows a short burst of 504 errors as hundreds of requests rebuild the same list and exhaust the database connection pool.
The operations team introduces three changes: a Redis lock with a five-second timeout so that only one worker rebuilds the list, stale serving for up to 30 seconds for all other requests, and random jitter of 15 percent on related fragment TTLs. In the next load test, origin queries for the homepage drop from several hundred per expiry to one, and the minute-by-minute error spikes disappear while the page content remains at most a few seconds old.