The Cache Expired and the Database Fell Over: Thundering Herd and Cache Stampede Explained
It was a normal Monday. Traffic was steady, the database was calm at around 30% CPU, and our Redis cache was serving more than 95% of product page reads.
At exactly 10:00 AM, the database CPU jumped to 100%. Connections maxed out. API latency went from 80 ms to 12 seconds, and the error rate climbed. Nothing had been deployed. Traffic had not changed.
Ten minutes later, everything was calm again, as if nothing had happened.
The next Monday, at 10:00 AM, it happened again.
This post explains what was going on, how we fixed it, and how to talk about it in an interview.
What actually happened
Every Monday at 10:00 AM, a job refreshed our product catalogue and cleared the cache for the most popular products. All those keys were also set with the same TTL of exactly one hour.
So at the same moment, thousands of hot cache keys disappeared together. Every request that came in for those products found nothing in the cache. And every single one of those requests did the same thing:
- Cache miss.
- Run the expensive product query on the database.
- Write the result back into the cache.
The problem is the gap between step 1 and step 3. One product page query took about 400 ms. During those 400 ms, hundreds of other users asked for the same product. They all missed the cache too, and they all ran the same query.
Instead of one database query per product, we had hundreds. The database slowed down, so the queries took longer, so the gap got wider, so even more requests piled in. A feedback loop.
This is called a cache stampede, a type of thundering herd problem: a large number of clients wake up or react at the same moment and all hit the same resource together.
Where thundering herds show up
The cache case is the most common, but the same pattern appears in many places:
- Cache keys that expire together because they were set at the same time with the same TTL.
- Cache restart or flush, when a Redis node restarts empty and every request goes to the database.
- Retries without jitter, when a service comes back after an outage and every client retries at the same second.
- Cron jobs at round times, when hundreds of servers all run a job at exactly midnight or on the hour.
- Mobile apps reconnecting after a network blip, all at once.
The root cause is always the same: many clients acting in sync on a shared resource.
How we fixed it
We did not fix it with a bigger database. We fixed it in four steps.
1. Add random jitter to TTLs
Instead of every key expiring after exactly 3600 seconds, we added a random spread:
import random
base_ttl = 3600
ttl = base_ttl + random.randint(0, 600) # 60 to 70 minutes
redis.set(key, value, ex=ttl)
Now keys expire over a 10-minute window instead of in the same second. This one change removed most of the spike.
2. Let only one request rebuild the cache (request coalescing)
When a key is missing, only one request should go to the database. The others should wait for that result or serve the old value. A simple way is a short lock in Redis:
import random, time
def get_product(product_id):
key = f"product:{product_id}"
value = redis.get(key)
if value:
return value
lock_key = f"lock:{key}"
# Only one caller gets the lock, for at most 10 seconds
if redis.set(lock_key, "1", nx=True, ex=10):
try:
value = db.load_product(product_id)
redis.set(key, value, ex=3600 + random.randint(0, 600))
return value
finally:
redis.delete(lock_key)
# Others wait briefly and read again
time.sleep(0.05)
return redis.get(key) or db.load_product(product_id)
In Go, the singleflight package does this inside one process. Many CDNs and proxies have the same idea built in, often called request collapsing.
3. Serve stale data while refreshing
For product pages, data that is one minute old is fine. So we stored a "soft expiry" time inside the cached value. After the soft expiry, the first request refreshes the value in the background while everyone else keeps getting the old copy. Users never see a miss.
This is the same idea as HTTP stale-while-revalidate.
4. Warm the cache after the catalogue job
Instead of deleting hot keys, the Monday job now writes the new values directly into the cache, starting with the top 1,000 products. The cache is never empty for the pages that matter most.
We also added two guardrails:
- A connection limit and timeouts on the database side, so a stampede slows things down instead of taking the database out completely.
- Retries with exponential backoff and jitter on clients, so recovery does not cause a second herd.
How we found it
The clue was the timing. A spike at the same minute every week, with no deploy and no traffic change, points to something scheduled. When we put the cache hit ratio and database query count on the same Grafana panel, the picture was clear: hit ratio dropped from 95% to almost zero at 10:00, and the same query ran hundreds of times per second.
If you only watch database CPU, you will think you need a bigger database. Watch the cache hit ratio and the number of identical queries too.
The interview angle
A common system design follow-up is: "Your cache works well, but sometimes the database still gets overloaded. Why, and what do you do?"
A strong answer covers:
- Name it: cache stampede or thundering herd, caused by many keys expiring together or a cold cache.
- Spread expiry: add jitter to TTLs.
- Coalesce requests: one rebuild per key with a lock or singleflight.
- Serve stale: stale-while-revalidate or soft TTLs.
- Warm the cache: refresh hot keys before they expire, and after restarts.
- Protect the database: connection limits, timeouts, backoff with jitter on retries.
Interviewers like this question because it tests whether you understand that a cache is not only a speed-up. When it fails, it can multiply load instead of reducing it.
Key takeaways
- A cache can hide how much load your database really has, until it suddenly stops hiding it.
- Same TTL plus same start time equals same expiry time. Add jitter.
- Only one request should rebuild a missing key.
- Old data for a few seconds is usually better than a down database.
- Watch cache hit ratio next to database load, not just CPU.
In 14+ years, many of the "we need a bigger database" incidents I have seen were really "we need a smarter cache".
Let's connect: Free 15-min Cloud & DevOps Interview Guidance Call 👆 link in bio (topmate.io/cloudtechbydevang)
About the author
- I help engineers learn cloud, DevOps, SRE and AI in simple English, crack interviews and follow clear roadmaps. 14+ years building and running platforms on AWS, GCP, Kubernetes and Terraform. One topic a day.
Comments
Join the discussionNo comments yet. Be the first to comment.
