Building at scale · L1Caching and cache stampedes

Caching and cache stampedes

A cache makes reads fast and cheap, until one popular key expires and every request rushes to the database at once.

L1 Must-knowBuilding at scale14 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 21 Oct 2026 · How we check content
Senior at work · lesson 6 of 26
Section 1 of 8

What broke

A made-up story to show a common failure. Not about a real company.

This story is made up, but it is common. A shopping app runs a flash sale at 8 pm. The product page for one phone gets 5,000 requests a second.

The page data sits in Redis with a TTL of 60 seconds. The database is sized for the normal load: a few hundred queries a second. This works while the cache answers almost every read.

At 8:01 pm the key expires. In the next 200 ms, about a thousand requests find nothing in the cache. Each one runs the same heavy query against the database.

The database slows down, so the queries take longer. More requests miss while they wait, and they also go to the database. The product page times out, and the sale page shows errors for ten minutes.

Nothing was wrong with the code or the cache. One popular key expired at the worst moment.

Section 2 of 8

The idea in simple words

A cache is a fast copy of data that is slow or costly to get. You read the copy instead of asking the database every time. A cache hit is fast. A cache miss means you must go to the source.

Every cache has to answer three questions:

  1. How does data get in? The app fills it, or the cache fills itself.
  2. When does data leave? It expires (TTL), it is deleted on a write (invalidation), or it is pushed out when memory is full (eviction).
  3. What happens on a miss? If a key is popular, a miss is not one query. It can be thousands.

The key idea. A cache does not just make reads faster. It hides load. When a hot key expires, all that hidden load hits the database at once. Design for that moment.

That moment is called a cache stampede. A popular item expires, and many requests miss and rebuild the same item at the same time. 4 The Facebook memcache paper calls a similar problem a thundering herd: writes keep deleting a hot key, so many reads go to the database. 1

Section 3 of 8

How it works

Ways to fill a cache

  • Cache-aside. The app checks the cache. On a miss, the app reads the database and writes the value into the cache. Facebook uses its memcache this way. On a write, it updates the database and then deletes the cache key. It deletes instead of updating because deletes are idempotent. 1
  • Read-through. The app only talks to the cache. On a miss, the cache itself loads from the database.
  • Write-through. Each write goes to the cache and the database together. The cache stays fresh, but every write is slower.
  • Write-behind. Writes go to the cache first and reach the database later, in batches. Writes are fast, but you can lose data if the cache dies first.

AWS calls a cache that the app code manages a "side cache", like cache-aside. Read-through and write-through are "inline caches". With an inline cache, the app needs no cache code. But if the cache fails, the app cannot work around it. 2

TTL, invalidation and eviction

A TTL sets how long a value lives. Pick it from two facts: how old the data may be, and how often the source changes. Then measure cache hits and misses, and adjust. 2

Invalidation removes a key when the data changes. It keeps data fresh, but you must find every place that writes the data.

Eviction removes keys when memory is full. In Redis you set a maxmemory limit and a policy. allkeys-lru removes the least recently used keys. Redis calls it a good default when some keys are read far more often than others. 5

The stampede, step by step

Step through what happens when a hot key expires. Use Next and Back, or the ← and → keys.

A hot key expires: a stampede, then the same moment with request coalescing Requests Cache Database GET product:425,000 per secondproduct:42quiet TTL ended miss × 1,000overloadedA · same query, 1,000 times B · coalescing or a lease1 query999 others wait set product:42same answer✓ 1 query, not 1,000 SeniorPath
  1. A popular product key sits in the cache. 5,000 requests a second read it, and almost none reach the database.
  2. The key's TTL ends, and the cache drops it. The next requests will all miss.
  3. Path A, no protection. About 1,000 requests miss before the first reload finishes. Each runs the same query, and the database is overloaded.
  4. Path B, with a lease in the shared cache (or coalescing, if there is one server). Only the first request that misses loads the key. The other 999 wait for that one answer.
  5. The one query returns. The value goes back into the cache, and every waiting request gets the same answer. The database ran 1 query, not 1,000.
Step 1 of 5

Now try it yourself. Turn request coalescing on and off, and change the traffic.

Try it: what happens when a hot key expires

Four ways to stop a stampede

1. Request coalescing (single-flight). Only one load runs per key. Others wait for it and share the answer. Go's singleflight package does exactly this inside one server. 6 AWS uses coalescing so only one request is pending for an uncached item. 2

2. Locks or leases in the cache. Coalescing inside one server still leaves one query per server. With 200 servers, that is 200 queries. A shared lock in the cache fixes this. Facebook's memcache gives out a "lease" token on a miss. By default, it gives at most one token per key every 10 seconds. Other clients are told to wait a moment and try again. 1 In Facebook's case, the herd came from writes that kept deleting a hot key. Over one week, for keys prone to thundering herds, peak database load fell from 17,000 to 1,300 queries a second. 1

3. Refresh early, with randomness. Refresh a hot key a little before it expires, so it never goes missing. If every server refreshes at the same moment, you get a smaller stampede. So each request decides at random, and the chance rises as expiry gets closer. 4 Also add jitter to TTLs, so keys loaded together do not all expire together.

4. Serve stale while you refresh. Keep the old value a little longer and return it while a refresh runs in the background. Serving stale data does not by itself limit the refresh to one request. Add coalescing or a lock, so only one request fetches the new value. HTTP has a header for serving stale data: stale-while-revalidate. With max-age=600, stale-while-revalidate=30, a response is fresh for 600 seconds. A cache may then serve it stale for 30 more seconds while it checks for a new copy. 3 AWS describes a similar idea: refresh after a "soft" TTL, and keep using the old value until a "hard" TTL if the source fails. 2

Section 4 of 8

Trade-offs

FixStops the stampede?CostUse it when
Request coalescing in each serverPartly. One query per server, not one in total.Small code change.Always, as a first step.
Lock or lease in the shared cacheYes One query in total.Waiting clients add latency. Lost locks need a timeout.Many servers and very hot keys.
Early refresh with jitterYes , for keys that are read often.Some extra loads before they are needed.Hot keys you can predict.
Stale-while-revalidateYes , with coalescing. Users get the old value fast.Users may see data a few seconds old.Data where a little staleness is fine, like product pages.
Longer TTL onlyNo It only makes stampedes rarer.More stale data.Data that rarely changes.

Simple rule: add coalescing everywhere. For your top keys, add stale-while-revalidate or a lease too.

Section 5 of 8

At work: how a senior uses this

  • Ask in design reviews: "What happens to the database if the cache is empty?" If the answer is "it crashes", you depend on the cache. Plan for a cold start. 2
  • Know your hot keys. Track the top keys by reads. A sale, a viral post or a homepage banner creates new ones.
  • Decide how stale each kind of data may be. Write it down: "prices: 5 seconds, product text: 10 minutes".
  • Watch hit rate, evictions and database load on the same dashboard. A falling hit rate is an early warning.
  • Never flush the whole cache in production without a plan. It turns every key into a miss at once.
  • Cache "not found" and error results too, with a short TTL. Otherwise a missing item sends every request to the database. AWS suggests a separate TTL for error results. 2
Section 6 of 8

With AI

What to ask the agent

"Wrap this getProduct function with cache-aside in Redis. Use request coalescing so only one database call runs per key at a time."

"Add a soft TTL and a hard TTL. After the soft TTL, return the cached value and refresh it in the background. Add 10% random jitter to both."

"Write a load test where 1,000 requests ask for the same key just after it expires. Assert that the database gets at most 1 query."

What to check yourself

  • The coalescing key is the cache key, not something that differs per user.
  • A failed or slow load does not leave other callers waiting forever. There is a timeout.
  • A lock in Redis has an expiry, so a crashed server does not hold it forever.
  • On a write, the code deletes or updates the cache after the database commit.
  • Error results are not cached for as long as good results.
Section 7 of 8

Check yourself

1. In cache-aside, what does the app do on a cache miss?

Show answer

Reads from the database, then puts the value in the cache. In cache-aside, the app owns the cache. It reads the database on a miss and fills the cache itself.

2. A key read 5,000 times a second expires. Each database query takes 200 ms. Without protection, what happens?

Show answer

Many requests miss at the same moment and all run the same query. That is a cache stampede. Every request that misses before the first reload finishes goes to the database.

3. What does request coalescing do?

Show answer

Sends one database query per key and lets other callers wait for its answer. Only one load runs per key. Duplicate callers wait and get the same result.

4. Why add jitter to TTLs?

Show answer

So keys written at the same time do not all expire at the same time. Keys loaded together, for example after a deploy, would expire together and cause a burst of misses.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 6 sources and related lessons
  1. Nishtala et al., “Scaling Memcache at Facebook”, NSDI 2013 (USENIX) (opens in a new tab)
    Facebook's look-aside cache, why it deletes instead of updates, and leases (section 3.2.1).
  2. Jas Chhabra, “Caching challenges and strategies”, Amazon Builders' Library (opens in a new tab)
    Side caches vs inline caches, TTLs, request coalescing, and the risk of depending on a cache.
  3. Mark Nottingham, RFC 5861: HTTP Cache-Control Extensions for Stale Content (IETF, 2010) (opens in a new tab)
    The stale-while-revalidate and stale-if-error directives, with examples.
  4. Vattani, Chierichetti and Lowenstein, “Optimal Probabilistic Cache Stampede Prevention”, PVLDB vol. 8, 2015 (opens in a new tab)
    Defines the cache stampede and gives a simple random rule for refreshing early.
  5. Redis documentation, “Key eviction” (opens in a new tab)
    The maxmemory limit and every eviction policy, with advice on which to pick.
  6. Go package golang.org/x/sync/singleflight (opens in a new tab)
    A tiny, real request-coalescing library you can read in a few minutes.

Case studies: Discord: Moving trillions of messages from Cassandra to ScyllaDB · Meta: Scaling memcache to billions of requests a second

Related: Distributed caches · CDNs and HTTP caching · Redis in depth · Load shedding and graceful degradation

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper