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 Penetration and Cache Avalanche

Requests for data that does not exist, and many keys expiring together: two ways a cache fails to protect you.

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

01Quick Summary

These are two different ways a cache stops protecting your database. Cache penetration is when requests ask for data that does not exist anywhere, so the cache can never help. Cache avalanche is when many keys expire at the same moment (or the whole cache goes down) and the database is hit by everything at once.

  • Penetration: the id is not in the cache and not in the database either. Every request goes all the way through, again and again.
  • Avalanche: a big group of keys was given the same life, so they all disappear together. A flood of rebuilds lands on the database.
  • Neither is the same as a stampede, where one popular key expires and many requests rebuild it at once.

02Concept: What is it?

A cache works because most requests ask for things that were asked before. The cache keeps the answer, and the database is left alone. Both problems on this page are cases where that promise breaks.

Cache penetration

Normally a cache miss is fine: the app reads the database, stores the answer in the cache, and the next request is fast. But what if the database has no answer? Suppose someone asks for /user/99999999 and that user was never created. The app finds nothing in the cache, asks the database, finds nothing there, and has nothing to store. The next request for the same id repeats all of it.

A few such requests are harmless. A flood of them, from a bug or from an attacker who tries random ids on purpose, goes straight through the cache to the database. The cache does nothing, so the database does all the work.

Cache avalanche

Imagine a nightly job that fills the cache with 100,000 keys, all with a life of one hour. An hour later all 100,000 expire in the same second. Every request now misses, and the app tries to rebuild 100,000 entries from the database at the same time. The database slows down, requests wait longer, and more pile up.

The same happens when the cache itself fails (a node crashes or the cluster restarts). The cache comes back empty and every key has to be rebuilt together.

Where each problem happens
Penetration
📨Requestid 99999999
→↓miss
⚡Cachenothing stored
→↓miss
🗄️Databasenot found
Requests that reach the databaseevery time, for the same id
Avalanche
🔑100,000 keysall expire together
→↓all miss
🗄️Databaseflooded
Database load at that secondfar above capacity
Penetration: nothing to cache. Avalanche: a lot to cache, but it all disappears together.
🧠Three look-alikes
Penetration: the data does not exist. Stampede (breakdown): one hot key expires. Avalanche: many keys expire, or the cache dies. The fixes are different, so name the problem first.

03Real-Life Example

🍵The Library Desk and the Missing Book
A library has a front desk with a small shelf of the most borrowed books (the cache), and a huge basement archive (the database). Visitors ask the desk first. Now a prankster keeps asking for a book that was never printed. The desk checks the shelf (not there), sends a runner to the basement (not there), and the runner comes back empty-handed. The prankster asks again, and again. The runner never rests, and real visitors wait.

A different day: the librarian restocks the whole front shelf at 9:00 and stamps every book "return by 10:00". At 10:00 sharp every book is thrown out. The next hundred visitors all need a runner at once, and the basement is jammed.
Library
Cache
A book that was never printed
An id that does not exist
A note on the desk: “no such book, do not send a runner”
Caching a “not found” marker
A catalogue card index of every real title
A Bloom filter of valid ids
Every book stamped with the same return time
Every key with the same TTL
Staggering the stamps over the morning
Adding random jitter to TTLs
The desk is closed for cleaning and the shelf is empty after
The cache restarts and comes back empty
A limit on how many runners can go down at once
Load shedding to protect the database
The same morning with and without defences
🪪Check the indexdoes this id exist?
→↓
📝Check the noteknown missing?
→↓
⚡Check the shelfcache
→↓
🗄️Send a runnerdatabase, last

04Why Do We Need It?

🛡️Keep the database alive
A cache is a shield. If it fails, the database takes the whole load. Most databases are far smaller than the total traffic.
🚨Failures chain together
A slow database makes requests wait, waiting requests pile up, and the pile makes the database slower. A short spike can become a long outage.
🕵️Attackers use it
Asking for random ids is a cheap way to hurt a service. The cache cannot help, because there is nothing to store.
📅Easy to cause by accident
A bulk warm-up, a deploy that clears the cache, or a copied TTL constant can create an avalanche with no attacker at all.
💸Wasted work
Queries for ids that do not exist cost real CPU and disk time, and can never be answered usefully.
📈Hard to see coming
Everything looks fine until the moment it does not. Tests with small, tidy data miss both problems.
A cache only protects the database if it can answer, and if its answers do not all vanish at the same time.

05Where Do We Use It?

👤Lookups by id
Profile pages, product pages, short links. Anything where a client sends an id that may not exist.
🔗Short URL services
People guess codes. Most guesses do not exist, and each one reaches the database.
🛒Flash sales and launches
A bulk warm-up for the big day, with one shared TTL, is the classic avalanche set-up.
📰Content sites
A whole section is cached on publish with the same life, so it all expires together.
🧰Cache restarts and failovers
A cold cache after a crash or a rolling restart is an avalanche in waiting.
🔐Login and API endpoints
Credential-stuffing and scanning tools send huge numbers of unknown ids and names.

06Types / Parts / How It Works

Defences against penetration

DefenceHow it worksGood and bad
Validate the id firstReject ids that cannot be valid (wrong format, negative, too long) before touching the cache or database.Cheap and always worth doing. It cannot catch well-formed ids that simply do not exist.
Cache the “not found” answerStore a marker (a null) for the missing id, with a short TTL such as 30 to 60 seconds.Great when the same missing ids repeat. Weak against an attacker who uses a new random id every time, and the markers use memory.
Bloom filter of valid idsA small structure that says “definitely not here” or “maybe here”. Check it before the cache.Stops almost all missing ids using little memory. It has false positives (a few missing ids slip through) and must learn about new ids when they are created.
Rate limitingLimit how many requests one client can send.Slows a single attacker. Does not help against many clients, or against a bug in your own code.
📝The Bloom filter must stay up to date
A Bloom filter never says "no" to something that was added. But if you create a new record and forget to add its id, the filter will wrongly reject a real id. Add the id to the filter at the same moment you create the record, or rebuild the filter regularly.

Defences against avalanche

DefenceHow it worksGood and bad
Jitter on TTLsAdd a random amount to every TTL (for example base ± 10%), so keys expire at different times.The simplest and most effective fix for expiry avalanches. Costs nothing.
Staggered warmingWarm the cache in small batches over time instead of all at once.Avoids a synchronised start. Slightly slower to fill.
High availability for the cacheReplicas and automatic failover, or a cluster, so one crash does not empty the cache.Protects against the “cache is down” case. More machines to run.
Two cache levelsA small local cache in each app in front of the shared cache.Soaks up some load when the shared cache is cold. Adds a freshness trade-off.
Load shedding and circuit breakerReject or slow down some requests, or stop calling the database for a while, when it is overloaded.Keeps the database alive during the spike. Some users get errors or a fallback.
Graceful degradationServe a simpler page, an old copy or a default when the database cannot be reached.Users see something. Needs design work in advance.
Jitter turns a spike into a slope
Same TTL
Rebuilds in the busiest secondall keys at once
Rebuilds in other secondsalmost none
TTL with jitter
Rebuilds in the busiest seconda small share
Rebuilds in other secondsspread out
Spike Spread out
Same 1,000 keys. The only change is a little randomness in each TTL.
VisualizerPenetration and avalanche: watch the database loadPenetration: raise the share of missing ids, then try each defence, and change the number of different ids to see when the null cache stops helping. Avalanche: keep the TTL the same, then add jitter, then turn on the cache outage and load shedding.
Which problem?
Defence
Database queries per second. Cyan = ordinary cache misses. Red = lookups for ids that do not exist. Dashed line = database capacity (illustrative 300/s).
Bad requests
400/s
ids that do not exist
Stopped early
0/s
by the filter or null cache
DB queries
412/s
capacity 300/s
Database load
137%
of capacity
Without a defence, every request for a missing id passes the cache (nothing to find) and the database (nothing to find): 400/s of useless queries, 412/s in total, against a capacity of 300/s.

A simplified, deterministic model. The capacity (300/s), the 2% ordinary miss rate, the 60 s null TTL and the 20/s background load are illustrative numbers, not measurements. A rebuilt key costs one query, and each rebuilt key gets a new random life from a fixed seeded generator.

07How to Use It / Steps / Implementation

Protecting against both

  1. 1
    Validate ids at the edge
    Check format, range and length before the cache is even asked. This removes the silly requests for free.
  2. 2
    Cache “not found” with a short TTL
    Store a marker for ids that the database says do not exist. Keep the TTL short (seconds to a minute), so a record created a moment later is found soon.
  3. 3
    Put a Bloom filter in front for big id spaces
    Load it with every valid id at start-up, and add each new id when it is created. Check it first: if it says “no”, return not found at once.
  4. 4
    Add jitter to every TTL
    Do not write ttl = 3600. Write ttl = 3600 + random(0, 360). Do this in one shared helper, so no one forgets.
  5. 5
    Warm in batches
    When filling the cache before a launch, spread the loading over time and give keys different lives.
  6. 6
    Make the cache highly available
    Use replicas and automatic failover, and test what happens when a node restarts. A cold cache should be a rare, planned event.
  7. 7
    Protect the database itself
    Add rate limits, a connection pool limit and a circuit breaker, so an overloaded database sheds load instead of collapsing.
  8. 8
    Watch the right numbers
    Track cache hit ratio, the share of “not found” results, database queries per second and the number of keys expiring each minute.
💡One line of code that prevents most avalanches
Wrap every cache write in a helper that adds a small random amount to the TTL. It costs nothing and removes the synchronised expiry.
⚠️Do not cache “not found” for too long
If a missing id is cached as "does not exist" for an hour, a user who signs up one minute later may not be found for the rest of that hour. Keep the null TTL short, or delete the marker when the record is created.

08Key Terms to Know

TermMeaning in easy words
Cache penetrationRequests for data that exists neither in the cache nor in the database, so each one reaches the database
Cache avalancheMany keys expire at the same moment, or the cache goes down, so the database is flooded
Cache breakdown / stampedeOne hot key expires and many requests rebuild it at the same time
Negative cachingStoring the answer “does not exist” (a null marker) so it is not asked again soon
Bloom filterA small structure that answers “definitely not here” or “maybe here”, with no false “not here”
False positiveA Bloom filter says “maybe here” for something that is not there. A few missing ids slip through
TTL (time to live)How long a cache entry is kept before it expires
JitterA small random amount added to a TTL so keys do not expire together
Cold cacheA cache that is empty, for example after a restart, so nearly every request misses
Load sheddingRejecting some requests on purpose so the rest can still be served
Graceful degradationGiving a simpler or older answer instead of failing completely

09Pros, Cons and Trade-offs

✅ Pros
  • Cheap defences (validation, jitter) remove most of the risk
  • Bloom filters guard huge id spaces with little memory
  • Null caching is simple and needs no new components
  • Load shedding keeps the database alive in the worst case
  • Spreading expiry gives smooth, predictable database load
⚠️ Cons
  • Null markers use memory and can hide a record created soon after
  • A Bloom filter has false positives and needs to be kept in sync
  • Jitter makes exact expiry times less predictable
  • Staggered warming slows down filling the cache
  • Load shedding means some users get errors or fallbacks

Trade-offs

ChoiceWe gainWe lose
Longer null TTLFewer repeat queries for missing idsA newly created record may look missing for longer
Shorter null TTLNew records appear quicklyMore repeat database queries for missing ids
Lower Bloom false-positive rateFewer bad requests slip throughA bigger filter and more hash work
More jitterFlatter database loadLess predictable freshness, some keys live longer
Short TTLs overallFresher dataMore rebuilds, so more database load and more avalanche risk
Load shedding onThe database survives a spikeSome requests are rejected on purpose

10Common Problems and Mistakes

Common mistakes

  1. Treating all three the same. Jitter does not stop penetration, and a Bloom filter does not stop an avalanche.
  2. One shared TTL constant. A single TTL = 3600 copied everywhere is an avalanche waiting for a bulk load.
  3. Never caching “not found”. The database answers the same pointless question forever.
  4. Caching “not found” for too long. A new record stays invisible.
  5. A Bloom filter that is never updated. New ids are rejected as if they did not exist.
  6. A single cache node. One restart turns into an empty cache and an avalanche. It is also a single point of failure.
  7. Clearing the whole cache on deploy. This creates a cold cache on purpose, at the busiest time.
  8. No protection on the database. With no limit, a spike takes the database down instead of being absorbed.

Things to watch

📉Hit ratio drops suddenly
A sharp fall means a mass expiry or a cold cache. Look at what changed in the last few minutes.
🔍Many “not found” results
A high share of misses for ids that never exist points to scanning or a bug in a client.
⏱️Expiry spikes
Count how many keys expire per minute. A tall bar means they were created together.
🔁Retry storms
Clients that retry on errors add more load while the database is struggling. Use backoff.

11Real-World Examples

🔗URL shorteners
Many requests are for codes that were never issued. Validation, null caching and a filter of issued codes are common.
🛍️Big sale events
Teams warm the cache before the event, but spread the TTLs, so the product pages do not expire together.
📰News sites
Pages are cached with a short life plus jitter, so a big edition change does not flatten the database.
🎮Game back ends
After a cache cluster restart, a slow warm-up and limits on the database avoid a login storm.
🔐Public APIs
Rate limits and id validation reduce scanning. Unknown ids are answered quickly and cheaply.
🗄️Storage and databases
Many systems keep a Bloom filter in front of disk lookups, so a missing key rarely costs a disk read.
📝Note
Libraries and cache products name these ideas differently. Check your own tools for options like TTL jitter, negative caching and request limits instead of assuming they are on by default.
Mini case: a product page API
📨Request/product/123456
→↓valid?
🧮Bloom filterreal id?
→↓maybe
⚡CacheTTL + jitter
→↓miss
🗄️Databaselimited, protected
Guards Cache Database
Four cheap layers between the request and the database.

12Related Topics to Read Next

Cache Stampede→

One hot key expiring: the third look-alike, with different fixes.

Cache Warming→

Filling the cache ahead of time, and why it must not use one shared TTL.

Bloom Filters→

The structure that rejects ids that do not exist.

Rate Limiting→

Slows down a client that scans for missing ids.

Circuit Breaker→

Stops calling an overloaded database for a while.

Single Point of Failure (SPOF)→

A single cache node is one, and its failure causes an avalanche.

Cache Invalidation→

Removing or refreshing entries, including old “not found” markers.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Penetration: ids that do not exist, so cache and database both miss, every time.
  • ✔Fix penetration: validate ids, cache a short “not found”, Bloom filter, rate limit.
  • ✔Avalanche: many keys expire together, or the cache dies and restarts empty.
  • ✔Fix avalanche: jitter on TTLs, staggered warming, HA cache, protect the database.
  • ✔Stampede is different: one hot key. Use a lock or request coalescing.
  • ✔Null TTL: keep it short, so new records are not hidden.
  • ✔Bloom filter: no false “not here”, a few false “maybe”. Add new ids on create.
  • ✔One line: “Do not let the cache fail the same way twice: no misses forever, and no expiry all at once.”
← Previous
Hot Keys
Next →
CDN Push vs Pull