Sub topic 13
Preventing cache stampedes
This chapter assumes you know cache-aside reads, TTL expiration, and basic threading in Python. A cache stampede happens when many requests miss the same key at once and all of them go to the source to rebuild it. Cache-aside makes this easy to trigger, because every miss triggers a load.
What a stampede looks like
Suppose a popular report is cached with a 60-second TTL. It costs the database two seconds of work to build. At 500 requests per second, the entry expires and the next requests all see a miss. Until the first rebuild finishes, roughly 1,000 requests (two seconds at 500 per second) each start the same expensive query.
The database slows down under that load. The rebuilds take longer, so even more requests pile up behind them. A cache that was meant to protect the database ends up overloading it.
Stampedes are also called thundering herds or dogpiling. Three situations commonly cause them:
- A hot key expires.
- The cache is cold after a restart or deploy.
- Many keys were written together with the same TTL, so they all expire together.
Mitigation 1: a per-key lock
The most direct fix is to let one caller rebuild the entry while the others wait. The first caller takes a lock for that key. The waiting callers then check the cache again once they get the lock, because the first caller has probably filled it.
import threading
import time
cache = {} # key -> (value, expires_at)
locks = {}
locks_guard = threading.Lock()
TTL_SECONDS = 60
def fresh(key):
entry = cache.get(key)
if entry is not None and entry[1] > time.monotonic():
return entry[0]
return None
def get_or_load(key, loader):
value = fresh(key)
if value is not None:
return value
with locks_guard:
lock = locks.setdefault(key, threading.Lock())
with lock:
value = fresh(key) # another thread may have filled it while we waited
if value is not None:
return value
value = loader()
cache[key] = (value, time.monotonic() + TTL_SECONDS)
return valueThree details matter here:
- The lock is per key. A single global lock would make unrelated keys wait for each other.
locks_guardprotects only the creation of the per-key lock, and it is held briefly.- The second call to
freshinside the lock is what stops the stampede. Without it, each waiting thread would reload the value one after another.
This design has limits:
- The lock lives in one process. With 20 application servers, you can still get 20 simultaneous rebuilds.
- The
locksdictionary grows with every key. Long-running services need a way to remove unused locks. - Waiting callers block for the full load time. If the loader hangs, they hang too, so use timeouts.
freshtreatsNoneas a miss. IfNoneis a legitimate value, it is reloaded every time, so cache a sentinel instead.
Mitigation 2: a distributed lock
To limit rebuilds across servers, take the lock in a shared store. Redis is a common choice, using a SET with the NX option (set only if absent) and an expiry. The expiry is essential. If the lock holder crashes, the lock must release itself.
The flow for a miss is:
- Try to acquire
lock:<key>with a short expiry, for example 10 seconds. - If you got it, load from the database, write the cache entry, and release the lock.
- If you did not, wait briefly and read the cache again. Retry a few times, then fall back to loading directly or return an error.
Release the lock only if you still own it. Store a unique token as the lock value and compare it before deleting. Otherwise a slow holder whose lock already expired can delete the lock of a newer holder.
A distributed lock adds a network round trip to every miss and a new failure mode. Locks are not perfect guarantees, so design the loader so that two simultaneous rebuilds are harmful only to performance, never to correctness.
Mitigation 3: serve stale data while refreshing
Sometimes waiting is worse than serving old data. In a stale-while-revalidate design, each entry has two times:
- A soft expiry, after which the entry is stale and should be refreshed.
- A hard expiry, after which the entry must not be served.
When a request finds a stale but not hard-expired entry, it returns the old value immediately. One request, chosen by a lock, starts a refresh in the background. Users never wait on the rebuild, and the database sees one query.
This trades freshness for latency. It fits data where being a few seconds old is acceptable, such as a leaderboard. It does not fit data such as account balances. The idea also exists in HTTP as the stale-while-revalidate Cache-Control directive, which a later chapter covers.
Mitigation 4: refresh before expiry
Instead of reacting to a miss, you can rebuild hot keys before they expire. There are two common ways:
- A background job reloads a known list of hot keys on a schedule shorter than the TTL.
- Probabilistic early refresh: as an entry gets closer to expiring, each request has a small and rising chance of refreshing it. Most of the time one request wins well before the deadline, and the hot key rarely reaches a true miss.
Scheduled refresh is simple but needs you to know which keys are hot, and it wastes work on keys nobody reads. Probabilistic refresh needs no list but is harder to reason about and test.
Mitigation 5: spread out expirations with jitter
If many keys are written together, add random jitter to each TTL so they do not expire in the same instant.
import random
def ttl_with_jitter(base_seconds, spread=0.1):
# Returns base +/- 10% by default, e.g. 54 to 66 seconds for a base of 60.
delta = base_seconds * spread
return base_seconds + random.uniform(-delta, delta)Jitter does not help a single hot key. It addresses the case of many keys expiring together, which is common after a bulk load or a cache warm-up.
Related protections
- Request coalescing: merge concurrent requests for the same key into one backend call, and give all callers the result. A per-key lock with a recheck is one way to do this.
- Negative caching: cache "not found" results for a short time. Repeated requests for missing keys otherwise miss every time and hit the database each time.
- Rate limiting and load shedding: cap the number of concurrent rebuilds, and reject extra work, so that a stampede degrades service instead of taking the database down.
- Cache warming: fill the cache before sending traffic to a new node or after a restart.
Choosing a mitigation
| Technique | Prevents | Cost | Main risk |
|---|---|---|---|
| Per-key lock (in process) | Duplicate rebuilds in one server | Low | Does not coordinate across servers |
| Distributed lock | Duplicate rebuilds across servers | Extra round trip per miss | Lock expiry and lost locks |
| Stale-while-revalidate | Waiting on rebuilds | More complex entries | Serving old data |
| Early refresh | Hot-key misses | Background work | Wasted loads |
| TTL jitter | Mass simultaneous expiry | Almost none | No help for one hot key |
Most systems combine several. A common baseline is jitter on all TTLs, a per-key lock around the loader, and stale-while-revalidate for the few keys where load is heaviest.
Common mistakes
- Locking without rechecking the cache, so waiters reload the value anyway.
- Using a lock with no expiry, which blocks a key forever if the holder crashes.
- Using one global lock, which serializes all cache misses.
- Setting the same TTL on every key written in a batch.
- Not testing it. Simulate many threads requesting one expired key and count how many times the loader runs.
Exercise
A hot key has a 30-second TTL and takes 3 seconds to rebuild. You add the per-key lock from this chapter but remove the second call to fresh() inside the lock. Traffic is 200 requests per second. What goes wrong, and which of the other techniques would let users avoid waiting on the rebuild?
Show answer
Without the recheck, every thread that waited on the lock still calls the loader after acquiring it. The loads run one after another instead of at the same time, so the database gets the same number of queries, and the last waiting thread waits for all of them to finish. The recheck lets each waiter find the value the first thread stored. To avoid making users wait at all, use stale-while-revalidate, which returns the old value while one request refreshes it, or refresh the key in the background before the TTL ends.
Exercise
A nightly job loads 10,000 product pages into the cache, each with a 1-hour TTL. Every hour the database spikes. A per-key lock does not fix it. Why not, and what does?
Show answer
The problem is many different keys expiring at the same moment, not many requests for one key. Each key has only one rebuild, so a per-key lock has nothing to merge. Adding random jitter to each TTL spreads the expirations over a window, which flattens the load. Limiting concurrent rebuilds would also cap the spike.