SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • CDN
  • Distributed Cache Architecture
  • Cache Stampede
  • Cache Warming
  • Hot Keys
  • Cache Penetration and Cache Avalanche
  • CDN Push vs Pull
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Distributed Caching

Cache Stampede

A popular item expires and thousands of requests hit the database at the same moment.

⏱ 12 min readAdvancedInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A cache stampede (also called a thundering herd or dogpile) happens when a popular cached item expires and thousands of requests all go to the database at the same moment to rebuild it.

  • The cache was protecting the database. When it fails for one hot key, the database takes the whole crowd.
  • The database slows down, so rebuilding takes longer, so even more requests pile up.
  • Fixes: let only one request rebuild, spread out expiry times, serve old data while refreshing, or refresh early.

02Concept: What is it?

Imagine a product page cached for 10 minutes. It is read 5,000 times a second. For 10 minutes, the database sees almost nothing. At minute 10 the entry expires. In the next fraction of a second, thousands of requests find the cache empty. Each one asks the database to build the same page.

Before and during a stampede
Key is fresh
πŸ‘₯5,000 req/s
→↓hits
⚑Cache
⇒⇣~0 reach DB
πŸ—„οΈDBcalm
Key just expired
πŸ‘₯5,000 req/s
→↓all miss
⚑Cacheempty
→↓all go through
πŸ”₯DBoverloaded
One expired key turns thousands of cheap cache reads into thousands of expensive database queries.
⚠️Why it gets worse by itself
An overloaded database answers slowly. While it is slow, the key stays empty longer. So more requests arrive, find it empty and also go to the database. This loop can take the whole system down.

03Real-Life Example

🍡The Exam Result Board
A school pins the results on a board. Students read the board, not the office. At 9 am the board is taken down to print new results. 2,000 students rush to the office at once and ask the one clerk for their marks. The clerk is buried, and the new board cannot be printed because nobody lets him work.
School
System
Results board
Cache
The office clerk
Database
Board taken down
Key expires
2,000 students rush the clerk
Stampede of cache misses
β€œWait here, one of us will print the board”
Lock or single flight
Keep the old board up until the new one is ready
Stale-while-revalidate
Print the new board before the old is removed
Early refresh
The timeline of a stampede
  1. βœ“
    A hot key is cached with a 10-minute TTL
    Everything is calm.
  2. !
    The key expires
    The cache is now empty for this key.
  3. πŸ”₯
    Thousands of requests miss at the same time
    Each one starts a database query.
  4. 🐒
    The database slows down
    Queries queue up. Rebuilding takes longer.
  5. πŸ’₯
    More requests arrive and also miss
    A loop of overload. Other parts of the app start failing.

04Why Do We Need It?

We need to understand it because a cache stampede is a common way for a healthy system to fall over suddenly.

πŸ’₯Outages from one key
A single hot key can take the database down.
⏱️Spikes in latency
Even without a crash, users see slow pages.
πŸ’ΈCost
Databases and APIs that charge per query get an unexpected bill.
πŸ”—Cascading failure
A slow database makes app servers wait, then they fail, then others fail.
A cache helps only while it is full. Plan for the moment it is not.

05Where Do We Use It?

πŸ›’Sale day product pages
A few pages get most of the traffic, and they all expire on the same TTL.
πŸ“°Home page and feeds
One key read by every visitor.
πŸ†Trending and leaderboards
Expensive to build, read constantly.
πŸ”After a cache restart or deploy
Many keys are missing at once (a cold cache).
🌍CDN purge
Purging a popular file makes every edge ask the origin together.
πŸ•›Keys all set at the same time
A batch job fills the cache with the same TTL, so everything expires together.

06Types / Parts / How It Works

Four ways to prevent a stampede

ProtectionHow it worksGood and bad
Lock / single flight (request coalescing)On a miss, one request takes a lock and rebuilds the value. The others wait for it, or share its result.Database sees 1 query per key. Waiting requests add delay. A stuck lock needs a timeout.
TTL jitterAdd a small random extra time to each TTL (for example 10 minutes plus 0 to 60 seconds).Keys stop expiring together. Does not help if ONE hot key expires.
Stale-while-revalidateWhen the value expires, keep serving the old one. One request refreshes it in the background.Users never wait. They may see slightly old data.
Early (probabilistic) refreshRefresh a little before expiry. Each read has a small, growing chance of starting the refresh as the expiry gets close.The value never really expires under load. Slightly more work than needed.
Single flight: many requests, one database query
πŸ‘€Request 1gets the lock
πŸ‘€Requests 2 to 1,000wait
→↓
πŸ”’Lock1 key = 1 builder
→↓1 query
πŸ—„οΈDatabasecalm
→↓value
⚑Cachefilled once
The first request rebuilds the value. The others wait a moment and read the new value from the cache.

More safety nets

  • Load shedding / rate limiting on the database path: if too many requests arrive, return an error or a default to some of them, so the rest succeed.
  • Circuit breaker: after many failures, stop calling the database for a short time, and serve a fallback.
  • Pre-compute hot values: a background job refreshes them on a schedule, so users only read.
  • Negative caching: also cache β€œnot found” results briefly, so repeated misses for missing items do not hit the database.
VisualizerCause a stampede, then stop itRaise the traffic until the red bars pass the database limit. Then switch protections on one by one.

6 hot keys are all filled at second 0 and stay fresh for 10 seconds. Rebuilding one takes the database 2 seconds. The database can handle about 200 queries per second.

Database queries per secondsecond 40 of 40
database limit (200)
0 s20 s40 s
Peak DB load
900
limit 200/s
Seconds over limit
6
Requests that waited
0
held back by the lock
Old values served
0
stale-while-revalidate
At second 10, the database got 900 queries in one second. It can take about 200. That is a cache stampede: the keys expired together and every request went to the database.

A simplified model with a simulated clock: the numbers show the idea, not a real database.

07How to Use It / Steps / Implementation

A simple defence plan

  1. 1
    Find your hot keys
    Look at which keys get the most reads and which are expensive to rebuild.
  2. 2
    Add jitter to every TTL
    It is cheap and stops keys from expiring together.
  3. 3
    Use single flight for hot keys
    One rebuild per key. Give the lock a timeout, so a crashed builder cannot block forever.
  4. 4
    Serve stale where allowed
    For data that can be a few seconds old, use stale-while-revalidate.
  5. 5
    Refresh early or in the background
    For the very hottest keys, a scheduled job keeps them fresh.
  6. 6
    Protect the database
    Set connection limits, timeouts and load shedding, so it cannot be flattened.
  7. 7
    Test it
    Run a load test where hot keys expire, and watch the database.
πŸ’‘Simple idea for the lock
In a shared cache like Redis, a request can try to set a key like lock:product:42 only if it does not exist, with a short expiry. The one that succeeds rebuilds. The others wait a few milliseconds and read the cache again.
Database queries on expiry (1,000 waiting requests)no protection: 1,000 queries
With single flight1 query

08Key Terms to Know

TermMeaning in easy words
Cache stampedeMany requests rebuild the same missing key at the same time
Thundering herd / dogpileOther names for the same problem
TTLTime to live: how long a cached value stays fresh
JitterA small random amount added so things do not happen together
Single flight / coalescingOnly one request does the work. Others share its result
Stale-while-revalidateServe the old value while a fresh one is fetched in the background
Early refreshRefresh before the value expires
Hot keyA key with very high traffic
Load sheddingRefuse some requests on purpose to protect the system
Circuit breakerStops calls to a failing system for a while
Negative cachingCaching a β€œnot found” answer for a short time

09Pros, Cons and Trade-offs

βœ… Pros
  • The database stays safe when hot keys expire
  • Users see steady, fast responses
  • A cheap fix (jitter, locks) prevents a big outage
  • Fewer surprise bills
⚠️ Cons
  • Locks add waiting and the risk of a stuck lock
  • Stale data may be shown for a short time
  • Early refresh does extra work
  • More logic in your cache code

Trade-offs

ProtectionWe gainWe lose
Lock / single flightOne query per keySome users wait; needs lock timeouts
TTL jitterNo mass expiryDoes not protect one single hot key
Stale-while-revalidateNever wait, no spikeBriefly old data
Early refreshKey never expires under loadA bit of wasted work
Load sheddingThe DB survives anythingSome users get errors or defaults

10Common Problems and Mistakes

Common mistakes

  1. The same TTL for everything. A batch job fills 10,000 keys at once, and they all expire together.
  2. A lock with no expiry. The builder crashes, the lock stays, and nobody can rebuild.
  3. Waiting forever for the lock. Give waiters a time limit and a fallback.
  4. Retry storms. Clients retry at once when the database is slow, which makes it slower. Use exponential backoff with jitter.
  5. Flushing the whole cache. Every key is missing at once. Remove only what is needed.
  6. Not testing it. A stampede only shows up under real load.

Related problems

πŸ₯ΆCold cache
After a restart, many keys miss together. See Cache Warming.
πŸ”Cache penetration
Requests for keys that do not exist always reach the database. Use negative caching or a Bloom filter.
🧨Cache avalanche
Many different keys expire together, or the cache goes down. Use jitter and replicas.

11Real-World Examples

πŸ›’Big sale and flash sale pages
Home pages and top products are read by millions at once, so stampede protection is a must.
🌍CDN request collapsing
Many CDNs combine simultaneous misses for the same file into one request to the origin (general idea).
πŸ“°Breaking news pages
One page, millions of readers. Stale-while-revalidate keeps it up.
πŸ”—Caching libraries and frameworks
Many have single flight or β€œrefresh ahead” features built in.
πŸ”Memcached and Redis users
Common patterns: lock keys, jittered TTLs and background refresh jobs.
🎟️Ticket booking
A popular event page is hammered the second booking opens.
πŸ“Note
These are general ideas. Each company uses its own tools and numbers.
Combined defence
πŸ‘₯Many requests
→↓
⚑Cachejittered TTL, stale OK
→↓miss
πŸ”’Single flight
→↓
🚦Limit / breaker
→↓
πŸ—„οΈDatabase
Cache One rebuilds Safety net
Several small protections together make a strong shield for the database.

12Related Topics to Read Next

What is Caching?β†’

The basics, including hit and miss.

Cache Invalidation→

Explicit removal can also cause many misses together.

Cache Warming→

Fill the cache gently to avoid a cold start stampede.

Rate Limiting→

A way to protect the database path.

Distributed Cache Architecture→

Replicas help when a node dies.

CDN→

Edges can stampede the origin after a purge.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • βœ”What: a hot key expires and many requests rebuild it together, overloading the database.
  • βœ”Other names: thundering herd, dogpile.
  • βœ”Fix 1: single flight or lock (with a timeout).
  • βœ”Fix 2: jitter on TTLs, so keys expire at different times.
  • βœ”Fix 3: stale-while-revalidate or early refresh.
  • βœ”Safety net: load shedding, circuit breaker, backoff with jitter.
  • βœ”Remember: a cache only protects the database while it is full.
  • βœ”One line: β€œDo not let a thousand requests rebuild the same thing. Let one do it.”
← Previous
Distributed Cache Architecture
Next β†’
Cache Warming