Protect against a cache stampede
A popular key expires and every request misses at once, flattening the database (dog-piling).
Basic solution
Serve the stale value while one request refreshes it, lock the refresh so only one caller fetches, and stagger TTLs with jitter so keys do not expire together.
One refresher, everyone else served stale
At expiry the first request wins the refresh lock and reloads from the database. Concurrent requests get the stale value immediately instead of piling onto the database.
How it works
- A request reads key K from the cache and sees that the entry is expired or inside its refresh window (close to expiring).
- It tries to become the one refresher by taking a short lock: SET lock:K NX PX 2000 creates the lock only if nobody holds it (NX) and makes it expire after 2 seconds (PX) so a crashed refresher cannot hold it forever.
- The request that won the lock reads the database, writes the new value into the cache with a fresh TTL, and deletes the lock.
- Every request that lost the lock does not touch the database. It returns the previous value if the cache still holds it (stale-while-revalidate), or, inside one process, waits on the winner's in-flight promise and gets the fresh value when it arrives (single-flight).
- When any value is written, its TTL is multiplied by a random factor between 0.9 and 1.1 (jitter), so a batch of keys written at the same time expires spread over a window instead of all at once.
Serving stale needs two timestamps
- Each value is stored with a logical expiry (the time after which it should be refreshed) and a longer physical TTL (the time after which Redis may drop it). Between those two points reads still succeed with the old value while one refresh runs in the background.
Worked example
URL shortener viral link
- One alias gets 50K redirects/s during a spike. Its cache entry has a 5-minute TTL.
- Without protection: at expiry, every in-flight request misses. With 3 ms database latency and 50K req/s, ~150 concurrent identical queries hit the database at once, and that repeats every 5 minutes.
- With single-flight per app server: 20 servers each coalesce their own requests, so at most 20 database reads per expiry instead of 150+. Adding a Redis refresh lock across servers makes it 1.
- With stale-while-revalidate: zero requests wait. Logical expiry at 5 min, physical TTL at 6 min. The one refresher takes 3 ms; the other 50K requests in that window return the 5-minute-old long URL, which is fine for a redirect.
- Jitter: 1M keys written in the same second during a warm-up would all expire in the same second 5 minutes later. With 10% jitter on a 5-minute TTL they expire across a 60-second window (4.5 to 5.5 minutes) instead of a 1-second spike.
Variants and when each wins
Stale-while-revalidate
- Readers keep getting the old value while one caller refreshes it in the background. It wins for read-heavy data that can be a few seconds old, because no request ever waits on the database.
Refresh lock (mutex) with waiting
- Readers that lose the lock wait for the winner and then read the fresh value. It wins when stale data is not acceptable, at the cost of every waiting request paying the refresh latency, and the lock needs a TTL so a crashed winner does not block everyone.
Early probabilistic refresh (XFetch)
- Each read refreshes the entry with a probability that rises as expiry approaches, so the refresh usually happens before anyone misses. It wins for a moderate number of warm keys because it needs no lock at all.
Never expire plus background refresh
- A worker refreshes a fixed list of very hot keys on a schedule and the entries have no TTL. It wins for the top few hundred keys because the request path never refreshes anything, but someone has to own and maintain that list.
Recommendation: stale-while-revalidate with a refresh lock, plus TTL jitter everywhere; schedule background refresh for the top few hundred keys.
Failure modes
Winner dies holding the lock
- You notice a key stays stale for a couple of seconds and then the database spikes anyway. It happens because the request that won the refresh lock crashed before writing the new value, so nobody refreshed until the lock expired and everyone missed together. Fix it with a short lock TTL of a few seconds, and losers that serve the stale value rather than wait, so a dead winner only delays the refresh.
Cold start stampede
- You notice every key misses at once after a deploy or a cache node restart. It happens because the cache is empty, so there is no stale value to serve while refreshing. Fix it by warming the top keys from a list before taking traffic, restarting cache nodes one at a time, and replicating the cache so a restart never empties the only copy.
Stale forever
- You notice a value that never refreshes even though its data has changed. It happens because the refresh keeps failing, the error is swallowed, and the stale value keeps being served. Fix it by capping how long stale may be served (the physical TTL) and alerting on the refresh error rate.
Jitter not applied on bulk loads
- You notice a database spike exactly one TTL after each batch job runs. It happens because the batch wrote thousands of keys in the same second with the same TTL, so they all expire in the same second. Fix it by applying jitter wherever values are written, not only on cache-aside loads.
Lock contention across many keys
- You notice the lock calls themselves show up as a hot spot in Redis. It happens because every read of every key is attempting a lock. Fix it by only attempting the lock when the entry is inside its refresh window, so normal reads never touch the lock.
Interviewer follow-ups
Answer out loud before you open each one.
What is the difference between a cache stampede and a thundering herd?
A stampede is the specific case of one popular key expiring and all its readers missing at once. A thundering herd is the general pattern of many clients acting at the same instant, such as reconnects after an outage or retries aligned to the same backoff. The fixes overlap: jitter, coalescing, and serving stale.
How do you implement single-flight across many app servers, not just inside one process?
Use a short-lived lock in the shared cache: SET lock:key NX PX 2000. The winner refreshes; losers either serve the stale copy or poll the key briefly. In-process single-flight still matters because it removes the lock calls themselves from the hot path.
Is serving stale data acceptable?
For most read-heavy data, yes, if you bound it: a redirect target or a feed can be a few seconds old. For a balance or an inventory count it is not; there you use the lock-and-wait variant and accept the latency, or route to the primary.
How much jitter is enough?
Enough to spread a batch of expiries over a period the database can absorb. 10 to 20 percent of the TTL is the usual range: a 5-minute TTL becomes 4.5 to 5.5 minutes, so a million entries written in the same second expire over about a minute rather than at once.
Connections
- In study paths
- Scaling reads · Feeds and fan-out
- Built on
- LRU cache: hash map + doubly linked list
- Pairs with
- Cache the hot reads · Collapse duplicate in-flight requests · Avoid synchronised stampedes · Spread a hot key
- Pulls against
- Accept a short delay for scale
- Used in
- Distributed Key-Value Cache (Redis / Memcached-like) · URL Shortener (TinyURL / bit.ly)
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon ElastiCache | Redis | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon Aurora | Database | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |