Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

What is a cache stampede (thundering herd) and what does the probabilistic early expiration technique do to prevent it?

Try it yourself

Cache-aside: one read, three cache states

See what a cache hit saves, what a miss costs, and why a write deletes the cached entry instead of updating it.

Read this example as text

When the entry is in the cache (a hit)

  1. A request arrives. A caller asks the service for product 42. The cache already holds it.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Hit: the value comes back. The entry is there and still fresh, so the cache answers at once. The database is never touched.

1 cache call, 0 database reads.

When it was never cached (a miss)

  1. A request arrives. A caller asks the service for product 42. Nobody has asked for it before, so the cache holds nothing.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. The key was never stored. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When its time to live has run out

  1. A request arrives. A caller asks the service for product 42. The cache held it once, but its time to live ran out 12 seconds ago.
  2. Ask the cache first. The service always asks the cache before the database. It sends GET product:42.
  3. Miss: nothing comes back. An expired key is the same as a missing one: Redis no longer returns it, and removes it. The cache answers nil, and the service must find the value itself.
  4. Read the database. The service runs SELECT ... FROM products WHERE id = 42. This is the slow, authoritative read the cache exists to avoid.
  5. The row comes back. The database returns the row. The service now has the value, but the cache is still empty.
  6. Store it for next time. Before answering, the service writes the value into the cache with a time to live: SET product:42 ... EX 300. The next read inside 300 seconds will be a hit.
  7. Answer the caller. The caller gets the value. It cost one database read, which a hit would have saved.

2 cache calls, 1 database read.

When the price changes afterwards

  1. The price changes. Later, someone updates the price to 25. The service writes the database first: UPDATE products SET price = 25 WHERE id = 42.
  2. Delete the cached entry. Then it deletes the key: DEL product:42. It does not write 25 into the cache. Deleting is simpler and safer: the next read misses and loads whatever the database holds then.
  3. The next read will miss. The cache is empty for this key again, so the next request repeats the miss path and stores 25.

3 cache calls, 1 database read, 1 database write.

What this example leaves out
  • One request at a time. Two requests missing at the same moment (a stampede) are not shown.
  • The write deletes the key. Some systems update the cache instead, which this example does not model.
  • The numbers are counts of round trips, not measured times.

A cache stampede, also called a thundering herd, happens when a popular entry expires or is evicted and many concurrent requests miss at the same moment and all recompute it, overloading the database or service behind the cache. Probabilistic early expiration lets each reader decide, with a probability that rises as expiry approaches, to recompute the value a little before it expires. Under load, one request usually refreshes early, so the entry is replaced before it ever expires and the herd never forms. Other defences are per-key locking or request coalescing, stale-while-revalidate and TTL jitter, and all of them matter most for expensive values with high read rates.

Why this question is asked

Caches are usually explained in terms of hits and misses, as if each miss were an isolated event. Under real load, misses are not isolated: when a hot key expires, every request that arrives before the value is rebuilt misses together. If the value takes two seconds to compute and the key is read 1,000 times a second, that is up to 2,000 concurrent recomputations of the same thing. Interviewers ask about stampedes to see whether we understand caching under concurrency, and probabilistic early expiration is an elegant technique that shows whether we can reason about timing. In this answer, we will see how a stampede forms, walk through the probabilistic technique with its formula and code, look at the other defences, and decide when the problem is worth solving.

1How a Stampede Forms

Picture a home page summary cached with a 60 second TTL. It is read 1,000 times per second, and computing it takes a two second database query. While the entry is present, the database sees nothing. At the moment it expires, the next request misses and starts the query. But for the two seconds the query runs, the entry is still missing, so every other request also misses and starts its own query.

Step throughOne expiry, many identical queries
RequestsCacheDatabase
get(home): entry expired
miss
query 1 (takes 2 s)
get(home), 1 ms later
miss: still not refilled
query 2
queries 3 to 2,000 during the next 2 s
database saturated; each query now slower

8 messages in order. Play them, or step through them one at a time.

The longer the recomputation takes, the bigger the herd, and the herd makes each recomputation slower.

Notice the feedback loop. The concurrent queries slow the database, which makes each query take longer, which keeps the entry missing longer, which lets more requests join. A key that was a performance optimisation becomes the cause of an outage.

2The Idea Behind Probabilistic Early Expiration

The stampede happens because everyone agrees on the exact moment of expiry. Probabilistic early expiration removes that moment. Each reader that gets a hit asks itself: should I recompute now, a little early? The answer is random, and the probability is tiny when expiry is far away and rises sharply as it approaches. With 1,000 readers per second, one of them will almost certainly say yes a short while before expiry, recompute, and put a fresh value with a new expiry. Everyone else keeps getting hits. The entry is renewed before it ever disappears.

The well-known formulation, sometimes called XFetch, stores two extra things with each value: delta, how long the last recomputation took, and the expiry time. A reader recomputes early when now - delta * beta * ln(random) >= expiry, where random is uniform between 0 and 1 and beta is a tuning factor, 1 by default. Because ln(random) is negative, the term -delta * beta * ln(random) is a random positive head start, usually around delta but occasionally much larger. Expensive values, with a large delta, start refreshing earlier, which is exactly what we want.

3Implementing It Around a Cache

Spring's @Cacheable has no built-in support, so we wrap the value ourselves and use the Cache API directly.

Java
record Timed(Object value, long deltaMillis, long expiresAtMillis) {}
@SuppressWarnings("unchecked")
<V> V get(String key, Supplier<V> loader, Duration ttl) {
Timed t = cache.get(key, Timed.class);
long now = System.currentTimeMillis();
if (t != null) {
double headStart = -t.deltaMillis() * BETA * Math.log(ThreadLocalRandom.current().nextDouble());
if (now + headStart < t.expiresAtMillis()) return (V) t.value(); // a normal hit
}
V v = loader.get(); // missing, or chosen to refresh early
long delta = System.currentTimeMillis() - now;
cache.put(key, new Timed(v, delta, now + delta + ttl.toMillis()));
return v;
}
// ttl 60 s, delta 2 s, beta 1, 1,000 reads per second:
// 50 s before expiry: chance per read about e^-25, effectively 0
// 15 s before expiry: chance per read about 1 in 2,000, so at 1,000 reads per second someone refreshes now
// result: the entry is renewed roughly 15 s early, about one query every 45 s, and it never expires under load

Notice two practical details. The physical TTL in the cache store must be longer than the logical expiresAt, otherwise the provider deletes the entry before readers get a chance to refresh it early; we typically set the store TTL to the logical TTL plus a margin. And the early refresh can still happen on two readers at once, so it reduces the herd to one or a few recomputations rather than strictly one, which is enough in practice.

4Other Defences Against Stampedes

Per-key locking or request coalescing makes concurrent misses for the same key wait for a single computation. Within one JVM, Caffeine's get(key, loader) and Spring's @Cacheable(sync = true) do this; across instances it needs a short distributed lock or lease. Stale-while-revalidate keeps serving the old value after its logical expiry while one caller recomputes in the background, which removes the latency spike entirely if slightly stale data is acceptable; Caffeine's refreshAfterWrite is this idea built in. TTL jitter adds a random amount to each TTL, for example 10 minutes plus or minus 10 percent, so that many keys written at the same time, such as after a cache warm-up or a deployment, do not all expire in the same second.

Stampede defences compared
TechniqueWhat it preventsCost
Probabilistic early expirationthe expiry moment itselfextra fields per value; occasional early recompute
Per-key lock / coalescingduplicate concurrent loadswaiting callers; distributed lock is complex
Stale-while-revalidateboth the herd and the latency spikeserves stale data for a short time
TTL jittermany keys expiring togethernone worth mentioning

5When It Is Worth the Effort

Stampedes only hurt when two conditions meet: the value is expensive to compute, and it is read at a high rate. A user profile read twice a minute can expire however it likes. A home page aggregation read thousands of times per second that takes seconds to build is exactly where a stampede causes outages. So we apply these techniques selectively, to the handful of hot, expensive keys, and use plain TTLs everywhere else.

6Follow-up questions

Is @Cacheable(sync = true) enough to prevent stampedes?

Within one JVM it collapses concurrent misses for a key into one computation, which is often enough for a single instance. With many instances, each one still computes once, so 30 instances can still produce 30 simultaneous expensive queries. It also does nothing about the latency spike, because waiting callers still wait for the full computation.

Why is beta useful?

beta scales the head start. Values above 1 make early refreshes happen sooner and more reliably, at the cost of recomputing a bit more often; values below 1 refresh closer to expiry. In practice beta = 1 works well, and we only tune it when measurements show the entry occasionally expiring under load.

7Conclusion

In this answer, we saw that a cache stampede happens when a popular, expensive entry expires and many concurrent requests recompute it at once, and that the extra load creates a feedback loop that can take down the source. Probabilistic early expiration removes the shared expiry moment by letting each reader recompute early with a probability that rises as expiry approaches, scaled by how long recomputation takes, so one request usually refreshes the entry before it expires. We also compared per-key locking and coalescing, stale-while-revalidate and TTL jitter, and noted that these defences matter mainly for expensive values with high read rates.

What to say in the interviewAbout 90 seconds aloud

Open with

A cache stampede, or thundering herd, is what happens when a hot entry expires or is evicted and many requests miss at the same moment. They all recompute the value, and if that is a slow query, the database gets hundreds of identical queries, which makes each one slower, which keeps the entry missing longer.

Then, if they want more

Probabilistic early expiration attacks the cause, which is that everyone sees the same expiry moment. Each value is stored with how long it took to compute and its expiry time.

On each hit, the reader computes a random head start, minus delta times beta times the log of a random number, and if now plus that head start passes the expiry, it recomputes early and stores a fresh value.

Far from expiry the probability is essentially zero; close to expiry it rises sharply, and since there are many readers, one of them refreshes a bit early and the entry never actually expires under load. Expensive values get a bigger head start automatically. The store's physical TTL has to be a bit longer than the logical one.

Other techniques are per-key locking or request coalescing, like sync = true within one JVM, stale-while-revalidate, which serves the old value while one caller recomputes, and TTL jitter so keys do not expire together. I would apply them to expensive keys with high read rates, not everywhere.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "What is a cache stampede (thundering herd) and what does the probabilistic early...": https://scrivio-interview-library.netlify.app/databases/caching/a5af8ce1ac/