Zum Hauptinhalt springen

The Thundering Herd: Turning N Cache Misses Back Into One

· 10 Minuten Lesezeit
Clustron Team
Engineering für verteilte Systeme

Caching works by arithmetic. A value that costs 200 milliseconds and a heavy database query to compute gets stored under a key, and for the next ten minutes every request for it is served from memory in microseconds without touching the database at all. If that key sees ten thousand requests a second, the cache is absorbing ten thousand requests a second and the database is seeing, effectively, none. That ratio — the whole point of the cache — is also exactly what makes its failure mode so violent.

Because the ten minutes end. The key expires, and in the microsecond after it does, the ten thousand requests per second that were all being served from that one cached value all miss, simultaneously. Each of those requests, finding nothing in the cache, does the natural thing: it recomputes the value — runs the heavy query, hits the backend. So the backend that was sized for the cache-protected load, perhaps a handful of queries a second, is suddenly handed ten thousand identical expensive queries in the same instant. It does not serve them faster for their being identical. It saturates, queues, and falls over, and the cache miss you thought was a microsecond of latency has become a full outage of the system the cache existed to protect.

This is the cache stampede — the thundering herd, the dogpile — and it has a nasty self-sustaining quality: while the herd is all recomputing, the key is still empty, so every new request that arrives also misses and joins the herd. The stampede feeds itself until the backend dies or the herd drains. The fix is not a bigger backend, because any backend can be swamped by a hot enough key. The fix is to stop letting N misses each act as if they were alone.

One miss should cost one recompute​

Step back and state what should happen. A cache miss on a hot key means the value needs recomputing — once. There is exactly one correct new value, and computing it ten thousand times in parallel produces ten thousand identical results at ten thousand times the cost. The right behavior is single-flight: the first caller to notice the miss recomputes the value and populates the cache, and every other caller that misses during that window does not recompute — it waits for the first one's result. N concurrent misses collapse into one recompute and N−1 cheap waits.

The hard part is that "the first caller" is not a meaningful idea inside a single process. Your service runs on fifty instances behind a load balancer, and the herd is spread across all of them. A per-process lock — a local mutex around the recompute — coalesces the misses within one instance, so each instance recomputes once instead of two hundred times. That is a 200× improvement and still fifty times too many: fifty instances, fifty simultaneous recomputes, a backend still taking fifty times its protected load. Real single-flight has to coordinate across the whole fleet, and coordinating across the fleet means a piece of shared state every instance can agree on. That is precisely what a distributed lock is for.

A distributed lock, held just long enough​

The mechanism is a lock keyed on the cache key itself. On a miss, a caller does not immediately recompute — it first tries to acquire a lock named after the key. Acquisition has exactly one winner across the entire fleet.

value = cache.Get(key)
if (value is present) return value // the common path — no lock, no wait

// Miss. Elect one recomputer across the whole fleet.
if (lock.TryAcquire("recompute:" + key, lease: 10s)) {
try {
value = backend.Compute(key) // the single, expensive recompute
cache.Put(key, value, ttl: 10m)
return value
} finally { lock.Release("recompute:" + key) }
} else {
// Someone else is already recomputing. Don't stampede — wait briefly,
// then read the cache they are about to populate.
await small_backoff()
return cache.Get(key) ?? backend.Compute(key) // fallback only if still absent
}

The winner recomputes and populates the cache. The losers — the other 9,999 requests a second — take the else branch: they back off for a moment and re-read the cache, which the winner has by then filled. The backend sees one query, not ten thousand. The herd has been funnelled through a single door.

No coordination: key expires → every miss recomputesrequests10,000 missesall recomputebackendsaturates ✗Single-flight: a distributed lock elects one recomputerrequestslock on key1 winner · rest wait1 querybackendserene ✓winner fills cache → waiters re-read it, no recomputeN misses funnelled through one door → backend sees one query

Why the lease on the lock is not optional​

There is a failure in the single-flight scheme that will eventually find you, and it is the reason the lock must carry a TTL — a lease — rather than being held until explicitly released. The winner acquires the lock and begins the expensive recompute, and then it crashes: an OOM, a deploy, a node reboot, mid-query. If the lock is held forever until release, it is now held by a process that no longer exists. Every other caller takes the else branch, waits, re-reads an empty cache, and waits again — forever. The hot key is permanently wedged, and you have converted a transient stampede into a permanent one, which is worse.

A lease fixes this by making the lock expire on its own. The winner holds it for at most, say, ten seconds; if the winner does not release it — because it died — the lease lapses and the lock becomes acquirable again, so a new caller takes over the recompute. The lease length is a judgment call: long enough to cover a normal recompute, short enough that a crash does not wedge the key for long. This is why Zaris's distributed locks are lease-based: a lock you can hold forever is a lock that a single crash turns into a deadlock, and the one scenario single-flight exists to survive — a caller dying mid-recompute — is exactly the one an un-leased lock cannot.

Smoothing the edge: don't let the herd gather at all​

Single-flight stops the backend from being flooded, but the N−1 waiters still take a small latency hit while the one winner recomputes — a brief blip each time a hot key expires. Two refinements soften it, and both are worth knowing even if you reach for them only on your hottest keys.

The first is to serve the stale value while one caller revalidates. Keep the old value available past its logical expiry and hand it to the herd while the winner recomputes in the background; readers get an answer immediately, slightly stale, and the fresh value swaps in when it is ready. The second is to desynchronize expiry: instead of letting a key expire at a hard instant, have callers probabilistically recompute it a little early, in the background, with a probability that climbs as the deadline nears. The hot key is refreshed before it ever expires, so the herd never gathers at a cliff edge because there is no cliff. Both trade a touch of freshness for the disappearance of the blip, and both compose cleanly with the lock — the lock still guarantees one recompute, these just decide when it happens.

Wrap-up​

A cache is a bet that one expensive computation can serve many cheap reads, and a stampede is that bet collapsing all at once: the instant the cached value is gone, every reader becomes a writer, and the backend meets the full unprotected load in a single synchronized spike. The defense is coordination, not capacity — electing a single recomputer across the whole fleet with a distributed lock, so a miss costs one recompute and a crowd of waits rather than a crowd of recomputes. Lease the lock so a dying winner cannot wedge the key, serve stale or refresh early on your hottest keys to erase the latency blip, and the cache keeps doing its job through the one moment it is most tempted to stop: the moment it is empty and everyone wants in at once.