Video in progress
How does a cache avalanche happen, and how do you prepare the system against it?
Many keys expire at the same time or Redis goes down completely, so the whole load hits the DB at once and takes it down too. Protection: jitter on the TTL, warming the cache beforehand, a circuit breaker for Redis, and limiting the requests that go to the DB.
📖 Answer
If a stampede is about one hot key, an avalanche is about the whole cache layer. Typical scenarios:
- a deploy or a nightly import wrote all the keys at once with a 1-hour TTL, and exactly an hour later everything misses;
- Redis restarted and there's no persistence, so the cache is empty;
- the whole cache was cleared during a deploy because the format changed.
The DB usually sits at a capacity sized for a cache hit ratio of 95%. If the hit ratio drops to 0%, the load goes up 20 times.
What I do:
Duration ttl = Duration.ofMinutes(30)
.plusSeconds(ThreadLocalRandom.current().nextInt(0, 300));
- jitter spreads the expiry times out;
- warm up the hottest keys (the top 1000 products, the home page) at startup or before a deploy (an
ApplicationRunneror a separate job); - a short timeout (100-300 ms) on the Redis client and a Resilience4j circuit breaker, so that if Redis dies, every request doesn't wait 2 seconds;
- a bulkhead or semaphore in front of the DB: at most N "load on miss" requests at a time, and the rest get a stale value or a 503;
- when the cache format changes, instead of clearing everything, a versioned prefix (
v3:), so old and new keys live side by side and the old ones go away on their own with the TTL.
You should test this under load: turn Redis off on purpose and measure how the DB and the API hold up.
Sign up to mark studied questions and save your progress.