Cache stampede

Also known as: dogpile effect

On this page 8

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.

PhaseWhat happensVisible symptom
ExpiryA popular key reaches its TTLCache hit ratio dips slightly
Miss burstConcurrent requests all query the originDatabase connections climb sharply
ContentionDuplicate queries compete for locks and CPUResponse time and tail latency rise
SaturationWorker pools and connection limits fillTimeouts and 502 or 504 errors
Recovery or cascadeA value is finally cached, or other keys expire tooEither fast recovery or a prolonged outage
Typical phases of an unprotected stampede

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.

TechniqueMechanismMain trade-off
Mutex or lockFirst miss acquires a short lock and rebuilds; others wait or retryWaiting requests add latency; lock TTL must be tuned
Request coalescingConcurrent misses in one process share a single in-flight fetchProtects one node only, not the whole cluster
Stale-while-revalidateServe the expired value while one request refreshes itUsers briefly receive slightly outdated data
Probabilistic early expirationEach read may refresh early with rising probability near expirySome extra recomputation; requires tuning
TTL jitterAdd random spread to expiry timesPrevents mass expiry but not single hot-key stampedes
Background refreshA worker rebuilds hot keys on a scheduleExtra infrastructure and wasted work on unused keys
Main stampede mitigation techniques

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.

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.

PatternTriggerPrimary remedy
Cache stampedeHot key expires under high concurrencyLocking, stale serving, early refresh
Cache penetrationRequests for keys that never existNegative caching or Bloom filters
Cache avalancheMany keys expire at once or a cache node failsTTL jitter, replication, cache warming
Thundering herdMany waiting clients wake for one eventSingle-waiter wakeup, backoff
How a stampede differs from similar failure patterns

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.

SituationRecommended approachReason
Content site homepageStale-while-revalidate with grace periodSeconds of staleness are acceptable
Pricing or stock levelsDistributed lock with short waitStale values could mislead customers
Expensive analytics queryBackground refresh before expiryRebuild takes too long for a request
Large key populationTTL jitter of 10 to 20 percentSpreads expiry without per-key logic
After deployment or flushCache warming of top URLsAvoids a cold-start stampede
Selecting a strategy by workload

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.