Video in progress
When a cache entry expires, hundreds of threads recompute the same expensive value at once. How do you solve this inside the JVM?
This is a cache stampede: for one key only one thread should compute, and the others should wait for its result. I do it with request coalescing through ConcurrentHashMap<K, CompletableFuture<V>>, Caffeine's refreshAfterWrite, and adding jitter to the expiry.
📖 Answer
The simple "check, compute if missing, put" code is open to a stampede:
V v = cache.get(key);
if (v == null) {
v = loadFromDb(key); // 300 threads are here at the same time
cache.put(key, v);
}
The result: 300 identical heavy queries hit the DB in one instant, latency spikes, and sometimes a cascading failure.
Request coalescing: we cache the future, not the value:
private final ConcurrentHashMap<String, CompletableFuture<Report>> inFlight = new ConcurrentHashMap<>();
CompletableFuture<Report> get(String key) {
return inFlight.computeIfAbsent(key, k ->
CompletableFuture.supplyAsync(() -> loadReport(k), loaderPool)
.whenComplete((r, ex) -> inFlight.remove(k)));
}
The first thread creates the future, and the others get that same future. The heavy work runs in a separate pool, not inside computeIfAbsent, otherwise we'd block the CHM bin for a long time. One subtle point: if the future finishes very fast (for example, immediately with an error), the whenComplete callback runs inside computeIfAbsent itself, before the mapping has been put in place. The result is either IllegalStateException: Recursive update, or remove finds nothing and the finished future stays in the map forever. So in practice I rely on a ready-made library.
Caffeine gives you this out of the box:
AsyncLoadingCache<String, Report> cache = Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofMinutes(10))
.refreshAfterWrite(Duration.ofMinutes(8)) // refreshes in the background before expiry
.buildAsync(this::loadReport);
With refreshAfterWrite the user gets the old value, and the refresh runs in a single background task, so there's no stampede at all.
Extra measures:
- jitter: a random ±10% on the expiry, so millions of keys don't expire at the same moment;
- caching the error for a short time, so that when the DB is down every request doesn't hammer it again;
- with many pods, coalescing inside the JVM only works within one pod. 50 pods means 50 parallel loads. If needed, add a short lock in Redis or a shared cache layer.
Sign up to mark studied questions and save your progress.