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.

See it run

Ten readers, one missing key. Count the database queries.

Operations

No protection

Every reader does what looks sensible.

Step 1 of 7

The key expires

Our systemproduct 123queryRequest 1Requests 2 to 5Requests 6 to 10APIno lockCacheexpiredDatabaseidle
Database load
5%

The TTL of product 123 ends.

Step 1: The key expires

def get(key):    value = cache.get(key)    if value is None:        value = db.query(key)      # everybody is here        cache.set(key, value, 300)    return value
Queries
10
Readers
all slow
Needed
1 query

Each request is correct on its own. The problem is that nobody knows about the others.

In the real world

The same thundering herd doing real jobs. Pick one and step through it.

Every key is missing, not just one.

Step 1 of 3

Empty cache

Our systemproduct 123queryRequest 1Requests 2 to 5Requests 6 to 10APIno lockCacheemptyDatabaseevery key
Database load
100%

The cache restarts. Every request for any key misses.

Step 1: Empty cache

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • A lock that never expires

    critical

    If its owner crashes, nobody can rebuild the key again.

    Wrong
    cache.set("lock:k", 1, nx=True)
    Right
    cache.set("lock:k", token, nx=True, ex=10)
  • Waiting without a deadline

    critical

    A rebuild that keeps failing holds every waiter, and the server runs out of threads.

    Wrong
    while not cache.get(k): sleep(0.1)
    Right
    while now() < deadline:    if v := cache.get(k): return v    sleep(random.uniform(0.05, 0.15))raise TimeoutError
  • Releasing a lock that is not yours

    major

    After expiry somebody else may own it.

    Wrong
    cache.delete("lock:k")
    Right
    delete_if_equal("lock:k", my_token)   # atomic
  • Refreshing on every stale read

    major

    Between soft and hard limit, each reader starts a refresh: the herd moves to the background.

    Wrong
    if stale: in_background(rebuild, k)
    Right
    if stale and try_lock(k):    in_background(rebuild, k)

Interview tips

  • How to explain it

    • One value missing, many readers.
    • Everybody does the same work.
    • Let one do it; the rest wait or use the old value.
  • Memory trick: STAMPEDE

    • Simultaneous, TTL over, All miss.
    • Multiple queries, Performance drops.
    • Everyone waits, Database overwhelmed, Explosive failures.
  • Order of work

    • Single flight in each process.
    • Serve stale where allowed.
    • A lock or lease for costly rebuilds.
  • Never forget

    • Expiry and token on the lock.
    • A deadline for waiters.
    • A limit for a cold restart.