Video in progress
When a popular key's cache entry expired, thousands of requests suddenly hit the database. What is this called, and how do you protect against it?
This is a cache stampede (thundering herd): the moment the key dies, all parallel requests get a miss and go to the database at the same time. The protection is to let one request reload the value while the others wait (a lock or request coalescing), add jitter to the TTL, and refresh in the background before expiry.
📖 Answer
Imagine the "Top 100 products" on the home page is computed with a heavy query in 2 seconds and read 5000 times a second. The TTL expires — within 2 seconds, 10,000 requests send the same heavy SQL to the database. The database chokes, the queries get even slower, and none of them manages to write the result to the cache.
Ways to protect:
A single loader. Within one instance, Caffeine does this itself: for parallel get calls on the same key, the loader runs only once and the others wait for the result.
LoadingCache<String, List<Product>> top = Caffeine.newBuilder()
.refreshAfterWrite(Duration.ofMinutes(4)) // refreshes in the background
.expireAfterWrite(Duration.ofMinutes(5))
.build(key -> productRepository.findTop100());
With several instances, one instance takes a short lock in Redis (SET key NX PX 5000) and recomputes, while the others return the old value or wait a bit.
Early refresh. Like refreshAfterWrite: the key is refreshed in the background before it dies, so the user always gets a ready value.
Jitter. A random addition to the TTL of many keys — they don't all die at the same moment.
Such keys are usually few, so identify them in advance and give them special attention.
Sign up to mark studied questions and save your progress.