Stage 2 · Building blocks · Medium · 16 min

Cache eviction and stampedes

A cache has limited memory. Learn which key it removes when full (LRU, LFU), and how one expired key, or many, can flood the database, with the fix for each.

What each interview level is expected to know

Learn first: Caching strategies

After this lesson you can:

  • Explain how LRU and LFU each choose what to remove from a full cache.
  • Protect the database when one hot key expires, with a lock so only one request rebuilds it.
  • Tell a stampede, an avalanche and penetration apart, and give a defence for each.

Start here

See it in 60 seconds

When a popular key expires

When a popular cached key expires, every waiting request can hit the database at once; letting one request refill it protects the database.

Scene 1 of 6 · A popular key

Readers keep asking for item:1, and the cache answers every one, so the database stays quiet.

ReadersReadersAppAppCacheCacheitem:1 cachedDatabaseDatabase
  • Readers — healthy
  • App — healthy
  • Cache — healthy — item:1 cached
  • Database — healthy
Requests waiting for item:1
not shown yet
Database reads of item:1
not shown yet
  1. A popular key. Readers keep asking for item:1, and the cache answers every one, so the database stays quiet.
  2. The copy expires. Then the TTL for item:1 runs out, and the cache throws its copy away.
  3. Everyone misses at once. 100 requests for item:1 arrive in the same moment, and every one of them misses the cache.
  4. A stampede. Each miss reads the database itself: 100 reads of the same key at once, a cache stampede.
  5. One read refills it. With request coalescing, the first miss reads the database and the other 99 wait for its answer.
  6. Everyone gets the answer. That one read refills the cache, and all 100 waiting requests get the same fresh copy.
  7. Now you try. How many requests are waiting for item:1 when it expires? For example: 300 waiting requests: without coalescing, 300 database reads at once; with it, 1. The other 299 wait for that one read, then all get the same fresh copy.

Scene 1 of 6: A popular key. Readers keep asking for item:1, and the cache answers every one, so the database stays quiet.

Key points

  1. A cache stampede happens when a popular key expires and every request for it misses at once.
  2. Each miss reads the database, so one expiry can send hundreds of identical reads together.
  3. Request coalescing lets one request per app server refill the key while the others wait.
  4. If many keys share one TTL, they expire together; a few random extra seconds on each TTL spreads them out.

Go deeper in the Caching lab →

In plain words

Say item:1 is the most-read key in a shop's . Its runs out, and the cache drops it. The next 100 requests for item:1 all miss, and all 100 read the database at the same moment. That burst is a . is the other half of this lesson. When the cache is full, it must remove a key to make room, and the rule it uses decides which one.

Each problem has a common fix. For eviction, removes the key nobody has read for the longest time, which suits many apps. For a stampede, the first miss takes a short lock and reloads item:1 while the other 99 wait for it. When many keys expire at the same moment, called an avalanche, a small random extra on each TTL spreads them out.

The problem it solves

A cache cannot hold everything, so something must go, and a poor choice lowers the . The database behind it is sized for the few reads that miss. So anything that makes many reads miss together can overload it. That can be one busy key expiring, many keys expiring at once, or requests for keys that do not exist.

Why it matters

A cache protects the database only while the right keys are in it. Memory is limited, so a full cache must choose a key to remove. When a busy key goes missing, every request for it reaches the database at once. That is how a cache problem becomes a database outage.

A worked example

Suppose a popular key gets 5,000 reads a second, then expires, and recomputing it from the database takes 200 ms. Every request that arrives during those 200 ms misses the cache. About 5,000 × 0.2 = 1,000 requests hit the database at the same time, instead of one request recomputing the value.

Think of it like…

Think of a shared office fridge with room for 20 lunches. When it is full, the lunch that has sat untouched the longest is taken out to make room.

Where this analogy stops working

Removing what nobody has used lately is the useful part. But a fridge shows nothing like a stampede. When a busy key expires, every request for it misses together. All of them then ask the database for the same value at once.

Try it

See it working

Live simulationOpen the full lab →

Lab · Building blocks

Caching

A cache keeps copies of popular data in memory so most reads skip the slower database. See when that works, what happens on writes, and the three classic failure modes: stale data, stampedes and cold starts.

Try it

Lab time 3.0 s
get / setreads on miss, writesClients, 100% readsClients100% reads12 ops/sApp server, Cache-asideApp serverCache-asideCache (Redis), LRU · TTL offCache (Redis)LRU · TTL off6/6 keysDatabase, source of truthDatabasesource of truth4 reads/s
About each part:
  • Clients — 100% reads — healthy — 12 ops/s
  • App server — Cache-aside — healthy
  • Cache (Redis) — LRU · TTL off — healthy — 6/6 keys
  • Database — source of truth — healthy — 4 reads/s
  • Request
  • Cache hit
  • Cache miss → DB
  • Stale data
  • Write
  • Invalidate
  • Response
Hit rate
36%
Watch: most reads miss
Database reads
4/s
Read latency,
570 ms
At the server: hits 30 ms, misses 290 ms
Stale reads
0
Write latency,
—
Lost writes
0

Numbers add up:33 reads = 12 hits + 21 misses; misses = 21 DB reads + 0 coalescedThe lab checks this sum as it runs, so a counting mistake would show here.

Controls

Traffic
12/s
0%
Key popularity

A few keys get most of the reads (typical web traffic).

Cache
6 keys
Eviction

Evict the key that was used least recently.

(TTL)
Writes & failures
Write strategy

Reads fill the cache on a miss. Writes go to the database, then delete the cached copy.

One DB read per key at a time; other misses wait for it.

What's in the cache right now

Evicted item:20
  • item:1v1 · used 5×
  • item:3v1 · used 5×
  • item:6v1 · used 2×
  • item:7v1 · used 2×
  • item:5v1 · used 1×
  • item:2v1 · used 1×

Keys are ordered by when they entered the cache. item:1 is the most popular key, item:20 the least.

Hit rate
0%25%50%75%100%1s2s3s
Show data table
TimeHit rate
1s0%
1s33%
2s57%
2s60%
3s40%
3s50%
Database reads per second
051015201s2s3s
Show data table
TimeDB reads/s
1s18
1s4
2s6
2s4
3s6
3s4

What just happened

  1. 0.3sWarning: Duplicate DB read: item:5 missed again while its first DB read was still running. With heavy traffic this becomes a stampede.
  2. 0.0sInfo: Cache ready: 6 slots, LRU eviction, Cache-aside.
What this model simplifies
  • Time is slowed: a database read takes 0.26 s here so you can watch it. Real ratios are similar in spirit — memory is roughly 10–100× faster than a database round trip.
  • The trip between client and server is slowed too, and it is the same for a hit and a miss. "At the server" leaves it out, so it shows what the cache itself saves.
  • The cache is a single node. Real deployments shard keys across many nodes and replicate them.
  • Write-behind flushes every 2.5 s in one batch. Real systems flush by time or batch size and may persist a log to survive crashes.
  • Every key has the same size and cost. In practice big or expensive-to-compute values change which keys are worth caching.

Mechanics

How it works

A full cache has to remove a key, and a missing key sends its reads to the database. This page shows both on one small shop: an app, a cache and a database.

First comes which key goes when the cache is full. Then come the three ways that many reads can miss at once: one busy key, many keys together, and keys that do not exist.

  1. When the cache is full: LRU or LFU

    Pick a case to follow below

    With this case: LRU removed A, the most-read key, because B and C were read after it. The next read of A missed. 5 database reads in all.

    App, the shopAppthe shopCache, room for 3 keys, NOWCacheroom for 3 keysANOWDatabase, the real recordDatabasethe real record
    • App — the shop — healthy
    • Cache — room for 3 keys — healthy — NOW — A
    • Database — the real record — healthy
    • Read
    • Read that misses
    Step 1 of 4

    Step 1 of 4 · Cache

    Done: A is read three times

    What happens
    The first read misses, so the app loads A from the database. The next two reads are hits.
    Why
    A is the popular key here, the one most worth keeping.
    What changes
    The cache holds A, read 3 times.
    Next
    B and C are read once each
    In the cache
    A
    1 of 3 keys
    Reads of A
    3
    A is cached
    Database reads
    1
    one for each miss

    Step 1 of 4: Cache. A is read three times. The first read misses, so the app loads A from the database. The next two reads are hits.

    When the cache is full, it must remove (evict) a key to make room. The rule it uses decides which one. In the picture, the cache has room for 3 keys. Switch between the two rules.

    LRU (least recently used) removes the key that nobody has read for the longest time. It keeps the keys in order of last use, so finding that key takes one step. In the first case A goes, even though A was read 3 times, because B and C were read after it.

    (least frequently used) counts the reads of each key and removes the key with the fewest. In the second case B goes, and the next read of A is a hit. LFU protects keys that stay popular, but it is slow to notice when an old favourite goes cold.

    LRU is the common choice, because it is cheap and suits most traffic. lets you pick: its settings include LRU and LFU rules. By default it evicts nothing and refuses new writes when its memory is full.

  2. Cache stampede (thundering herd)

    Pick a case to follow below

    With this case: With no lock, 5 requests made 5 database reads for one value. At 5,000 requests a second, about 1,000 arrive in 200 ms, and each one reads the database.

    App, the shopAppthe shopCache, room for 3 keys, NOWCacheroom for 3 keysitem:1 expiredNOWDatabase, the real recordDatabasethe real record
    • App — the shop — healthy
    • Cache — room for 3 keys — healthy — NOW — item:1 expired
    • Database — the real record — healthy
    • Read that misses
    • Value
    Step 1 of 4

    Step 1 of 4 · Cache

    Watch: item:1 expires

    What happens
    Its TTL runs out, and the cache drops it. Rebuilding it takes one database read of 200 ms.
    Why
    item:1 is the busiest key, so many requests ask for it every second.
    What changes
    The next read of item:1 will miss.
    Next
    Request 1 misses and reads the database
    Database reads for item:1
    0
    one rebuild
    Requests waiting
    0
    none: each reads for itself

    Step 1 of 4: Cache. item:1 expires. Its TTL runs out, and the cache drops it. Rebuilding it takes one database read of 200 ms.

    A busy key expires, and every request for it misses until one database read brings it back. In the picture, 5 requests arrive during the 200 ms that this read takes.

    With no lock, each miss starts its own database read. All 5 read the same value, so 4 of those reads are wasted. Now say the key gets 5,000 reads a second. About 1,000 requests miss in those 200 ms, and every one of them queries the database.

    The fix is a lock per key. The first request that misses takes the lock and reads the database. The others wait, then read the new copy from the cache. This is also called . In the second case, 5 requests cost 1 database read.

    Another fix is to refresh a busy key a little before it expires, so readers never find it missing. The caching strategies page shows this as refresh-ahead.

  3. Cache avalanche

    Pick a case to follow below

    With this case: With the same TTL, all 4 keys expired at second 60, and the database got 4 reads at once. With thousands of keys, that is an avalanche.

    App, the shopAppthe shopCache, room for 3 keys, NOWCacheroom for 3 keys4 keys cachedNOWDatabase, the real recordDatabasethe real record
    • App — the shop — healthy
    • Cache — room for 3 keys — healthy — NOW — 4 keys cached
    • Database — the real record — healthy
    • Read
    • Read that misses
    Step 1 of 2

    Step 1 of 2 · Cache

    Done: Four keys are loaded in the same second

    What happens
    At second 0 the app caches 4 keys, each with the same TTL of 60 s.
    Why
    Keys loaded together, such as after a restart or a nightly job, all start their TTL together.
    What changes
    All 4 keys will expire at second 60.
    Next
    At second 60, all 4 keys expire together
    Clock
    0s
    Keys still cached
    4
    of 4
    Most database reads in one second
    0
    one at a time

    Step 1 of 2: Cache. Four keys are loaded in the same second. At second 0 the app caches 4 keys, each with the same TTL of 60 s.

    What these pictures simplify. These pictures use a cache with room for 3 keys, 5 requests and 4 keys, with stated times. A real cache holds millions of keys and gets thousands of reads a second. The random extras are stated examples. The Caching lab above runs many requests at once.

    An avalanche is many keys expiring in the same second. In the picture, 4 keys are loaded together at second 0, each with a TTL of 60 s.

    Keys loaded together, such as after a restart or by a nightly job, start their TTL together. With the same TTL they also run out together, and their reads reach the database at once. With thousands of keys, that can overload it.

    The fix is a random extra on each TTL, such as 0 to 30 s. In the second case the 4 keys expire at seconds 67, 73, 82 and 88, so the database gets one read at a time.

  4. Cache penetration

    Penetration is a flood of requests for keys that do not exist, such as item:-1. None of them is ever cached, so every request reaches the database.

    One fix is to cache the "not found" answer for a short time, so a repeat asks the cache and not the database. Another is to check a first. It can say for sure that a key does not exist, so those requests stop before the database.

When many reads miss at once
ProblemWhat causes itThe usual fix
StampedeOne busy key expiresOne lock per key, or refresh the key early
AvalancheMany keys expire in the same secondA random extra on each TTL
PenetrationRequests for keys that do not existCache the "not found" answer, or check a Bloom filter
Cold startThe cache restarts emptyWarm it up before it takes traffic

Use it when

  • Setting a memory limit on a cache such as Redis or Memcached: you must also pick the rule it uses to evict keys.
  • A busy key that is slow to rebuild: add a lock or an early refresh. Then one expiry does not send every reader to the database.
  • Keys that users can make up, such as /item/999999: cache the "not found" answer or check a Bloom filter first.

Skip it when

  • A data set small enough to fit in memory with room to spare: nothing has to be evicted, so the rule does not matter.
  • A key that is cheap to rebuild and rarely read: a stampede on it is a handful of fast queries, so a lock adds nothing.

Check yourself

A cache using LRU is full, and a new key arrives. Which key is removed?

Judgement

Trade-offs and how it fails

What you give up

Memory
Exact LRU keeps every key in a list ordered by last use, which costs two extra pointers for each key. Redis saves that memory: it samples a few keys and evicts the oldest of the sample, which is close to LRU but not exact.
Concurrency
A lock per key stops a stampede, but every other request for that key waits while one rebuilds it. If the rebuild is slow or fails, they all wait or fail with it, so the lock needs a .

Failure modes

  • Avalanche: every key was loaded at midnight with the same 24-hour TTL. They all expire together the next midnight, and the database gets every read at once.
  • Penetration: an attacker asks for ids that do not exist, such as -1 or abc. None is in the cache, so every request runs a database query.
  • A cold start: after a restart the cache is empty, so the database takes all the reads until it fills again.

In the real world

  • Facebook's paper "Scaling Memcache at Facebook" (2013) describes leases, which let one client refill a missing key while others wait. Source: USENIX: Scaling Memcache at Facebook (2013) (checked 14 October 2026)
  • Redis's documentation lists eviction policies such as allkeys-lru and allkeys-lfu. In open-source Redis the default is noeviction, which removes nothing and refuses new writes when memory is full. Managed services may set another default.

Trade-offs to be ready to discuss: Lru vs lfu

Check yourself

The cache cluster restarts and comes back empty. What is the main danger?

Interview

What interviewers look for

  • Name the problem, then its fix: "Keys loaded together expire together, so I add a random extra to each TTL."
  • For ids that do not exist: "I cache the not-found answer for a short time, or check a Bloom filter first."
  • For a busy key: "On a miss, one request rebuilds the value under a lock, and the others wait for it."

Say it out loud: How does a Bloom filter stop cache penetration?

A popular key takes 200 ms to rebuild and gets 5,000 reads a second. It expires. What protects the database?

Expected depth by interview level

Levels describe the depth interviewers probe, not years of experience. Choose a level on the learning path to highlight it.

JuniorUseful
LRU at a high level.
MidExpected
Eviction policies and cold caches.
SeniorCore
Stampedes, hot keys and cache failure modes.
StaffExpected
Designing so a cache outage degrades the service rather than breaking it.

Practice

Apply it

Three harder questions

The first two use the idea on a new case. The last asks you to judge a design.

Apply it

A full cache holds 3 keys. A was read 50 times, last an hour ago. B was read once, a minute ago. C was read twice, 5 minutes ago. Key D arrives. With LFU, which key is removed?

Apply it

A job loads 10,000 keys at midnight, each with a 24-hour TTL. How do you stop them all expiring in the same second the next night?

Judge a design

Attackers request item:-1, item:abc and other ids that do not exist, 5,000 a second. Every request reaches the database. Which design stops this?

Next: SQL and NoSQL databases, where the data lives when it is not in the cache, and how to choose between them.

Go deeper

Sources and further reading

First-hand sources to check this page against and to go further. They are standards, official docs, original papers, and guides from engineering and security teams. Each link was opened on 8 November 2026.

  • Official docsKey evictionRedis documentationEach Redis eviction policy, and why its LRU and LFU are close estimates rather than exact.
  • Research paperScaling Memcache at Facebook (2013)Nishtala et al., USENIX NSDILeases: how Facebook stops many servers rebuilding the same missing key at once.