Cache Stampedes
Many misses at once.
The home page's best sellers are cached, and ten thousand people a second read them. Then the cache entry expires. In that instant, all ten thousand requests miss, and hit the database at once. That's a cache stampede.

- 10,000 reads a second
- The entry expires
- All miss at once
Preventing stampedes
There are a few fixes. A lock lets only the first request reload the value, while the others wait a moment, or get the old value. Early refresh reloads popular keys a little before they expire. And random jitter on TTLs stops many keys from expiring at exactly the same moment.
One reload, not thousands
Here's the lock idea. A hundred requests arrive just after the key expires. Without a lock, all of them query the database. With a lock, the first one reloads, and the rest wait for its answer. Run it. A hundred database queries become just one.
import threading, time
db_calls, cache, lock = 0, {}, threading.Lock()
def load():
global db_calls
db_calls += 1
time.sleep(0.05)
return "best sellers"
def get():
if "home" not in cache:
with lock:
if "home" not in cache: # check again inside the lock
cache["home"] = load()
return cache["home"]
threads = [threading.Thread(target=get) for _ in range(100)]
[t.start() for t in threads]; [t.join() for t in threads]
print("requests: 100, database calls:", db_calls)requests: 100, database calls: 1
Summary
A stampede happens when a popular key expires and every request hits the database. Locks, early refresh, and jitter prevent it. Next, the most popular cache of all. Redis.
Key takeaways- Popular key expires
- Everyone misses
- Lock, refresh early, jitter