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.
See it run
Ten readers, one missing key. Count the database queries.
Operations
No protection
Every reader does what looks sensible.
Step 1 of 7
The key expires
- Database load
- 5%
The TTL of product 123 ends.
Step 1: The key expires
def get(key): value = cache.get(key) if value is None: value = db.query(key) # everybody is here cache.set(key, value, 300) return value- Queries
- 10
- Readers
- all slow
- Needed
- 1 query
Each request is correct on its own. The problem is that nobody knows about the others.
In the real world
The same thundering herd doing real jobs. Pick one and step through it.
Every key is missing, not just one.
Step 1 of 3
Empty cache
- Database load
- 100%
The cache restarts. Every request for any key misses.
Step 1: Empty cache
Common mistakes
The bugs interviewers watch for, with the fix beside each.
A lock that never expires
criticalIf its owner crashes, nobody can rebuild the key again.
Wrongcache.set("lock:k", 1, nx=True)Rightcache.set("lock:k", token, nx=True, ex=10)Waiting without a deadline
criticalA rebuild that keeps failing holds every waiter, and the server runs out of threads.
Wrongwhile not cache.get(k): sleep(0.1)Rightwhile now() < deadline: if v := cache.get(k): return v sleep(random.uniform(0.05, 0.15))raise TimeoutErrorReleasing a lock that is not yours
majorAfter expiry somebody else may own it.
Wrongcache.delete("lock:k")Rightdelete_if_equal("lock:k", my_token) # atomicRefreshing on every stale read
majorBetween soft and hard limit, each reader starts a refresh: the herd moves to the background.
Wrongif stale: in_background(rebuild, k)Rightif stale and try_lock(k): in_background(rebuild, k)
Interview tips
How to explain it
- One value missing, many readers.
- Everybody does the same work.
- Let one do it; the rest wait or use the old value.
Memory trick: STAMPEDE
- Simultaneous, TTL over, All miss.
- Multiple queries, Performance drops.
- Everyone waits, Database overwhelmed, Explosive failures.
Order of work
- Single flight in each process.
- Serve stale where allowed.
- A lock or lease for costly rebuilds.
Never forget
- Expiry and token on the lock.
- A deadline for waiters.
- A limit for a cold restart.