Cache stampede and how to survive it
One entry expires
Section titled “One entry expires”A product page is cached for 12 seconds, and it is popular: hundreds of requests a second ask for it. At the moment its entry expires, the next request misses and starts rebuilding it. But the rebuild is slow, say 250 milliseconds, and the entry is only stored when the rebuild finishes. In those 250 milliseconds, every other request for the same page also misses. In plain cache-aside, each of them starts its own rebuild.
That is a cache stampede. The paper that studied it puts the arithmetic simply: if an item is read 10 times a second and takes 3 seconds to recompute, 30 requests will recompute it, all for the same answer. The cost grows with the request rate and with how slow the rebuild is.
The danger is not the wasted work. It is that the extra reads go to the part of the system that is slow because it is already busy. More reads make each one slower, which makes more requests miss before any rebuild finishes. A stampede feeds itself, and that kind of feedback, in which overload slows the work and the slowness brings more load, is how the Google SRE book describes a small event turning into an outage.
See it happen
Section titled “See it happen”The lab is built to show a stampede. One very popular key takes 85% of the traffic, and rebuilding it is slow. Every key was stored at the same moment when the lab started, so every key expires together.
One very popular key sits in the cache, and recomputing it is slow. When it expires, every request that arrives before it is stored goes to the database at once. Every other key was stored at the same moment, so they all expire together as well. Turn on mitigations before the keys expire (about 6 seconds in), or restart and compare.
- Cache hit
- Cache miss, goes on to the database
- Waits for another request’s read
- Request fails
Each dot stands for many requests. The numbers show the real rate.
Hit ratio 100%: 0% of requests reach the database (0 reads/s, capacity 24/s).
History
Database queue (most waiting)
0Use the left and right arrow keys to read values at each moment.
p99 latency
0.87 msUse the left and right arrow keys to read values at each moment.
Requests that fail
0%Use the left and right arrow keys to read values at each moment.
Data table
| Simulated time | Database queue (most waiting) | p99 latency | Requests that fail |
|---|---|---|---|
| 1 s | 0 | 0.91 ms | 0% |
| 6 s | 0 | 0.87 ms | 0% |
| Component | State | Utilisation | Queue |
|---|---|---|---|
| Cache, Shard 1 | Healthy | <1% | 0 |
| Cache, Shard 2 | Healthy | <1% | 0 |
| Cache, Shard 3 | Healthy | 7% | 0 |
| Cache, Shard 4 | Healthy | <1% | 0 |
| Database | Idle | 0% | 0 |
- Traffic
- 1.5K/s
- Successful
- 1.5K/s
- Error rate
- 0%
- Hit ratio
- 100%
- Database reads
- 0/s
- p50
- 0.14 ms
- p95
- 0.61 ms
- p99
- 0.93 ms
- Entries cached
- 100 / 100
- Requests that write
- 0%
- Stale hits
- 0%
- Coalesced requests
- 0/s
- Skipped the cache
- 0/s
Figures describe the last 5 simulated seconds.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Each request asks for a key drawn independently from a fixed popularity distribution. Real traffic has bursts and trends that this does not capture.
- Every operation on a cache shard (lookups, stores, deletions) joins one queue served by a few slots, so a busy shard slows everything on it.
- 85% of requests ask for one key. The rest are spread evenly over 99 others. The database takes about a quarter of a second per read.
Simplifications
- An entry’s lifetime starts when it is stored. Reading it does not extend it.
- Only a version number is tracked for each key, not the data. A cached copy is stale when its version is behind the database’s.
- The cache never runs out of memory, so no entry is evicted early. Real caches evict the least recently used entries when they are full.
- A write updates the database and then deletes the cached copy (cache-aside). Write-through and write-behind are compared in the trade-off explorer, not simulated here.
- Refresh before expiry reloads an entry in the background when a request reads it in the last part of its life. Production systems often use a probabilistic variant.
- A cache that goes down loses everything it held and comes back empty. A cache with persistence would not.
- The application learns that the cache is down at once, on the request that fails. Health checks and circuit breakers are not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
Parameter values are illustrative. They are not benchmarks of any real product.
Leave all the mitigations off and press Play (or Restart if you want to see it from the start). Around the 12-second mark the hot key expires, and again 12 seconds later. Watch the three charts: Database queue (most waiting), p99 latency and Requests that fail.
With nothing turned on, in the first 30 seconds up to 155 reads for the same single key are in flight at once, the database queue reaches its limit of 150, and about 12% of requests fail.
Two things go wrong at the same moment
Section titled “Two things go wrong at the same moment”Read the lab’s summary again. It describes two separate problems:
- A crowd forms on one key. The hot key’s entry is gone, so everyone who wants it rebuilds it.
- Many keys expire together. Everything was stored at the same moment with the same lifetime, so everything expires at the same moment. This happens in real systems whenever a lot of entries are written together: after a deploy that warms the cache, after a restart, after a batch job.
A mitigation usually helps one of the two. Knowing which is how you choose.
The names vary. The research paper calls this problem a cache stampede, dog-piling, a cache miss storm or cache choking. Facebook’s memcache paper uses “thundering herd” for a related case, a key that is read and written so often that its entry keeps being invalidated, so that many reads fall through to the database.
Three mitigations
Section titled “Three mitigations”Request coalescing answers the crowd on one key. The first request that misses does the rebuild. The others wait for its result instead of starting their own. Go’s singleflight package describes exactly this: a duplicate caller waits for the original to complete and receives the same result. In the lab, switch on Request coalescing.
// Request coalescing (single flight): while one request reloads a key,// the others wait for that same read instead of starting their own.using System.Collections.Concurrent;using ShardCraft.Playground;
var clock = new FakeClock();var databaseReads = 0;var requests = 50;
// The database is slow: every read takes 200 ms.async Task<string> ReadFromDatabaseAsync(string key){ Interlocked.Increment(ref databaseReads); await clock.Delay(TimeSpan.FromMilliseconds(200)); return $"value of {key}";}
void Report(string label) => Console.WriteLine($"{label,-18} {databaseReads,3} database reads for {requests} requests");
// 50 requests arrive for a hot key that has just expired.// Each one makes its own read.var unprotected = Enumerable.Range(0, requests) .Select(_ => ReadFromDatabaseAsync("hot-key")) .ToArray();clock.Advance(TimeSpan.FromMilliseconds(200));await Task.WhenAll(unprotected);Report("without coalescing");
// The same 50 requests, now sharing one read.databaseReads = 0;var singleFlight = new SingleFlight<string>();var coalesced = Enumerable.Range(0, requests) .Select(_ => singleFlight.RunAsync("hot-key", () => ReadFromDatabaseAsync("hot-key"))) .ToArray();clock.Advance(TimeSpan.FromMilliseconds(200));await Task.WhenAll(coalesced);Report("with coalescing");
class SingleFlight<T>{ private readonly ConcurrentDictionary<string, Lazy<Task<T>>> _inFlight = new();
public async Task<T> RunAsync(string key, Func<Task<T>> load) { // The first caller for a key creates the read. // Callers that arrive while it runs get the same one. var flight = _inFlight.GetOrAdd(key, _ => new Lazy<Task<T>>(load)); try { return await flight.Value; } finally { // Remove only this read, so that a late waiter never removes // a newer read for the same key. _inFlight.TryRemove(KeyValuePair.Create(key, flight)); } }}without coalescing 50 database reads for 50 requestswith coalescing 1 database reads for 50 requestsThis is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
TTL jitter answers many keys expiring together. Instead of giving every entry the same lifetime, give each a lifetime that varies by a random amount, say plus or minus 40%. Entries stored together now expire apart. In the lab, move TTL jitter to about 40%.
Refresh before expiry answers both partly: it makes sure there is no moment when the entry is missing. A read in the last part of an entry’s life reloads it in the background while the old value is still being served, so by the time the old one expires a new one is already there. The paper cited in this lesson studies the better version of this idea: each request independently decides, with a probability that rises as the expiry approaches, whether to recompute early. Their result is that a particular probabilistic rule, which they call XFetch, is optimal and needs no tuning to the request rate. In the lab, switch on Refresh before expiry.
Other approaches exist and have their own costs. A background process can regenerate hot entries on a schedule, which means running and watching another component. A lock per key lets one request rebuild while the rest wait or serve something else, and it needs a lifetime for the lock itself and a plan for when its holder fails. Facebook’s leases are a lock-like token: by default the cache hands out one token per key every 10 seconds, and requests that arrive meanwhile are told to wait briefly and retry.
What each one does in the lab
Section titled “What each one does in the lab”These are the figures for the first 30 seconds, from the same lab, with the mitigations switched on one way or another.
| Mitigations | Most reads for one key in flight at once | Peak database queue | Requests that fail |
|---|---|---|---|
| None | 155 | 150 | 12% |
| Request coalescing | 1 | 66 | 0.2% |
| Refresh before expiry | 5 | 63 | 0% |
| Coalescing and jitter | 1 | 1 | 0% |
| Refresh before expiry and jitter | 2 | 2 | 0% |
Look at the second row. Coalescing ended the crowd on the hot key, and the number of reads for it fell from 155 to 1. But the queue still reached 66, because 99 other keys were expiring together. Only adding jitter fixed that. Try Jitter alone: it does nothing for the crowd on the hot key, which is still about 150 reads at once.
That is the point of the exercise: the two problems are different, so a mitigation for one is not a mitigation for the other.
What happens if the rebuild is slow, or fails?
Section titled “What happens if the rebuild is slow, or fails?”Coalescing makes everyone wait for one rebuild. That is exactly what you want when the rebuild is slow and succeeds. If it fails, or takes far longer than usual, all the requests waiting for it fail or wait with it. Give the shared rebuild a timeout, and decide what the waiting requests should do when it fires: an error, or an old value if you kept one.
Coalescing inside one application process also does not coordinate between processes. With 20 instances, a hot key can still be rebuilt 20 times at once, once per instance. That is much better than 2,000, and it is not one.
Trade-offs
Section titled “Trade-offs”| Mitigation | What it protects | What it costs | When it is not enough |
|---|---|---|---|
| Request coalescing | The database from a crowd on one key | Everyone who waits shares the rebuild’s fate and its delay | Many different keys expiring together |
| TTL jitter | The database from keys expiring together | Entries are fresh for different lengths of time | A single hot key that expires |
| Refresh before expiry | Readers from ever seeing a missing hot entry | Extra database reads for entries nobody may ask for again | An entry nobody asked for in its last moments still expires and is missed |
| Locks and leases | The database, and stale sets too | More moving parts, and a plan for a holder that fails | A holder that dies and a lock that does not expire |
Your turn
Section titled “Your turn”Keep the database alive through the moment the keys expire. Choose the settings, then run a 45-second test. You succeed when all three goals are met. Each setting on its own leaves part of the problem.
Challenge
Survive the stampede
Keep the database alive through the moment the hot key expires. Choose the settings, then run a 45-second test. You succeed when all three goals are met.
Running the test needs JavaScript.
Goals
- No more than 0.1% of requests fail
- No more than 40 reads ever wait for the database
- The hit ratio stays at 95% or more
Settings
Run the test at least once before looking at the solution.
Then check your understanding:
Check your understanding: cache stampede
This quiz needs JavaScript to check your answers.
- A stampede happens when many requests miss the same entry at once and each rebuilds it. The extra reads slow the rebuild, which causes more misses.
- It has two separate causes: a crowd on one key, and many keys expiring together.
- Request coalescing ends the crowd on a key. TTL jitter spreads out the keys that expire together. Refresh before expiry means the entry is never missing at the moment it is needed.
- Each mitigation has a price: shared fate, uneven freshness, extra reads, or extra machinery.
- Choose by naming which of the two problems you have.
Next: what happens when one key is not just popular but dominant, and the part of the cache that owns it cannot keep up.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.