Stampedes and consistency
200 requests running the same query when a hot key expired, single-flight and rebuild locks, serving stale for a 2 ms p99, the delete-on-write race versioning closes, and hot keys.
A cache in steady state is easy. The failures happen at edges: the moment a popular entry expires and every request misses at once, the moment a write and a read overlap, the moment one key carries a third of all traffic. Each of those has a name, a measurable effect, and a fix that costs something.
The experiments here ran against Redis 7.4, with Java clients in a separate container and a simulated slow query standing in for the database.
The stampede
A home page is built from an expensive query — 300 ms — and cached for a minute. At the moment its entry expires, 200 requests arrive together. Every one of them misses the cache, and every one of them runs the query:
cache-aside, no protection database loads 200 p50 313 ms p99 328 msTwo hundred copies of the most expensive query in the system, at the same instant. In this experiment the simulated database took them in its stride. A real one does not: the expensive query gets slower under concurrency, requests time out, clients retry, and the cache never gets repopulated because every attempt to rebuild it is itself timing out. This is also called the thundering herd, and it is how a cache expiring can take a database down.
Its relatives have their own names:
- Cache avalanche — many keys expiring at the same moment, typically because they were written together with the same TTL, or because the cache itself restarted empty.
- Cache penetration — requests for keys that do not exist, which never populate the cache. The caching patterns lesson measures negative caching against it.
Defence one: only one rebuild
The fix is to make sure only one caller rebuilds the entry, while the rest wait for it or use something else.
Single-flight inside each instance — a lock per key in the JVM, so concurrent misses on one instance share one load. With four application instances:
single-flight per instance (4 instances) database loads 4 p50 282 ms p99 318 msFour loads instead of two hundred: one per instance, because each instance's lock only coordinates its own threads. For many systems that is enough, and it needs nothing but a local lock — or a loading cache such as Caffeine, which does this for you.
A rebuild lock in Redis — SET key:lock 1 NX PX 5000 — so that across all instances only the caller that gets the lock rebuilds, and the rest poll the cache until the value appears. Two runs:
rebuild lock in Redis (SET NX), wait database loads 1 p50 302 ms p99 323 ms
rebuild lock in Redis (SET NX), wait database loads 2 p50 299 ms p99 326 msOne load — and then, in the second run, two. The implementation allows exactly one way for that to happen, and it is worth understanding: a waiting request checks the cache just before the rebuilder stores the new value, finds it empty, and tries the lock just after the rebuilder releases it — so it gets the lock and rebuilds again. The fix is a second check of the cache after acquiring the lock, before loading. Double-checked locking, the same pattern as in concurrent Java code.
Notice the latency, though. With waiting, every request still took about 300 ms: they were not hitting the database, but they were waiting for the one request that was.
Defence two: serve stale while rebuilding
If a slightly old value is acceptable — and for a home page it almost always is — the waiting requests do not need to wait. Keep a longer-lived copy of the previous value; when the fresh entry is missing, one request takes the lock and rebuilds, and every other request is served the old copy immediately:
rebuild lock, serve stale while rebuilding database loads 1 p50 0 ms p99 2 msOne database load, and a p99 of 2 ms. A single request paid the 300 ms rebuild; 199 were served in a couple of milliseconds from the stale copy. HTTP has a name for the same idea — Cache-Control: stale-while-revalidate — and CDNs implement it.
Two related techniques avoid the moment of expiry altogether:
- Refresh ahead of expiry. A background job, or the first request after an entry is, say, 80% of the way through its TTL, rebuilds it before it expires. Hot entries never go missing.
- Probabilistic early expiry. Each read decides at random whether to rebuild early, with a probability that rises as the entry nears expiry and with how long the rebuild takes. Across many requests, one of them rebuilds a little before the deadline and the herd never forms — without any lock.
Consistency: the cache that stays wrong
The caching patterns lesson's update path — write the database, then delete the cache entry — looks correct, and it has a race. A reader misses the cache and reads the old row; a writer updates the row and deletes the cache entry; the reader, delayed for a moment, stores the old row it read. Nothing in any single step is wrong, and the cache now holds a value older than the database, until its TTL expires.
How often? An experiment that deliberately makes the reader and writer overlap, with random pauses of 0–3 ms on each side, 400 times per strategy, twice:
delete 153 of 400 races left a stale price in the cache (until its TTL expires)
write-through 139 of 400 races left a stale price in the cache (until its TTL expires)
versioned 0 of 400 races left a stale price in the cache (until its TTL expires)
delete 147 of 400 races left a stale price in the cache (until its TTL expires)
write-through 136 of 400 races left a stale price in the cache (until its TTL expires)
versioned 0 of 400 races left a stale price in the cache (until its TTL expires)The rates are high because the experiment forces every read to overlap a write; in production the overlap is rare per request and certain at scale. What matters is the comparison:
- Delete on write left a stale value in more than a third of overlapping races.
- Write-through — the writer stores the new value instead of deleting — was barely better. The delayed reader simply overwrites the writer's fresh value with its old one.
- Versioned writes left none. Each cached value carries the row's version, and every write to the cache — from the reader and the writer alike — goes through a small Lua script that refuses to replace a newer version with an older one:
local cur = redis.call('GET', KEYS[1])
if cur then
local v = tonumber(string.match(cur, '^(%d+):'))
if v >= tonumber(ARGV[1]) then return 0 end
end
redis.call('SET', KEYS[1], ARGV[1] .. ':' .. ARGV[2], 'EX', 3600)
return 1The script runs atomically inside Redis, so the check and the set cannot be separated by another client's write. The cost is a version column in the table and a script call instead of a plain SET.
Hot keys
Hashing spreads keys evenly across Redis shards. It does not spread traffic when one key gets far more requests than the rest — a trending product, a celebrity's profile, the home page. Redis can find them: with an LFU eviction policy, it keeps a frequency counter per key, and redis-cli --hotkeys scans for the highest. After the skewed workload from the caching patterns lesson:
hot key found with counter: 43 keyname: "product:0"
hot key found with counter: 39 keyname: "product:1"
hot key found with counter: 32 keyname: "product:2"
hot key found with counter: 25 keyname: "product:3"The counters are logarithmic and decay over time, so they rank keys rather than count requests. In a Redis Cluster, every one of those keys lives on one shard; if a hot key gets a large share of traffic, that shard's CPU and network saturate while the others idle, and adding shards does nothing for it.
The remedies are the same as for a hot database partition:
- A local cache in front for just the hottest keys, with a short TTL — the caching patterns lesson's two-level cache. Most requests never reach Redis.
- Replicas for reads, so one hot key's reads are served by several nodes.
- Key splitting — store copies under
product:0#1…product:0#8and pick one at random on read — at the cost of updating all the copies on write.
Under the hood: the XFetch formula, and why it decides per-read instead of per-key
"Defence two" above names probabilistic early expiry in one sentence: rebuild a little before the deadline, at random, so the herd never forms. The mechanism behind that is worth naming precisely, because "at random" undersells it — the specific formula, often called XFetch (from Vattani, Chierichetti and Lowenstein's paper on optimal probabilistic cache stampede prevention), makes the probability of an early rebuild depend on both how close the entry is to expiring and how expensive rebuilding it is, which a plain "roll a die on every read" approach does not.
The check, run on every read of a cached entry, using the entry's own recorded delta (how long the last rebuild took) and expiry time:
recompute early if: now − (delta × beta × ln(random())) ≥ expiryrandom() draws a fresh uniform value in (0, 1) on every read; ln of a value in that range is always negative, so −delta × beta × ln(random()) is always positive — the check shifts "now" forward by a random amount before comparing it to the expiry time. Two things make this the right shape rather than an arbitrary one:
- The shift grows as the read happens closer to expiry, in effect. Because the comparison is against a fixed expiry time, the closer
nowalready is toexpiry, the smaller a random shift needs to be to cross it — so reads near the deadline are far more likely to trigger a recompute than reads early in the entry's life, without the formula needing to know explicitly how much time is left. deltascales the effect by rebuild cost. An entry that takes 300 ms to rebuild (this lesson's home-page example) gets a larger typical shift than one that takes 5 ms, so a slow rebuild is nudged to start earlier — which is exactly what avoids the herd: it gives a slow rebuild more of a head start before the crowd would otherwise arrive at the hard expiry.betais a tuning knob, typically left at 1; raising it makes every entry recompute earlier and more often (fewer stampedes, more redundant work), lowering it pushes recomputes closer to the true deadline.
Because every read makes its own independent random draw, no coordination is needed between requests or instances — unlike the Redis rebuild lock, nothing is shared, waited on, or can deadlock. The trade is that it is probabilistic: it makes a stampede unlikely, not impossible, in a way a lock (done correctly) makes impossible by construction.
double deltaMs = 50; // last rebuild took 50 ms
double beta = 1.0;
long expiry = 1_000_000; // epoch ms, arbitrary timeline
long farFromExpiry = 999_000; // 1000 ms before expiry
long closeToExpiry = 999_990; // 10 ms before expiry
double randomDraw = 0.5; // fixed "random()" draw, so the exercise is deterministic
double shiftedFar = farFromExpiry - deltaMs * beta * Math.log(randomDraw);
double shiftedClose = closeToExpiry - deltaMs * beta * Math.log(randomDraw);
System.out.println("far from expiry, recompute early? " + (shiftedFar >= expiry));
System.out.println("close to expiry, recompute early? " + (shiftedClose >= expiry));The same random draw (0.5, a middling value — neither an unusually early nor unusually late trigger) produces a different answer purely because of how close each read is to the expiry time. A real system never fixes the draw, so the exact moment any single read decides to rebuild is genuinely random — only the distribution of when a rebuild happens, clustering more tightly as expiry approaches, is what the formula controls.
Try it yourself
Predict the fence, then reason about beta
Run the prediction above, then consider: if beta were doubled from 1.0 to
2.0 in that same snippet, what would happen to the two answers, and why does
that match what beta is described as tuning above?
Doubling beta doubles the shift, which can only push more reads over the line, never fewer
beta is a pure multiplier on the shift amount (delta × beta × ln(random()),
in absolute value), so doubling it doubles how far "now" is pushed forward
before comparing to expiry, for every read, everywhere in an entry's
lifetime. For the close-to-expiry read, which already crossed the line at
beta = 1.0, doubling the shift keeps it well past expiry — still true.
For the far-from-expiry read, the shift at beta = 1.0 was about 34.7 ms,
nowhere near closing a 1,000 ms gap; doubling it to about 69.3 ms is still
nowhere near closing that gap, so it stays false here too — but note the
direction: a larger beta can only ever make a read more likely to
recompute early, never less, because the shift only ever adds a positive
amount. That is the operational meaning of "raising beta makes entries
recompute earlier and more often": it is a dial with one direction of
effect, and tuning it is a trade between rebuilding too early (wasted work,
because the old value was still fine) and not spreading rebuilds out enough
(closer to a stampede again).
Misconceptions
- "Adding jitter to TTLs and using probabilistic early expiration are basically the same idea." Jitter randomizes the expiry time itself, once, at write time — it spreads out when a batch of entries written together will expire, so they do not all miss at once. XFetch does not touch the expiry time; it makes a fresh probabilistic decision on every read, and — unlike jitter — that decision also factors in how expensive the specific entry is to rebuild (
delta). They are complementary, not redundant: jitter prevents many keys from colliding on one expiry moment; XFetch prevents many requests for one key from colliding on that key's rebuild. - "Probabilistic early expiration adds latency, because now every read might trigger a rebuild." Only the (rare, near-expiry) reads that draw a value crossing the threshold pay the rebuild cost; every other read gets the cached value immediately, same as always. That is a real difference from the Redis rebuild lock's "wait" mode, where every concurrent request pays the ~300 ms wait regardless of which one is actually rebuilding.
Sources
- A. Vattani, F. Chierichetti, K. Lowenstein, "Optimal Probabilistic Cache Stampede Prevention" (VLDB 2015) — the XFetch formula and its derivation.
- MDN Web Docs / IETF RFC 5861 —
stale-while-revalidate, the HTTP analogue of serving a stale copy while one request rebuilds.