SteelReed

Search

Search posts, questions…

7. System Design

Cache failures: avalanche, breakdown, penetration, hot keys and big keys

Six failures that turn the cache from a shield into a weak spot: the cache going down, many keys expiring at once, a hot key expiring, keys that don't exist, keys that are too hot, values that are too big. Causes, fixes (jitter, single-flight, null caching, Bloom filters, local caches) and eviction policies.

18 Nov 20269 min readSenior

–

Post 1 is about the cache being wrong; this one is about the cache failing to absorb the load, so requests pour into the database and it goes down even though the code has no bug. You'll learn to recognize six failures, fix them and pick an eviction policy. Read post 1 first (cache-aside, TTLs); Redis internals are in the Redis series.

1. The problem

A warm-up loads 1 million keys at 00:00, all with TTL = 3600. At exactly 01:00 every key disappears, and 10,000 req/s fall onto a DB built for 100 queries/s. The pool drains, requests time out, clients retry, and the DB goes down.

2. Key idea

The cache is a dike and the DB a field that can only take a puddle.

Incident What happens Main fix
Avalanche (down) the cache cluster dies under load Sentinel/Cluster, circuit breaker, bulkhead limiting misses to the DB
Avalanche (expiry) many keys expire in the same second TTL ± 10% jitter
Breakdown one hot key expires, a thousand requests reload it (stampede) background refresh, Redis mutex, single-flight
Penetration nonexistent ids, every one hits the DB validation, empty values cached 30–60 s, Bloom filter
Hot key one key always lives on one node local cache with 1–5 s TTL, key copies #1..#N
Big key a 5 MB value blocks Redis split, compress; delete with UNLINK

2.1 How do you stop a stampede?

Approach Use when Don't use when
In-JVM single-flight (cache.get(key, loader)) always on, nearly free as the only defense with 50 pods: still 50 loads
Redis mutex SET lock:key token NX PX 3000 hot keys across many pods every key: one extra round trip per miss
Background refresh, no TTL a small, known hot set (home page, flash sale) you don't know which keys are hot

2.2 What gets forgotten?

  • Redis restarts empty: open traffic right away and the DB falls a second time. Warm up, then ramp traffic.
  • @Cacheable(sync = true) is single-flight only inside one JVM with Caffeine; with Redis it doesn't lock per key.
  • A cache-only Redis uses allkeys-lru/allkeys-lfu, not volatile-*.

3. In Java

JAVA
static long ttlWithJitter(long baseSeconds, double jitterRatio) {
    long spread = (long) (baseSeconds * jitterRatio);
    return baseSeconds + ThreadLocalRandom.current().nextLong(-spread, spread + 1);
}
// ttlWithJitter(600, 0.1) -> [644, 623, 553, 645, 651]: expiries spread over 540–660 s
 
Cache<Long, Product> local = Caffeine.newBuilder()
        .expireAfterWrite(Duration.ofSeconds(2))   // hot key: Redis sees a few reads/s per pod
        .build();
Product p = local.get(id, productRepo::load);     // single-flight: 100 threads miss -> 1 load
// naive check-then-put, 100 threads: DB calls = 100
// cache.get(key, loader), 100 threads: DB calls = 1

Other languages: Go has golang.org/x/sync/singleflight; Node.js keeps a Map of in-flight Promises per key.

Bloom filters: size and limits

A Bloom filter answers "definitely not here" or "maybe here": no false negatives, false positives at a chosen rate.

For n items and error rate p: bits m = −n·ln p / (ln 2)², hash functions k = (m/n)·ln 2. 1 million ids at p = 1%: 1.14 MB, k = 7; the measured error rate was 1.01%.

Limits: you must load every id from the DB, add new ids with BF.ADD, and you can't delete items, so rebuild it periodically. Redis 8 ships BF.RESERVE/BF.ADD/BF.EXISTS; on the JVM there is Guava's BloomFilter.

4. Working with AI

Give the AI: a two-tier Caffeine + Redis setup, a warm-up job, a test counting DB calls when 100 threads miss together.

Check in AI-written code:

  • TTLs have jitter, not one constant for a million keys.
  • No reliance on @Cacheable(sync = true) to stop stampedes across pods.
  • Endpoints taking arbitrary ids validate them and cache nulls briefly or use a Bloom filter.
  • No DEL on big keys, no KEYS * in production.

5. Exercises

Exercise 1: Flash sale at 30,000 req/s

At 20:00, 50 products go on sale; expect 30,000 req/s on their detail pages. The DB handles at most 2,000 queries/s, and there are 40 pods. Design the cache so the DB survives.

Solution to Exercise 1
  • Preloaded allowlist: at 19:50 a job loads the 50 products into Redis without TTL and overwrites them every 5 s: no breakdown.
  • Hot keys: a Caffeine local cache with a 2 s TTL. 40 pods × 50 keys × 0.5 reads/s = 1,000 Redis reads per second instead of 30,000.
  • Stampede: cache.get(key, loader) so each pod loads each key once.
  • Penetration: ids outside the allowlist get 404 without touching the DB.
  • Bulkhead: at most 50 concurrent cache-miss queries to the DB.
  • Stock decrements don't rely on the cache: UPDATE ... WHERE stock > 0 or an atomic DECR.

Exercise 2: "Duplicate loads prevented"

The AI configures RedisCacheManager with disableCachingNullValues() and @Cacheable(value = "product", sync = true, unless = "#result == null"), described as "prevents stampedes and penetration". The service runs 30 pods, and a bot is scanning random ids. What's wrong?

Solution to Exercise 2
  • Stampede: sync = true with Redis doesn't lock per key; even where it does, it's per JVM, so 30 pods load 30 times. Put Caffeine get(key, loader) in front, plus a Redis mutex for the few truly hot keys.
  • Penetration: nulls aren't cached, so every bot id hits the DB every time. Validate the id format, cache nulls for 30 s, or use a Bloom filter of all existing ids.

Summary

  • Avalanche is many keys or the whole cluster; breakdown is one hot key; penetration is nonexistent keys.
  • TTLs always get jitter; an empty cache after a restart needs a warm-up.
  • Single-flight is always on; sync = true isn't enough across pods.
  • More nodes don't fix a hot key: use a local cache.
  • A cache-only Redis uses allkeys-lru/allkeys-lfu; delete big keys with UNLINK.

Read more: Cache-aside and invalidation.

Practice interview questions on this topic

All Caching & Redis questions →

Loading comments…