Request coalescing and leases
Letting the first request that misses on a key fetch the value while later requests wait for its result, plus a lease token that lets the cache refuse a stale value written back by a slow reader.
What it is
A cache stampede (also called dog-piling or a thundering herd) happens when a cached value that many requests depend on disappears, through expiry, a delete or a restart, and each request that misses at that moment recomputes it at the same time. None of them knows the others are doing the same work. Wikipedia's example: a page that takes 3 seconds to render, under 10 requests per second, means about 30 renders start together when the cached copy expires, each one loading the database. Under enough load the recomputations time out before any of them finishes and refills the cache, so the hit rate stays near zero and the overload feeds itself.
Request coalescing (also called single-flight or a cache lock) is the fix at the point of the miss: the first request to miss on a key does the fetch, and later requests for the same key that arrive while that fetch is in flight wait for it and receive the same result instead of starting their own. Go's golang.org/x/sync/singleflight (v0.25.0) is the in-process form. Do(key, fn) runs fn for one key at a time, hands the same value and error to each duplicate caller that arrives mid-flight, and reports through a shared flag whether the result went to more than one caller. Forget(key) drops the in-flight entry so the next call runs fn again. Its reach is one process: with many service instances, a hot key can still produce one fetch per instance.
A reverse proxy can coalesce for HTTP. In nginx, proxy_cache_lock (added in 1.1.12, off by default) lets a single request populate a new cache entry for a given cache key by going to the upstream; other requests for that entry wait for the response to land in the cache or for the lock to be released, up to proxy_cache_lock_timeout (default 5 s). A request that waits out the timeout is passed to the upstream, but its response isn't cached. proxy_cache_lock_age (default 5 s) lets one more request through if the fetch holding the lock hasn't finished within that time, so a stalled fetch doesn't block the key for long.
A lease moves coalescing into the cache server and adds a correctness check. In the design Facebook described for its memcache fleet in its 2013 paper, a cache server that misses on a key hands the client a 64-bit token bound to that key. The client reads the database and sets the value along with the token, and the server checks the token before storing. When a delete for that key arrives, the server invalidates any outstanding tokens for it, so a set that shows up afterwards with an old token is ignored and the key stays empty until the next reader loads the latest row. That blocks a stale set: an old value written back after a newer write already invalidated the key, which can happen when concurrent updates to one key get reordered. The same servers hand out a token for a given key once per 10 seconds; a client that misses inside that window has to wait, on the expectation that the holder has filled the key by the time the waiter retries.
# Sketch only: the shape of a lease read path, not a real client API.
value, token = cache.get(k)
if value is None:
if token is None: # in this sketch, no token means: wait briefly, then retry
wait_briefly()
retry
value = db.read(k)
cache.set(k, value, token) # refused if a delete invalidated the token
return valueWhen to use it
Reach for coalescing when the same key is read by many callers at once and refilling it is expensive: a popular product page, a feed header, a config blob all servers read at startup, a live video segment each viewer wants in the same second. The cost you're cutting is the peak, not the average: a database sized for its steady miss rate is the one a herd of simultaneous misses takes down.
Use a lease, not just a lock, when the same keys see heavy reads and heavy writes together: each write deletes the cached copy, so misses keep coming, and a slow reader can write back a value that a later write already replaced and leave it there until the next write. A lease addresses both at once. Decide separately what waiters receive: block until the holder fills the key, return a not-found that the caller handles, or hand out the previous value while the refresh runs.
Our advice in a design round: say which layer coalesces. In-process single-flight is nearly free and removes duplicates inside one instance; a proxy lock protects the origin for cacheable HTTP; a lease protects a shared cache that many instances fill. For a large fleet the shared layer is the one that matters, because per-instance coalescing still lets each instance send its own fetch.
When not to
Skip it when no two requests share a key at the same moment: keys indexed by user, long-tail content, or a cache whose misses are rare and spread out. Coalescing changes nothing there, and the lock adds a write per miss. Wikipedia lists the price of the locking approach: an extra write for the lock, plus the hard parts of doing it right, such as the holder crashing, choosing the lock's lifetime, and races between contenders.
When a few seconds of staleness are fine, serving the old copy beats making anyone wait. nginx can do this with proxy_cache_use_stale updating, which returns the stale response while an update is in progress, and proxy_cache_background_update (added in 1.11.10), which starts that refresh as a background subrequest so the client gets the stale copy at once; since the same version it also honors stale-while-revalidate from the response headers. For keys with steady traffic, probabilistic early expiration avoids coordination: each caller may refresh before expiry with a probability that rises as expiry nears, so refreshes spread out instead of piling up. It helps a key that's already cached; a key that isn't present yet misses in the usual way.
Don't share a result across callers unless the key captures everything the result depends on: a response that varies by user, locale or authorization header, coalesced under a key built from just the URL, can hand one user's data to another. And keep writes out of it: coalescing exists for reads that produce the same answer for everyone asking, and two writes that look alike are usually two separate intents.
Compared
| Approach | Where it runs | Waiting callers get | Pick it when |
|---|---|---|---|
Single-flight (Go | Inside one process | The same value and error as the first caller | Few instances, or an in-process cache; the simplest to add, but each instance still fetches once |
Proxy cache lock ( | Reverse proxy or edge | A wait up to a timeout, then an uncached pass-through | Cacheable HTTP shared by many users, with the origin as the thing to protect |
Lease in the cache | The cache server | A short wait, then a retry that usually hits | Many instances fill one shared cache, and the same keys see heavy reads and writes |
Serve stale while one refresh runs | Proxy or application | The previous value at once | Seconds of staleness are acceptable and latency matters more than freshness |
Probabilistic early refresh | Each caller, independently | Any caller whose random draw says refresh recomputes the value itself; callers whose draw says no keep reading the cached copy | Keys with steady traffic where you want no lock and no coordination |
In a picture
Step 1 of 5
Three misses, three queries
A hot key is gone. Requests A, B and C miss in the same moment and each goes to the database on its own.