Video in progress

What is a cache stampede (dogpile), and how do you protect against it?

When a popular key expires, hundreds of requests miss at once and send the same heavy query to the DB. Protection: let a single request do the reload (a lock or sync = true), refresh in the background before expiry, and add random extra time to the TTL.

📖 Answer

On prod it looks like this: every 10 minutes the DB CPU briefly hits 100% and the API p99 spikes. On the graph, sawtooth teeth.

The main techniques:

  1. A single loader. The request that got the miss does SET lock:product:5 1 NX PX 5000. The one that got the lock goes to the DB, and the others wait briefly and re-read the cache or return the stale value.

  2. sync = true in Spring:

@Cacheable(cacheNames = "home-page", key = "'main'", sync = true)
public HomePageDto homePage() { ... }

This guarantees that within one JVM a single thread loads a given key. With several instances, one request from each goes to the DB, which is usually enough.

  1. Early refresh. Store the "created at" time along with the value. Once 80% of the TTL has passed, the first request to arrive refreshes it in the background while the others still get the old value.

  2. TTL jitter. If many keys are created at the same time, give them 600 + random(0..120) seconds so they don't all die together.

For very popular data that is expensive to compute (the home page), I don't wait for expiry at all. A scheduler rewrites it every minute.