Caching

Cache stampede and thundering herd

Why one expired key or one cache restart can take a database down, how to tell stampede, avalanche and penetration apart, and which fix fits each.

Lesson13 min read
Video walkthrough: not recorded yet. The lesson below is complete without it.

The problem

A news site caches its “top stories” block under one key. Building it takes a 200 ms aggregate query. The key has a 60 second TTL and is read 5,000 times a second, so for almost the whole minute the database never sees this query.

Then the key expires. The first request to notice starts the query. It will take 200 ms, and in that time another 1,000 requests arrive, miss, and start the same query. A database that ran this query once a minute now runs a thousand copies at once. Each one slows the others, so the cache stays empty for longer and more requests pile in.

A cache stampede when one hot key expires4 components: Clients, App servers, Cache, Database. Connections: Clients to App servers; App servers to Cache; App servers to Database (on a miss).Clients5,000 requests a secondApp servers40 instancesCachetop-stories, TTL 60 severy read is a hitDatabasethe query takes 200 msidle for this queryon a miss

Step 1 of 8

One cache key holds the top stories block. It takes a 200 millisecond query to build, and it is read 5,000 times a second. While the key is in the cache, the database never sees those reads.

Read the steps as text
  1. One cache key holds the top stories block. It takes a 200 millisecond query to build, and it is read 5,000 times a second. While the key is in the cache, the database never sees those reads.
  2. The key was stored with a 60 second time to live. When that runs out, the cache drops the entry. Nothing is wrong yet, and no alert fires.
  3. The next request misses. The app server does what cache-aside tells it to do. It starts the 200 millisecond query and plans to store the result when it comes back.
  4. The query is still running, and requests keep arriving at 5,000 a second. In those 200 milliseconds about 1,000 of them reach the cache, find nothing, and each one starts the same query.
  5. A database that ran this query once a minute is now running a thousand copies at once. They compete for CPU, memory and connections, so each takes seconds instead of 200 milliseconds, and the cache stays empty for longer.
  6. While the cache stays empty, every new request also misses and joins the pile. Clients time out and retry, which adds more load. One expired key has turned into an outage.
  7. When the queries finally finish, each one writes the same value into the cache. All but the first were wasted work. The cost of one miss was multiplied by the number of requests that arrived while it was being repaired.
  8. The fix is to make sure a missing hot key is recomputed once, not once for every waiting request. Request coalescing, locks, serving stale data during the refresh and refreshing early all do this in different ways.
A cache stampede when one hot key expires

The first fixes people try do not work. A longer TTL makes the event rarer and exactly as large. A bigger database is paid for all day to survive one bad second a minute. A scheduled job that refreshes the key works for a handful of known keys and not for a million product pages.

The real problem is that the cost of a miss is multiplied by concurrency. Every fix in this lesson breaks that multiplication.

Name Trigger What reaches the database
Cache stampede (dogpile) One hot key expires or is deleted Many copies of one expensive query
Thundering herd Many waiters react to one event: a restart, a deploy, synchronised retries A burst of everything at once
Cache avalanche Many keys expire together, or the cache tier is lost Most reads, across many keys
Cache penetration Requests for keys that do not exist in the database Every such request, every time

Stampede fixes: one recompute per key

Request coalescing

Keep a table of loads in progress, keyed by cache key. The first request to miss starts the load and registers it. Later requests for the same key find the entry and wait for the same result. Go’s singleflight package does this, and so do loading caches such as Caffeine.

Request coalescing lets one request recompute a missing key4 components: Clients, App server, Cache, Database. Connections: Clients to App server; App server to Cache; App server to Database (one load per key).Clients5,000 requests a secondApp server1 of 40, single flightnothing in flightCachetop-stories, TTL 60 sentry expiredDatabasethe query takes 200 msone load per key

Step 1 of 9

The same hot key expires under the same 5,000 requests a second. This time each app server keeps a small table of loads that are in progress, one entry per key. This is request coalescing, also called single flight.

Read the steps as text
  1. The same hot key expires under the same 5,000 requests a second. This time each app server keeps a small table of loads that are in progress, one entry per key. This is request coalescing, also called single flight.
  2. The first request misses in the cache. Before it goes to the database, the app server records that a load for this key is in flight.
  3. It then runs the query. This is the only query this server will run for the key, however many requests arrive in the meantime.
  4. This server receives 125 requests a second, so about 25 more arrive for the same key during the 200 milliseconds. Each one finds the in-flight entry and waits for that result. None of them calls the database.
  5. The query returns once. The server stores the value in the cache with a fresh time to live and removes the in-flight entry.
  6. Every waiting request gets the same result at the same moment. They waited at most 200 milliseconds, and the database did the work once for this server instead of 26 times.
  7. The table lives inside one process, so 40 app servers can still run 40 queries between them. That is usually acceptable. When it is not, a short lock or lease held in the cache lets only one server in the whole fleet recompute.
  8. Waiting is still a delay. If the old value is kept past its soft expiry, requests can be answered with it at once while a single refresh runs in the background. This is stale-while-revalidate.
  9. Coalescing turns a thousand recomputations into one per server. A lock makes it one for the fleet, and serving stale data removes the wait. Most production caches combine at least two of these.
Request coalescing lets one request recompute a missing key

It is cheap and has almost no downside, so use it everywhere. Its limit is that the table lives in one process. Forty servers can still run forty loads. Give the shared load a timeout too, because every waiter inherits its failure.

Locks and leases

To get to one load across the fleet, take a short lock in the cache itself, for example SET lock:top-stories token NX PX 5000 in Redis. The winner recomputes and stores the value. Losers either wait briefly and re-read the cache, or serve a stale copy.

The lock needs an expiry so that a crashed holder does not block the key for ever, and that expiry must be longer than the recompute. Facebook’s memcache paper describes the same idea as a lease: on a miss, the cache gives a token to one client and tells the others to retry shortly.

Choose a lock when a single recompute is very expensive. Do not add one for cheap values, since the extra round trip and the waiting logic cost more than they save.

Stale-while-revalidate

Store two times with each value: a soft expiry and a later hard expiry. After the soft expiry, requests still get the old value at once, and the first of them triggers one background refresh. Nobody waits and the database sees one query.

The trade is freshness: readers can see a value older than the nominal TTL. It also needs the old value to exist, so it does not help a cold cache. HTTP has the same idea as a Cache-Control directive, covered in CDN caching.

Probabilistic early expiry

Let each read decide, at random, to refresh the value a little before it expires. The probability rises as expiry approaches. A published version of this, known as XFetch, refreshes when

now - delta * beta * ln(random()) >= expiry

where delta is how long the last recompute took, beta is a tuning factor that defaults to 1, and random() is uniform between 0 and 1. A slow recompute starts earlier. On a hot key some request almost always refreshes before expiry, with no lock and no coordination. On a cold key nothing refreshes early, which is fine, because a cold key cannot stampede.

Avalanche fixes: do not lose everything at once

  • TTL jitter. Keys loaded together, after a deploy or a batch job, expire together. Add a random 10 to 20% to each TTL so that reloads spread out.
  • Warm-up. Do not send full traffic to an empty cache. Pre-load the hot keys, copy from a peer, or ramp traffic up gradually. A Redis node with persistence restarts with its old data, which is stale but warm.
  • Lose a fraction, not the tier. With consistent hashing across N nodes, one node failing loses about 1/N of the keys.
  • Protect the database. Cap concurrent queries, shed load early, and wrap the fallback in a circuit breaker. Serving some errors is better than a database that cannot recover.

There is a capacity question underneath. If the database can serve only 5% of read traffic, the cache is not an optimisation any more. It is a dependency, and its loss needs a rehearsed plan.

Penetration fixes: stop asking for what is not there

A request for product:999999999 misses the cache, finds nothing in the database, and leaves nothing to cache. Repeat that a million times, by accident or as an attack, and the cache gives no protection.

  • Negative caching. Store a “not found” marker with a short TTL, such as 30 to 60 seconds. Delete the marker when the item is created, or new items look missing. Random keys from an attacker each take an entry, so keep the TTL short.
  • Bloom filter. Keep a Bloom filter of all existing ids in front of the cache. It answers “definitely absent” or “possibly present” using about 10 bits per key for a 1% false positive rate. False positives fall through to the normal path. It must be updated on every insert, and a standard Bloom filter cannot remove a key.
  • Validation and limits. Reject ids with an impossible format or range, and rate limit clients that generate many misses.

Choosing a fix

Situation Reach for
Any cache with concurrent readers In-process coalescing
Hot key, slight staleness is fine Stale-while-revalidate or early expiry
Recompute is very expensive A lock or lease, with stale fallback
Keys loaded in bulk TTL jitter
Cache restart or new node Warm-up and database limits
Lookups for missing keys Negative caching, Bloom filter

When should you not bother? A key read once a minute with a 2 ms query cannot stampede. Most of these mechanisms matter only for the small set of keys that are both hot and expensive, so find those keys first.

In the interview

Raise this yourself whenever you add a cache in front of something slow. A simple prompt is to ask, out loud, “what happens when this key expires at peak?” and then answer it.

A strong answer gives the arithmetic (request rate times recompute time is the size of the herd), then layers the fixes: coalescing by default, stale-while-revalidate for the hot keys, jittered TTLs, and a concurrency limit on the database as the last line. If the interviewer mentions missing keys or an attacker, switch to penetration and offer negative caching and a Bloom filter. Naming the failure precisely before fixing it is what separates this answer from a list of buzzwords.

Key takeaways

  • A stampede multiplies the cost of one miss by the number of requests that arrive while the value is being recomputed.
  • The core fix is one recompute per key: coalesce requests in process, and add a lock or lease when one per server is still too many.
  • Stale-while-revalidate and probabilistic early expiry avoid the wait altogether by refreshing before, or while, the old value is still served.
  • An avalanche is many keys or a whole cache tier lost at once. Jitter the TTLs, warm caches before they take traffic, and protect the database with limits.
  • Penetration is requests for keys that do not exist. Cache the negative result briefly, or reject them early with a Bloom filter and input validation.
  • A cache that hides a database able to serve only a few percent of traffic is a dependency, and its failure needs a plan.

Check yourself

1. A key is read 2,000 times a second and takes 500 ms to recompute. With plain cache-aside and no protection, roughly how many recomputations start when it expires?
2. A fleet of 30 app servers uses in-process request coalescing. A hot key expires. What is the worst case for database queries for that key?
3. After a deploy that flushed the cache, a service's keys were all reloaded within a minute, each with a 1 hour TTL. What should the team expect an hour later, and what prevents it?
4. An attacker requests millions of random product ids that do not exist. Each request misses the cache and queries the database. Which defence stops the queries without storing an entry per fake id?
5. What does stale-while-revalidate trade away compared with a lock that makes waiting requests block?

0 of 5 answered

Flashcards

These 6 cards are in your review deck. Tap a card to see the answer.

What is a cache stampede?

A hot key expires or is deleted, and many concurrent requests miss and all recompute the same value at once, overloading the backend. Also called a dogpile.

Stampede, avalanche, penetration. What triggers each?

Stampede: one hot key goes missing. Avalanche: many keys expire together or the cache tier fails. Penetration: requests for keys that do not exist, which can never be cached normally.

What is request coalescing (single flight), and what is its limit?

Concurrent requests for the same key in one process share a single load. It bounds loads to one per process, not one per fleet.

How does probabilistic early expiry work?

Each read may refresh the value before it expires, with a probability that rises as expiry approaches and scales with the recompute time. One request refreshes early, so the key never expires under load.

Why add jitter to TTLs?

Keys written at the same time with the same TTL expire at the same time. A random offset of 10 to 20% spreads the reloads out.

Two defences against cache penetration.

Negative caching (store "not found" with a short TTL) and a Bloom filter of existing keys that rejects definite misses. Validate id format and rate limit as well.

Review the deck