Skip to content

Cache stampede mitigation — when N clients race to refresh

Why a popular cache entry expiring under load takes down origin, and the proven patterns to prevent it — locks, jitter, stale-while-revalidate, request coalescing.

A cache stampede is what happens when a popular entry expires and N concurrent requests all observe a miss, all stampede toward origin to rebuild it, and origin — sized for cached traffic — falls over. The classic incident: a hot product page expires at peak, thousands of clients miss the cache simultaneously, each one runs the same expensive database query, and the database queue fills up. The application timeout cascades; everything goes red. This article is the patterns we deploy to prevent it.

How to verify

Identify whether your application is vulnerable. Look for the symptom shape — origin RPS spikes that match cache TTL boundaries.

# Check cache hit rate over time
varnishstat -1 -f MAIN.cache_hit -f MAIN.cache_miss
# In the application logs, group by expensive endpoint and look for periodic miss bursts
grep -E '"GET /products/" .*200' /var/log/nginx/access.log \
  | awk '{print substr($4, 14, 5)}' | sort | uniq -c | sort -rn | head

# In origin DB, look for sudden query bursts
psql -c "SELECT date_trunc('minute', query_start) AS m, count(*) FROM pg_stat_activity
         WHERE query LIKE 'SELECT%products%' GROUP BY m ORDER BY m DESC LIMIT 20;"

If your origin RPS chart has periodic spikes lining up with cache TTL, you have a stampede problem already, even if it has not caused an outage yet.

What’s happening

The math is simple. If your cache TTL is 60 seconds and a hot URL gets 1000 requests per second, that URL produces one origin request per minute when the cache is healthy. The instant the entry expires, the next 1000 concurrent requests all miss; they all hit origin; origin runs the same query 1000 times. The cache stores the response once the first one finishes, but the other 999 are already in flight.

The standard mitigations:

  1. Request coalescing (single-flight). The cache layer ensures only one request to origin per cache key in flight; the other N-1 wait for the same response. Varnish does this natively; nginx with proxy_cache_lock on does it; Redis-backed application code can use a per-key mutex.

  2. Stale-while-revalidate (SWR). When a cached entry is “fresh enough” (within a grace period after expiry), serve the stale value while one background worker refreshes it. HTTP Cache-Control: stale-while-revalidate=60 formalises this at the CDN; Varnish’s beresp.grace does it; many caching libraries support it natively.

  3. Probabilistic early expiration. Rather than expiring all entries at exactly TTL, sometimes refresh them slightly early — probability of early refresh increases as TTL approaches. Spreads the refresh load.

  4. TTL jitter. Apply random TTL within a window (set EX 60 + random(0..10)) so a batch of entries written at the same time does not expire at the same time.

The procedure

  1. Enable request coalescing in the cache layer. Varnish has it on by default; nginx needs proxy_cache_lock on.

    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;
    proxy_cache_lock_age 5s;
    proxy_cache_use_stale updating error timeout http_500 http_502 http_503;
  2. Enable stale-while-revalidate. In Varnish, set beresp.grace; in HTTP Cache-Control, emit stale-while-revalidate=N so the CDN does it too.

    sub vcl_backend_response {
        set beresp.ttl = 60s;
        set beresp.grace = 300s;     # serve stale up to 5 min while refresh runs
    }
    add_header Cache-Control "public, max-age=60, stale-while-revalidate=300";
  3. Probabilistic early expiration in application caches. The classic formula (XFetch) refreshes early with probability delta * beta * ln(rand) near the TTL.

    import math, time, random
    def get_or_refresh(key, ttl, beta=1.0):
        cached = redis.get(key)
        if cached is None:
            return rebuild_and_cache(key, ttl)
        value, expire_at, delta = decode(cached)
        now = time.time()
        if now - delta * beta * math.log(random.random()) >= expire_at:
            return rebuild_and_cache(key, ttl)
        return value
  4. TTL jitter on writes. Pad the TTL with a random window so simultaneous writes do not expire in lockstep.

    ttl = 60 + random.randint(0, 10)
    redis.set(key, value, ex=ttl)
  5. Per-key mutex for very expensive rebuilds. If the rebuild query is seconds long, a coalescer at the cache layer is not enough — implement an application-level lock so only one worker rebuilds.

    def with_lock(key, ttl_lock=10, ttl_value=60):
        cached = redis.get(key)
        if cached is not None: return cached
        lock_key = f"lock:{key}"
        got_lock = redis.set(lock_key, "1", nx=True, ex=ttl_lock)
        if got_lock:
            try:
                value = expensive_query(key)
                redis.set(key, value, ex=ttl_value)
                return value
            finally:
                redis.delete(lock_key)
        else:
            # Another worker is rebuilding; serve stale if available, or wait
            time.sleep(0.05)
            return redis.get(key) or expensive_query(key)

Common pitfalls

  • Enabling SWR with no upper bound on grace — a sustained origin outage will serve stale content for hours; cap it explicitly.
  • Adding jitter on read instead of write — jitter is set at the moment the cache is populated, not when it is consulted; applying it on read is meaningless.
  • Per-key locks without a TTL — if the worker holding the lock crashes, every other request waits forever. Always set an expiry on the lock.
  • Treating “the CDN handles it” as sufficient — POPs do not share coalescing across each other, so a popular object can stampede from N POPs simultaneously even with per-POP locking.
  • Misreading “high cache hit rate” as immune — a 99 % hit rate still produces a stampede on the 1 % miss if N is large.

In the engagements we run, stampede mitigation is a checklist item per cached endpoint, not a global flag. Stack Harbor’s managed operations practice is to identify the top 20 cached URLs by traffic and review each one for the right pattern — coalescing, SWR, or jitter — and to load-test the expiry boundary explicitly before declaring the cache “production safe.”