Cache Stampede - Complete Deep Dive

Prerequisites: Caching, Distributed Locking Used in: Distributed Cache, Zomato, Twitter Feed


What is a Cache Stampede?

A cache stampede is what happens when a single popular cache entry expires and every request that wanted it misses at the same instant. Instead of one request recomputing the value, thousands do — all at once, all hitting the database with the identical query. It is also called a thundering herd, because a quiet system suddenly turns into a stampede of duplicate work.

Real-world analogy: A café puts out one jug of fresh coffee every ten minutes. Normally people take a cup from the jug and leave. The moment the jug runs empty, the fifty people in the queue do not wait — each one walks to the back and asks the barista to brew a fresh pot. The barista now has fifty identical orders for the same pot of coffee. Brewing takes longer because the machine is overloaded, so the queue grows while the jug stays empty, and more people join the stampede. The fix is not a bigger jug; it is one person brewing while the other forty-nine wait for that pot.


How One Expiry Takes Down a Database

The failure is a feedback loop, not a single spike. Walk it one step at a time.

  1. A key is hot — a huge share of traffic reads it. A homepage feed, a product price, a restaurant menu, a feature flag bundle.
  2. The key has a TTL, or time-to-live — the number of seconds the cache keeps it before discarding it so a fresh value can be loaded.
  3. The TTL elapses. The cache now returns a miss to every reader, not just one.
  4. Every missing reader does what it was coded to do: run the expensive query and write the result back.
  5. The database receives thousands of copies of the same query within a few hundred milliseconds. It saturates — connections exhausted, CPU pinned, queues building.
  6. Because the database is saturated, the recompute that took 200 ms now takes 2 seconds. The window in which the cache is empty got ten times longer, so ten times more requests pile into it.
flowchart LR
    R["50K reads per second<br/>for one hot key"] --> C["Cache"]
    C --> M["TTL elapsed<br/>every read misses"]
    M --> DB["Database<br/>same query thousands of times"]
    DB --> S["Saturated<br/>recompute gets slower"]
    S --> W["Empty window widens"]
    W --> M

Step 6 is the part people miss in interviews. A stampede is not a spike that drains; it is self-reinforcing. Left alone it ends in a full outage, and the outage outlives the original expiry by minutes because the recovery itself requires the database you just melted.


The Arithmetic of a Stampede

Reads on the hot key   = 50,000 per second
Recompute latency      = 200 ms = 0.2 s
Concurrent recomputes  = 50,000 x 0.2 = 10,000 identical queries in flight

Now the feedback loop. The database handles 2,000 concurrent queries
comfortably, so at 10,000 it saturates and latency degrades.

Recompute latency under load = 2 s
Concurrent recomputes        = 50,000 x 2 = 100,000

One hundred thousand in-flight duplicates of a query you needed answered once. Each one also holds a connection from the pool, starving every unrelated query in the service — see Connection Pooling — which is why a stampede on one key takes down endpoints that have nothing to do with that key. The framing worth keeping: wasted recomputes equals request rate multiplied by recompute latency. You can measure both numbers today, so you can predict the size of your herd before it happens.


Three Problems That Look Alike

These get conflated constantly, and they have different fixes. Keep them separate.

Problem What triggers it The fix that actually works
Stampede / thundering herd A cached key expires while it is being read heavily Coalescing, serve-stale, early refresh
Cache penetration Requests for keys that do not exist anywhere, so nothing ever caches A Bloom filter or caching the negative answer
Cold start Cache is empty after a flush, a restart, a deploy, or a region failover Warming, gradual traffic ramp, serve-stale from a second tier

Cache penetration deserves its own sentence because the instinct is wrong. If an attacker requests product:999999999 a million times and that product does not exist, the cache can never help — there is no value to store, so every request reaches the database. Caching a tiny “does not exist” marker with a short TTL fixes the common case; a Bloom filter in front of the cache fixes the adversarial case, because it answers “definitely not present” with no lookup at all. Cold start, meanwhile, is a stampede over every key at once rather than one. Coalescing helps, jitter does not, and the only real defense is to not point full production traffic at an empty cache — ramp new instances in, or keep a warm second tier they can read from.


Fix One - Request Coalescing or Single Flight

The first and cheapest fix: inside one process, when N callers miss the same key, let exactly one of them do the work and have the other N minus 1 wait on that same in-flight result.

sequenceDiagram
    participant A as Request A
    participant B as Request B
    participant SF as In flight map
    participant DB as Database

    A->>SF: miss on key menu-42
    SF->>DB: recompute once
    B->>SF: miss on key menu-42
    Note over SF: already in flight<br/>B waits on the same future
    DB-->>SF: value
    SF-->>A: value
    SF-->>B: the same value
inflight = {}                       # key -> in-progress promise or future

def get(key):
    hit = cache.get(key)
    if hit is not None:
        return hit
    with lock:
        future = inflight.get(key)
        if future is None:          # I am the leader for this key
            future = executor.submit(load_and_store, key)
            inflight[key] = future
            future.add_done_callback(lambda _: inflight.pop(key, None))
    return future.result()          # followers block on the leader

The trade-off you must say out loud: this is per-process. Ten application servers each coalesce their own callers, so you go from 10,000 duplicate recomputes to ten — one per server. Ten is usually survivable and a hundred times better than ten thousand, but it is not one. Go’s singleflight package, Caffeine’s LoadingCache, and Guava’s loading caches all give you exactly this and exactly this limitation.


Fix Two - A Distributed Lock Around the Recompute

To get down to one recompute across the whole fleet, the leader election has to happen outside any single process. Use a short-lived lock in the cache itself.

def get(key):
    hit = cache.get(key)
    if hit is not None:
        return hit
    # SET IF NOT EXISTS with a short expiry. Exactly one caller wins.
    if cache.set(f"lock:{key}", me, nx=True, ex=5):
        value = db.query(key)
        cache.set(key, value, ex=300)
        cache.delete(f"lock:{key}")
        return value
    sleep(0.05)            # lost the race, read what the winner wrote
    return cache.get(key) or db.query(key)

Failure modes, which are the whole interview answer:

  • The lock holder dies before writing. Nobody refreshes until the lock’s own TTL expires, so every reader stalls for up to the lock TTL. Keep the lock TTL short — a small multiple of the expected recompute time, never minutes.
  • The lock holder is slow, not dead. The lock expires while it is still working, a second process starts recomputing, and now you have two writers racing to write the same key. Harmless for a cache; dangerous if the recompute has side effects, which is when you need Fencing Tokens.
  • Followers must decide what to do while waiting. Blocking is simplest. Returning stale data is better. Falling through to the database defeats the whole point and recreates the stampede.

This buys you cluster-wide single recompute at the cost of a round trip on every miss, plus a correctness story you now have to own. Reach for it when the recompute is genuinely expensive — a multi-second analytics rollup, an external paid API call — not for a 5 ms primary key lookup.


Fix Three - TTL Jitter

Most stampedes are self-inflicted by correlated expiry. If a deploy or a cache warm writes a million keys in the same minute, each with ex=3600, then an hour later a million keys expire in the same minute. The herd is not caused by popularity; it is caused by everything having been written together.

cache.set(key, value, ex=3600)                              # bad, all expire together
cache.set(key, value, ex=3600 + random.randint(-180, 180))  # good, spread over a band

Jitter is one line, has no failure mode, and should be your default on every write. But be precise about what it fixes: jitter desynchronises many keys from each other. It does nothing for a single hot key. One key has one expiry time no matter how randomly you chose it, and when that moment arrives all 50,000 readers still miss together. If your traffic is concentrated on a handful of keys you also have a skew problem — see Hot Partitions for how that same concentration hurts your storage tier.


Fix Four - Stale While Revalidate

Change the question. Instead of “how do I stop a thousand callers recomputing,” ask “why is anyone waiting at all?” Store two timestamps with the value: a soft TTL after which the value is considered stale, and a hard TTL after which it is actually evicted. Between those two points:

  1. A reader gets the stale value immediately.
  2. One reader — picked by coalescing or a lock — kicks off a background refresh.
  3. Nobody blocks. The database sees exactly one query. Readers see data that is a few seconds old.
written        soft TTL                 hard TTL
  |---------------|------------------------|
  fresh           serve stale and          evict
  serve as is     refresh in background    block or fail

The trade-off is freshness for availability, and it is usually the right default. A restaurant menu that is 30 seconds out of date is fine; a blank page is not. HTTP encodes this directly as Cache-Control: max-age=60, stale-while-revalidate=600, and every serious CDN implements it — see CDN. The related stale-if-error keeps serving the stale copy when the origin is down, which turns a database outage into a staleness incident. Where it does not apply: anything where a stale read is a correctness bug — account balances, inventory at checkout, permission checks. Those keys need one of the blocking fixes.


Fix Five - Refresh Before Anything Expires

The cleanest designs never let the hot key expire while traffic is on it.

Probabilistic early expiration, also called XFetch

Alongside the value, store how long the last recompute took. On every read, a caller may volunteer to refresh early, with a probability that rises as the expiry approaches and rises with how expensive the recompute is. Said in words: the closer you are to expiry, the more likely any given reader decides to refresh now, and the more expensive the last recompute was, the earlier that willingness starts — because an expensive value is one you really do not want to be caught without.

The random draw is what stops this becoming a stampede of its own. Each reader decides independently, so in practice one reader crosses the threshold first, refreshes, and extends the expiry before anyone else draws a number high enough to join in.

# delta  = how long the last recompute took, in seconds
# beta   = tuning knob, 1.0 is the usual starting point
# expiry = absolute time this key expires
early = delta * beta * -math.log(random.random())
if time.time() + early >= expiry:
    refresh_in_background(key)
return value          # the caller is never blocked

This cuts duplicate recomputes to near zero with no lock, no coordination, and no extra round trip. The cost is that it only protects keys being read — a key with no traffic still expires cold.

Refresh-ahead by a background job

If your hot set is small and known — the top 500 products, the ten feature-flag bundles, the homepage feed — stop making user requests responsible for refreshing it. A background worker rewrites those keys on a schedule shorter than their TTL, so user requests only ever see hits. This is the lowest-latency option available and the easiest to reason about, but the limits are real: you must know the hot set, you pay for refreshes nobody reads, and it scales with the size of the set rather than with traffic. Fine for hundreds of keys, useless for hundreds of millions.


Comparing the Fixes

Fix What it actually prevents What it does not prevent Cost
Coalescing / single-flight Duplicate recomputes within one process N recomputes across N servers Almost none, in-process only
Distributed lock Duplicate recomputes fleet-wide Stalls if the holder dies mid-work A round trip per miss, plus lock correctness
TTL jitter Correlated expiry of many keys A single hot key expiring One line, no downside
Stale-while-revalidate Any reader ever blocking on a miss Serving data that is seconds old Freshness, and two TTLs to manage
Probabilistic early refresh Expiry happening at all on read keys Keys with no traffic going cold A few lines, needs tuning
Refresh-ahead job Misses on the known hot set Anything outside that set Wasted refreshes, must know the set

In practice you stack them. A sound default for a read-heavy service is jitter on every write, coalescing in every process, and serve-stale on every read — all three are close to free. Add a lock or probabilistic early refresh only for the specific keys whose recompute runs into hundreds of milliseconds, costs money per call, or carries a large share of total traffic.

❌ Do not reach for the heavier fixes when:

  • The “expensive” query is a 2 ms indexed lookup — the lock costs more than the work
  • The key has no concurrency, so there is no herd to coalesce
  • Your real problem is non-existent keys, which is penetration and wants a Bloom filter
  • Your real problem is an empty cache after a deploy, which is cold start and wants a traffic ramp

Why Raising the TTL Is Not a Fix

The reflex when a stampede takes down the database is to raise the TTL from 60 seconds to an hour. That is a worse system, not a safer one.

  • It changes the frequency, not the size. The herd is still 10,000 duplicate recomputes; you now get one per hour instead of one per minute. The outage is rarer and therefore more surprising, and you will have forgotten about it by the time it fires.
  • It makes the herd bigger. A longer gap means a colder path — query plan evicted, buffer pool no longer holding the pages — so the recompute that defined your window is now slower, which widens the window and admits more requests.
  • You pay in staleness for nothing. Every user reads data up to an hour old, a real product cost, and the failure is still there.
  • It does nothing for cold start. A flush, a deploy, or a failover empties the cache regardless of the TTL.

A long TTL combined with serve-stale and background refresh is a good design. A long TTL on its own is a postponed incident.


Common Interview Questions

Q1: Walk me through exactly why a cache stampede escalates instead of draining.

The size of the herd is request rate multiplied by recompute latency. At 50,000 reads per second on one key and a 200 ms recompute, 10,000 duplicate queries are in flight. That saturates the database, so the recompute now takes 2 seconds, so the next instant has 100,000 in flight. The variable that was supposed to be fixed — recompute latency — is itself a function of the load the stampede created. That is a positive feedback loop, which is why it ends in an outage rather than a spike, and why recovery is hard: fixing it requires the database you just melted.

Q2: Why is in-process coalescing not a complete fix, and what does it actually buy you?

The in-flight map lives in one process’s memory, so it can only deduplicate callers inside that process. With ten application servers you get ten recomputes instead of one. That is still a 1000x reduction from 10,000, which is usually the difference between an incident and a blip, so it is absolutely worth having. To get to exactly one you need coordination outside the process — a short-lived lock in Redis, or a dedicated refresher that owns the key.

Q3: TTL jitter is cheap and has no downside. So why isn’t it enough?

Jitter solves correlated expiry — a million keys written during the same deploy all expiring in the same minute. It desynchronises keys from each other. But a single key has exactly one expiry moment no matter how you randomised it, and every reader of that key still misses simultaneously when it arrives. Jitter is a universal default and a complete answer only when your traffic is spread across many keys. Concentrated traffic on one key is a skew problem too, and it shows up again in your storage tier as a hot partition.

Q4: When would you refuse to serve stale data, and what do you do instead?

When a stale read is a correctness bug rather than a cosmetic one — an account balance before a withdrawal, inventory at checkout, an authorisation decision after a permission was revoked. For those keys you accept that readers block, and you make the blocking cheap: a short-lived distributed lock so exactly one process recomputes, a bounded wait for the followers, and a fast failure if the wait is exceeded. The decision is per key class, not per service, so it is normal to serve stale menus and strictly consistent balances from the same cache.

Q5: A team says they fixed their stampede by raising the TTL from one minute to one hour. What do you tell them?

That they changed the frequency and not the size. The same 10,000 duplicate recomputes still happen; they now happen once an hour. Worse, the longer gap means the data pages and query plan have fallen out of memory, so the recompute is slower, which widens the miss window and makes the herd bigger. They have also made every read up to an hour stale, and they still have no answer for the cache being empty after a deploy. The hour-long TTL becomes a good design the moment they add serve-stale and a background refresh on top of it.


← Caching Rate Limiting →
All Concepts HLD Designs