Cache stampedes: when one expiring key takes down the database
A cache with a 99.8% hit rate can still take your database down: when a hot key expires, every request misses at once. The known fixes, explained with Java code: TTL jitter, single-flight loading, stale-while-revalidate, probabilistic early refresh and warming.
A cache with a 99.8% hit rate can still take your database down.
The usual pattern is cache-aside: check the cache, and on a miss, load from the database and store the result with a TTL. It works beautifully until your most popular key expires. In the next few milliseconds, every request for that key misses, and every one of them runs the same database query. A thousand identical queries arrive at once for data that was in memory a moment ago.
That’s a cache stampede, also called dogpiling or a thundering herd. It has an unpleasant property: the busier the key, the bigger the stampede, so it happens exactly when you have the most traffic. It’s a well-understood problem with well-understood fixes, and they combine nicely.


Three ways to start a stampede
- A hot key expires. The classic case: one popular product page, one homepage query, one config value.
- Many keys expire together. Everything cached at deploy time with
TTL = 3600expires at the same moment an hour later. No single key is hot, but the database sees the entire working set at once. - The cache starts empty. A cache node restarts, someone flushes it, or you shift traffic to a new region with a cold cache. Now every key is missing.
The fixes below address these in different combinations.
Fix 1: add jitter to TTLs
The cheapest fix, for case 2. Instead of a fixed TTL, add randomness:
Duration ttl = Duration.ofMinutes(60).plusSeconds(ThreadLocalRandom.current().nextInt(0, 600));
redis.opsForValue().set(key, value, ttl);
Keys cached together now expire over a ten-minute window instead of in the same second. It does nothing for a single hot key, but it removes synchronised expiry entirely, and it costs one line.
Fix 2: single-flight loading
When a key is missing, only one caller loads it; everyone else waits for that result instead of starting their own load.
Within one service instance, a good cache library does this for you. Caffeine’s get(key, loader) runs the loader once per key, and concurrent callers for the same key block on that one computation:
LoadingCache<String, Product> products = Caffeine.newBuilder()
.maximumSize(100_000)
.expireAfterWrite(Duration.ofMinutes(10))
.build(id -> productRepository.load(id)); // one load per key at a time, per instance
Across instances, you need a shared lock, typically in Redis. The caller that wins the lock loads and writes the value; the others wait briefly and read the cache again:
Boolean won = redis.opsForValue().setIfAbsent("lock:" + key, instanceId, Duration.ofSeconds(5));
if (Boolean.TRUE.equals(won)) {
Product fresh = productRepository.load(id);
redis.opsForValue().set(key, fresh, ttlWithJitter());
return fresh;
}
return waitForValue(key, Duration.ofMillis(200)) // poll briefly for the winner's write
.orElseGet(() -> productRepository.load(id)); // last resort if the winner died
The lock needs a timeout, because the winner can crash. Per-instance single-flight alone already cuts a stampede from “one query per request” to “one query per instance”, which is often enough.
Fix 3: serve stale while one caller refreshes
Waiting is better than stampeding, but it still adds latency to every request during the refresh. Usually there’s a better answer: the old value is fine for a few more seconds.
Store two times with each value: a soft expiry when it should be refreshed, and a hard expiry when it must not be served any more. Between the two, return the stale value immediately, and let exactly one caller (the lock winner) refresh it in the background.
Caffeine has this built in as refreshAfterWrite:
LoadingCache<String, Product> products = Caffeine.newBuilder()
.refreshAfterWrite(Duration.ofMinutes(5)) // soft: after 5 min, the next read triggers a background reload
.expireAfterWrite(Duration.ofMinutes(30)) // hard: never serve anything older than 30 min
.build(id -> productRepository.load(id));
Callers never wait on a refresh, and the database sees one query per key per refresh interval, regardless of traffic. HTTP has the same idea as the stale-while-revalidate directive on Cache-Control, which lets CDNs do it for you.
The question to ask the product owner: how stale is acceptable? For a product description, minutes. For a price during a sale, seconds. For an account balance, don’t cache it this way at all.
Fix 4: refresh early, probabilistically
Single-flight needs a lock. There’s an elegant lock-free alternative, published as “Optimal Probabilistic Cache Stampede Prevention” (Vattani, Chierichetti and Lowenstein, 2015) and often called XFetch: each reader, before the value expires, decides at random whether to refresh it early, with a probability that rises sharply as expiry approaches.
// delta: how long the last recomputation took; beta > 1 refreshes earlier (1.0 is a good default)
boolean shouldRefreshEarly(long expiresAtMillis, long deltaMillis, double beta) {
double jitter = -deltaMillis * beta * Math.log(ThreadLocalRandom.current().nextDouble());
return System.currentTimeMillis() + jitter >= expiresAtMillis;
}
With many readers, one of them almost always refreshes shortly before expiry, so the key effectively never expires under load, and no coordination is needed. Expensive values (large delta) start refreshing earlier, which is exactly what you want.
Fix 5: warm before you shift traffic
For case 3, the cold cache, none of the above is enough: every key is missing at once. So don’t let it happen to live traffic:
- Pre-load the hot set (the top N keys from yesterday’s access logs) before a new cache node or region takes traffic.
- Shift traffic gradually, so the cache fills while load is still small.
- Protect the database anyway: a limit on concurrent database queries per instance (a bulkhead) turns an overload into slower responses instead of a dead database. Some requests will wait; none will take the database down.
Which ones you need
| Situation | Fix |
|---|---|
| Many keys cached at the same time | TTL jitter |
| A few very hot keys | Single-flight, plus stale-while-revalidate |
| You can’t hold locks, or don’t want to | Probabilistic early refresh |
| Data can’t be stale at all | Single-flight with a short wait; or don’t cache it |
| Cache restarts, flushes, new regions | Warming, gradual traffic shift, database bulkhead |
In practice, most systems want jitter everywhere, per-instance single-flight by default, and stale-while-revalidate for the hottest keys. That combination handles the large majority of stampedes with very little code.
Takeaways
- A high hit rate doesn’t protect you when a hot key expires; the misses all arrive at once.
- Jitter TTLs so keys don’t expire together.
- Use single-flight loading, so one caller loads and the rest wait or share its result.
- Serve stale while refreshing wherever slightly old data is acceptable, and agree how old is acceptable.
- Warm caches before shifting traffic, and put a concurrency limit in front of the database as the last line of defence.