Thundering herd
medium 24 minA thundering herd, or cache stampede, happens when many requests find the same cached value missing at the same moment and all rebuild it.
Video lesson · Chapter 1 of 5
Ten requests arrive at the same missing product
Thundering herd in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 1 min.
What it is
A cache protects the database as long as most reads find their value. When a popular value disappears, every reader misses at once. Each one does the sensible thing, which is to ask the database and store the result. Together they do the same work hundreds of times.
This is a cache stampede. The wider name, thundering herd, covers any case where many waiters wake up for one event although only one can make use of it.
Why it exists
A database sized for a 99% hit rate sees only 1% of the reads. If one hot key with a large share of the traffic goes missing, its load can jump many times over within a second.
Worse, the load feeds itself. A slow database makes the rebuild slower, so more readers arrive before it finishes. Timeouts cause retries, and a short gap can become an outage.
A short history
May 2010
RFC 5861 defines stale-while-revalidate, so that HTTP caches can answer while they refresh.
April 2013
Facebook engineers publish "Scaling Memcache at Facebook". Their leases deal with stale sets and thundering herds.
2015
Vattani, Chierichetti and Lowenstein publish "Optimal Probabilistic Cache Stampede Prevention", with the XFetch algorithm.
Words to know
- Hot key
- A key that receives a large share of the reads.
- Rebuild
- Fetching or computing a missing value and storing it.
- Single flight
- Joining identical calls so that only one runs at a time.
- Lease
- A permission to fill a key, given to one reader for a short time.
- Soft TTL
- After it, the value is stale but may be used while it is refreshed.
- Hard TTL
- After it, the value may not be used.
- XFetch
- Refreshing early with a probability that rises towards expiry.
How it works
Step through the idea, or press Play.
A hot value disappears. It expires, is deleted or the cache restarts
Understand it
Start here
Ducks and the feed box
Imagine six ducks and a feed box. While there is feed, nobody bothers the person who looks after them. When the box is empty, they all run to that one person.
The ducks need one refill, not six.
The problem
When it happens
Expiry
The TTL of a popular key ends.
Invalidation
The key is deleted because the data changed.
Cold restart
The cache restarts empty, so every key is missing.
Same TTL
Many keys stored together expire together.
The cascade
- 1
12:00:00
The key for product 123 expires.
- 2
12:00:01
100 requests arrive for it.
- 3
All miss
Nobody has stored a new value yet.
- 4
All query
100 identical queries reach the database.
- 5
Overload
CPU and connections are used up. The answer that took 10 ms may now take seconds, callers time out and retry.
Without protection
How big is the herd?
Why it feeds itself
Solution 1
One process: single flight
Inside one server, keep a map of rebuilds that are running. The first caller starts the work, later callers for the same key wait for that result. Go has the singleflight package for exactly this.
It needs no network and no lock service. Its limit: 20 servers can still send 20 queries. For most systems that is already fine.
Two callers, one query
Solution 2
Many processes: a lock
How it works
- 1
Miss
The value is not in the cache.
- 2
Try to take the lock
Set a lock key only if it does not exist, with an expiry.
- 3
The winner
Checks the cache once more, queries, stores, then releases the lock.
- 4
The others
Wait a little and read the cache again, or use a stale value. They stop after a limit.
With a lock
SET lock:product:123 <token> NX EX 10# OK -> you have the lock# nil -> somebody else has it# release only your own lock, in one atomic script:if redis.call("get", KEYS[1]) == ARGV[1] then return redis.call("del", KEYS[1])else return 0endSolution 3
Refresh early, by chance
XFetch lets each reader of a still valid value decide, at random, to refresh it now. Far from expiry almost nobody does. Close to expiry somebody probably will, and the value is renewed before the gap.
XFetch
Chance per read, rebuild takes 2 seconds
| Time left | Chance to refresh |
|---|---|
| 20 s | about 0.005% |
| 6 s | 5% |
| 2 s | 37% |
| 1 s | 61% |
| 0 s | 100% |
No locks, no waiting, no background worker. But several readers may still refresh close together, and a key that is hardly read gets no early refresh.
Solution 4
Serve stale while one refreshes
Give each value two limits. With a soft TTL of 300 s and a hard TTL of 600 s, the value is fresh up to 300, stale but usable from 300 to 600, and gone after 600. In the middle zone readers get the old value at once, and one refresh runs.
Two limits
More tools
Other ways to calm the herd
- 1
Leases
On a miss the cache gives one reader a token to fill the key and tells the others to wait briefly. At Facebook, tokens were given once per 10 seconds per key by default; for a set of keys prone to herds the peak database rate fell from 17,000 to 1,300 queries a second.
- 2
Jitter
Random TTLs, for many keys that were stored together. See cache TTL.
- 3
Background refresh
A worker renews a known list of hot keys, so readers never rebuild.
- 4
Warming
Fill a new cache before it takes traffic.
- 5
A limit on the database
Allow only N rebuilds at a time and fail the rest fast. The last line of defence for a cold restart.
CDNs and proxies do the same. CloudFront collapses simultaneous requests for the same object, and nginx has proxy_cache_lock, which is off by default.
Compare
Which one?
| Solution | Good | Cost | Best for |
|---|---|---|---|
| Single flight | No network, simple | One query per process | Always, as a base |
| Lock or lease | Normally one query | Waiters, lock handling | Expensive rebuilds, strict freshness |
| Early refresh | No locks, no waiting | Some extra queries | Steady, busy keys |
| Serve stale | Always fast | Old data for a while, kept longer | Pages where speed matters most |
Choosing
Combine them: serve stale to readers, and use a lock so that only one background refresh runs.
Failure
What can go wrong with the cure
| Problem | Answer |
|---|---|
| The winner crashes | The lock expires by itself; waiters try again |
| The rebuild fails | Release the lock, keep the old value, retry with a pause |
| The value does not exist | Store a short negative entry, or waiters queue forever |
| Waiters wait too long | A deadline, then a stale value or an error |
| Waiters poll together | Random pauses |
| One lock for all keys | One lock per key |
Operate
See it before users do
- 1
Count rebuilds per key
More than one at a time means no protection.
- 2
Measure the rebuild time
The herd grows with it, so a faster query is also a fix.
- 3
Count joined calls
How many requests shared a result shows what the protection saves.
- 4
Test it
Delete the hottest key during a load test and look at the database.
Very hot keys have more problems than expiry. High-concurrency caching covers them.
Summary
The whole topic in one minute.
A stampede needs a hot key, a moment without a value and a rebuild that takes time. The number of duplicate queries is roughly the read rate times the rebuild time.
Let one request rebuild: single flight in each process, a lock or lease across processes. Better still, never let the value vanish: serve stale while one request refreshes. Add jitter for many keys, and protect the database with a limit as the last line.
- A stampede is many misses on one hot key at once.
- Its size is the read rate times the rebuild time.
- Single flight first, a lock or lease across processes.
- Serving stale removes the wait as well as the herd.
- Jitter is for many keys; it does not help one.