Module 4 · Caching and performanceLesson 43 of 886 minAdvanced

Cache stampedes

When a very popular cache entry expires, every request misses at once and they all rush the database together.

Try it

With no protection, watch the database spike every time the hot key expires. Then try "One refill (lock)" and "Refresh early".

Caches protect the database most when traffic is high. Which means the moment a very popular entry expires is the most dangerous moment of all.

What happens

  1. The home page is cached with a 30-second TTL.
  2. It expires.
  3. In the next 200 ms, thousands of requests miss.
  4. Each one runs the same expensive query against the database.
  5. The database slows down, so the rebuild takes longer, so even more requests miss.

This is a cache stampede (also called the thundering herd or dog-piling).

Fixes

1. Lock (single flight): the first request that misses takes a lock and rebuilds the value. Others wait briefly for it, or are served the old value while the rebuild happens. One query instead of thousands.

2. Refresh early: refresh the value before it expires, in the background, while still serving the cached copy. A popular trick is probabilistic early refresh: as expiry gets closer, each request has a growing chance of triggering a refresh.

3. Serve stale while revalidating: keep the old value after the TTL and serve it while one background job fetches the new one. HTTP even has a header for this (stale-while-revalidate).

4. Jitter: random TTLs, so many keys don't expire at the same moment.

5. Never expire, update instead: for a handful of critical keys, a background job rewrites them every few seconds, so they never go missing.

The general lesson

Anything popular that "resets" at a single moment can cause a herd: cache expiry, a cron job on every server at midnight, every client reconnecting after an outage. Spread things out in time.

Quick check

Your home page is cached for 30 seconds and gets 5,000 requests a second. Every 30 seconds the database spikes. What's happening?