Sub topic 13
Preventing Cache Stampedes
This chapter assumes you know cache-aside reads, TTL expiration, and basic threading in Python. A cache stampede is a burst of identical rebuilds that hits your database when a popular entry disappears.
How a stampede happens
Suppose a product page is requested 500 times per second and its entry expires. For the few hundred milliseconds the database query takes, every request sees a miss. Each one runs the same expensive query, and the database can slow down or fail. A slow database makes the rebuild take longer, which lets more requests pile up.
Stampedes usually start in one of three ways:
- A hot key reaches its TTL.
- The cache restarts or is flushed, so many keys miss at once.
- Many keys were written together with the same TTL, so they expire together.
Per-key locking
The first defense is to let one caller rebuild the entry while the others wait. After getting the lock, each waiter checks the cache a second time. The check matters because the thread ahead of it has probably already filled the entry.
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 valueThe locks_guard protects the locks dictionary. The per-key lock means requests for different keys do not block each other.
Other mitigations
Locking is not the only option. These techniques can be combined.
| Technique | How it works | Trade-off |
|---|---|---|
| TTL jitter | Add a random offset, such as ±10%, to each TTL | Spreads expiry over time. It does not help a single hot key. |
| Early refresh | Rebuild a little before the TTL ends, in the background | Needs extra logic. Readers never see a miss. |
| Stale-while-revalidate | Serve the expired value while one worker refreshes it | Users may briefly see old data. |
| Warming | Preload hot keys after a restart or deploy | You must know which keys are hot. |
Jitter is a one-line change:
import random
ttl = 60 * random.uniform(0.9, 1.1)Common mistakes
- Skipping the second cache check after acquiring the lock. Every waiter then still queries the database, one after another.
- Holding a lock with no timeout. If the loader hangs, all waiters hang too. Set a timeout on the lock or the loader.
- Never removing entries from
locks. In a long-running process with many keys, the dictionary grows without limit. - Caching
Noneas a failed load. Use a short TTL for negative results so a brief outage is not remembered for a full minute.
Exercise
Your cache holds 10,000 keys, all written at startup with a 60-second TTL. Every minute the database shows a load spike. Which mitigation fits best, and why does a per-key lock not solve it?
Show answer
Add TTL jitter so the keys expire at different times. The per-key lock stops duplicate rebuilds of a single key, but here thousands of different keys expire at once, so each still needs its own rebuild and the database receives them all together.