AlgoViz

Thundering herd

medium 24 min

A thundering herd, or cache stampede, happens when many requests find the same cached value missing at the same moment and all rebuild it.

Video lesson · Chapter 1 of 5

Ten requests arrive at the same missing product

0:00 / 3:29

Thundering herd in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 1 min.

What it is

A cache protects the database as long as most reads find their value. When a popular value disappears, every reader misses at once. Each one does the sensible thing, which is to ask the database and store the result. Together they do the same work hundreds of times.

This is a cache stampede. The wider name, thundering herd, covers any case where many waiters wake up for one event although only one can make use of it.

Why it exists

A database sized for a 99% hit rate sees only 1% of the reads. If one hot key with a large share of the traffic goes missing, its load can jump many times over within a second.

Worse, the load feeds itself. A slow database makes the rebuild slower, so more readers arrive before it finishes. Timeouts cause retries, and a short gap can become an outage.

A short history

  1. May 2010

    RFC 5861 defines stale-while-revalidate, so that HTTP caches can answer while they refresh.

  2. April 2013

    Facebook engineers publish "Scaling Memcache at Facebook". Their leases deal with stale sets and thundering herds.

  3. 2015

    Vattani, Chierichetti and Lowenstein publish "Optimal Probabilistic Cache Stampede Prevention", with the XFetch algorithm.

Words to know

Hot key
A key that receives a large share of the reads.
Rebuild
Fetching or computing a missing value and storing it.
Single flight
Joining identical calls so that only one runs at a time.
Lease
A permission to fill a key, given to one reader for a short time.
Soft TTL
After it, the value is stale but may be used while it is refreshed.
Hard TTL
After it, the value may not be used.
XFetch
Refreshing early with a probability that rises towards expiry.

How it works

Step through the idea, or press Play.

Step 1 of 3

A hot value disappears. It expires, is deleted or the cache restarts

Understand it

Start here

Ducks and the feed box

Imagine six ducks and a feed box. While there is feed, nobody bothers the person who looks after them. When the box is empty, they all run to that one person.

The empty feed box
FEEDBox full: nobody asks for feed

The ducks need one refill, not six.

The problem

When it happens

  • Expiry

    The TTL of a popular key ends.

  • Invalidation

    The key is deleted because the data changed.

  • Cold restart

    The cache restarts empty, so every key is missing.

  • Same TTL

    Many keys stored together expire together.

The cascade

  1. 1

    12:00:00

    The key for product 123 expires.

  2. 2

    12:00:01

    100 requests arrive for it.

  3. 3

    All miss

    Nobody has stored a new value yet.

  4. 4

    All query

    100 identical queries reach the database.

  5. 5

    Overload

    CPU and connections are used up. The answer that took 10 ms may now take seconds, callers time out and retry.

Without protection

300 readers reach three app servers, 100 each. All miss in the cache, where the key has expired, and all three servers query one database, which receives 300 queries.
Three machines, one database. To keep the picture readable, only server 3 shows its look into the cache.

How big is the herd?

Q≈λ⋅D2,000/s×0.2 s=400Q \approx \lambda \cdot D \qquad 2{,}000/s \times 0.2\,s = 400
Read rate of the key times rebuild time. If overload stretches the rebuild to 2 s, the same key causes 4,000 queries.

Why it feeds itself

Solution 1

One process: single flight

Inside one server, keep a map of rebuilds that are running. The first caller starts the work, later callers for the same key wait for that result. Go has the singleflight package for exactly this.

It needs no network and no lock service. Its limit: 20 servers can still send 20 queries. For most systems that is already fine.

Two callers, one query

Solution 2

Many processes: a lock

How it works

  1. 1

    Miss

    The value is not in the cache.

  2. 2

    Try to take the lock

    Set a lock key only if it does not exist, with an expiry.

  3. 3

    The winner

    Checks the cache once more, queries, stores, then releases the lock.

  4. 4

    The others

    Wait a little and read the cache again, or use a stale value. They stop after a limit.

With a lock

The same 300 readers on three app servers. Server 1 holds the lock kept in the cache, asks the database once and fills the cache. Servers 2 and 3 wait on the cache. The database receives one query.
Each server joins its own callers, and one server holds the lock.
Text
SET lock:product:123 <token> NX EX 10# OK  -> you have the lock# nil -> somebody else has it# release only your own lock, in one atomic script:if redis.call("get", KEYS[1]) == ARGV[1] then  return redis.call("del", KEYS[1])else  return 0end
Redis lock. The token is random and different for every attempt.

Solution 3

Refresh early, by chance

XFetch lets each reader of a still valid value decide, at random, to refresh it now. Far from expiry almost nobody does. Close to expiry somebody probably will, and the value is renewed before the gap.

XFetch

refresh if now−Δ β ln⁡(rand)≥expiry;⇒;P=e−gap/(Δβ)\text{refresh if } now - \Delta\,\beta\,\ln(rand) \ge expiry ;\Rightarrow; P = e^{-gap/(\Delta\beta)}
Δ\Delta is how long the rebuild takes, β\beta is normally 1, randrand lies between 0 and 1, gapgap is the time left.

Chance per read, rebuild takes 2 seconds

Time leftChance to refresh
20 sabout 0.005%
6 s5%
2 s37%
1 s61%
0 s100%
It depends on the rebuild time, not on the length of the TTL. With 1,000 reads a second, the first refresh usually starts about 15 seconds before expiry.

No locks, no waiting, no background worker. But several readers may still refresh close together, and a key that is hardly read gets no early refresh.

Solution 4

Serve stale while one refreshes

Give each value two limits. With a soft TTL of 300 s and a hard TTL of 600 s, the value is fresh up to 300, stale but usable from 300 to 600, and gone after 600. In the middle zone readers get the old value at once, and one refresh runs.

Two limits

Guard the refresh with a lock or single flight, or every stale read starts one.

More tools

Other ways to calm the herd

  1. 1

    Leases

    On a miss the cache gives one reader a token to fill the key and tells the others to wait briefly. At Facebook, tokens were given once per 10 seconds per key by default; for a set of keys prone to herds the peak database rate fell from 17,000 to 1,300 queries a second.

  2. 2

    Jitter

    Random TTLs, for many keys that were stored together. See cache TTL.

  3. 3

    Background refresh

    A worker renews a known list of hot keys, so readers never rebuild.

  4. 4

    Warming

    Fill a new cache before it takes traffic.

  5. 5

    A limit on the database

    Allow only N rebuilds at a time and fail the rest fast. The last line of defence for a cold restart.

CDNs and proxies do the same. CloudFront collapses simultaneous requests for the same object, and nginx has proxy_cache_lock, which is off by default.

Compare

Which one?

SolutionGoodCostBest for
Single flightNo network, simpleOne query per processAlways, as a base
Lock or leaseNormally one queryWaiters, lock handlingExpensive rebuilds, strict freshness
Early refreshNo locks, no waitingSome extra queriesSteady, busy keys
Serve staleAlways fastOld data for a while, kept longerPages where speed matters most

Choosing

Combine them: serve stale to readers, and use a lock so that only one background refresh runs.

Failure

What can go wrong with the cure

ProblemAnswer
The winner crashesThe lock expires by itself; waiters try again
The rebuild failsRelease the lock, keep the old value, retry with a pause
The value does not existStore a short negative entry, or waiters queue forever
Waiters wait too longA deadline, then a stale value or an error
Waiters poll togetherRandom pauses
One lock for all keysOne lock per key

Operate

See it before users do

  1. 1

    Count rebuilds per key

    More than one at a time means no protection.

  2. 2

    Measure the rebuild time

    The herd grows with it, so a faster query is also a fix.

  3. 3

    Count joined calls

    How many requests shared a result shows what the protection saves.

  4. 4

    Test it

    Delete the hottest key during a load test and look at the database.

Very hot keys have more problems than expiry. High-concurrency caching covers them.

Summary

The whole topic in one minute.

A stampede needs a hot key, a moment without a value and a rebuild that takes time. The number of duplicate queries is roughly the read rate times the rebuild time.

Let one request rebuild: single flight in each process, a lock or lease across processes. Better still, never let the value vanish: serve stale while one request refreshes. Add jitter for many keys, and protect the database with a limit as the last line.

  • A stampede is many misses on one hot key at once.
  • Its size is the read rate times the rebuild time.
  • Single flight first, a lock or lease across processes.
  • Serving stale removes the wait as well as the herd.
  • Jitter is for many keys; it does not help one.

Sources