Cache Stampedes and Hot Keys: Surviving Expiry Storms, Cold Starts and Celebrity Traffic
At 20:00:00 a homepage widget key expires. It is read 40,000 times a second, and rebuilding it takes a 120 ms aggregation query. In those 120 ms, 4,800 requests miss the cache and every one of them runs the same query. The database, sized for 300 queries a second of misses, suddenly has 4,800 identical ones in flight. Each query slows down because of the others, so the rebuild now takes 2 seconds, so 80,000 requests pile in behind it. The database tips over, and because the key never gets rebuilt, it stays tipped over.
Twenty minutes later, after a restart, a different problem: a celebrity posts, and one key, post:98123, gets 600,000 reads a second. The cache cluster has 30 shards with plenty of headroom in total, but every one of those reads hashes to the same shard. That one node pins its CPU and saturates its network card, and every other key on that shard times out with it.
These are the two classic ways a healthy cache takes a system down: many requests rebuilding the same key at once (a stampede), and one key receiving more traffic than one node can serve (a hot key).
What they are
A cache stampede (also called a thundering herd or dogpile) happens when a popular key is missing and many concurrent requests all decide to recompute it. It is triggered by a TTL expiring, an explicit invalidation, an eviction, or a cold cache after a deploy, failover or flush.
A hot key is a single key whose request rate exceeds what the node holding it can serve. Sharding by key, explained in consistent hashing, spreads different keys across nodes, but it can never spread one key. A related problem is the big key: a single value so large (a 50 MB hash, a list with 10 million elements) that reading, writing or deleting it blocks a node.
Both turn a cache from a load absorber into a load amplifier.
How a stampede amplifies itself
The arithmetic is simple. Misses during one rebuild equal request rate times rebuild time. The dangerous part is the feedback: concurrent rebuilds slow the database, which lengthens the rebuild, which lets more misses through.
Use the widget to see why. Set the utilisation to 50%, then push it to 90% and 95%. Queueing delay grows without bound as a resource approaches saturation, which is the reason a 10x spike of identical queries does not make things 10x slower but stops them entirely. The theory is in latency vs throughput.
flowchart LR E["Hot key expires"] --> M["N requests miss<br/>N = rate x rebuild time"] M --> Q["N identical DB queries"] Q --> S["DB saturates,<br/>each query slower"] S --> L["Rebuild takes longer"] L --> M style E fill:#FAEEDA,stroke:#854F0B,color:#633806 style M fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style Q fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style S fill:#FCEBEB,stroke:#A32D2D,color:#791F1F style L fill:#FAEEDA,stroke:#854F0B,color:#633806
Defences against stampedes
There are five tools. Real systems use two or three together.
1. Request coalescing (singleflight)
Inside one process, the first request for a missing key starts the rebuild and every concurrent request for the same key waits on that one result. Go ships this as golang.org/x/sync/singleflight; Caffeine’s LoadingCache does it automatically for Java; in other languages a map of in-flight futures keyed by cache key does the job.
var group singleflight.Group
func GetFeed(ctx context.Context, key string) ([]byte, error) {
if v, ok := cache.Get(key); ok {
return v, nil
}
v, err, _ := group.Do(key, func() (any, error) {
val, err := db.BuildFeed(ctx, key)
if err == nil {
cache.Set(key, val, jitter(5*time.Minute))
}
return val, err
})
if err != nil {
return nil, err
}
return v.([]byte), nil
}
Coalescing reduces database load from “every request” to “one per process”. With 200 app servers that is still 200 concurrent rebuilds, which is usually fine and sometimes not.
2. A distributed lock plus stale-while-revalidate
To get down to one rebuild across the whole fleet, take a short-lived lock in the cache: SET lock:feed:123 <token> NX PX 5000. The winner rebuilds. The losers should not spin on the lock, which just moves the stampede to the cache. Instead, they serve the stale value.
That requires keeping the stale value around. Store two times in the entry: a soft expiry after which the value should be refreshed, and a hard TTL (say, 10x longer) after which it is really gone. Readers past the soft expiry try for the lock; whoever wins refreshes; everyone else returns the stale copy immediately. This is the same idea as the HTTP stale-while-revalidate directive covered in CDN and edge caching.
The lock is advisory and expires on its own. If the rebuilder dies, the lock times out and someone else tries. You do not need fencing here because a duplicate rebuild is harmless; when correctness depends on a lock, read leader election, leases and locks.
3. Probabilistic early expiration (XFetch)
Instead of everyone noticing expiry at the same instant, let each request independently decide to refresh slightly early, with a probability that rises as expiry approaches. The algorithm from Vattani, Chierichetti and Lowenstein (VLDB 2015, Optimal Probabilistic Cache Stampede Prevention) stores, with each value, the time it took to compute (delta) and its expiry time. On every read:
recompute if now - delta * beta * ln(rand()) >= expiry
rand() is uniform in (0, 1], so ln(rand()) is zero or negative and the middle term pushes “now” forward by a random amount. Expensive values (large delta) start refreshing earlier. beta defaults to 1; above 1 favours earlier refreshes. The probability that a single read at time g seconds before expiry triggers a refresh is exp(-g / (delta * beta)), which is tiny far from expiry and approaches 1 at expiry.
XFetch needs no locks and no coordination. Its weakness is very high request rates, where several requests can trigger in the same few milliseconds, so in practice it is combined with singleflight.
4. TTL jitter
When many keys are written at the same moment (a warm-up job, a nightly import), they expire at the same moment. Adding a random 10 to 20% to each TTL turns one cliff into a slope. The same principle as adding jitter to retries, covered in timeouts, retries and backoff.
5. Never let it expire: background refresh
For a small set of keys that are known to be hot (homepage, top-100 products, config), do not rely on expiry at all. A background job recomputes them on a schedule and overwrites the value, and readers never miss. The risk is refreshing keys nobody reads, which is why this is reserved for a short list.
flowchart TB
R["Read key"] --> H{"Fresh?"}
H -->|"yes"| OK["Return value"]
H -->|"stale but present"| L{"Got rebuild lock?"}
L -->|"yes"| RB["Rebuild in background<br/>and write new value"]
L -->|"no"| ST["Return stale value"]
RB --> ST
H -->|"absent"| SF["Singleflight rebuild<br/>other callers wait"]
SF --> OK
style OK fill:#E1F5EE,stroke:#0F6E56,color:#085041
style ST fill:#E1F5EE,stroke:#0F6E56,color:#085041
style RB fill:#EEEDFE,stroke:#534AB7,color:#3C3489
style SF fill:#FAEEDA,stroke:#854F0B,color:#633806
Cold starts and cache warming
A stampede on one key is bad; a stampede on every key is worse. It happens when a cache cluster is replaced, flushed, or fails over to an empty replica, and when a new region comes up with no data.
Practical defences:
- Warm before you shift traffic. Replay the top N keys from access logs, or copy hot keys from the old cluster, before routing reads to the new one.
- Shift traffic gradually. Move 5%, then 25%, then 100% so misses arrive at a rate the database can absorb.
- Protect the database explicitly. A concurrency limit on the miss path (say, at most 200 in-flight rebuild queries per service) turns a stampede into queued or shed requests instead of a dead database. Shedding is covered in load shedding and backpressure.
- Do not restart all cache nodes together. Rolling restarts with replicas promoted first avoid a global cold start.
Hot keys
Detecting them
You cannot fix a hot key you cannot see. Options, roughly in order of effort:
- Per-shard metrics. One shard with 5x the CPU or network of its peers almost always means a hot key or a big key.
- Server-side tools. The redis-cli hotkeys scan (shown below) samples the keyspace and needs an LFU eviction policy to have counters to read. Redis 8.6 added a
HOTKEYScommand that tracks the top keys by CPU time and network bytes over a window.
redis-cli --hotkeys # needs maxmemory-policy allkeys-lfu or volatile-lfu
redis-cli --bigkeys # largest key per type
redis-cli --memkeys # largest keys by memory usage
- Client-side sampling. Count key frequencies in the client with a Count-Min sketch or a top-K structure, explained in Bloom filters, HyperLogLog and friends, and report the top keys every few seconds. This works with any cache server and also catches keys that are hot only from one service.
Mitigating them
Local L1 cache with a short TTL. The most effective single fix. If 300 app servers each keep post:98123 in memory for 1 second, the cache shard sees at most 300 reads a second for that key, no matter whether the key gets 6,000 or 6 million reads. The cost is up to 1 second of staleness, which is fine for a like count and not fine for a bank balance.
Key replication with suffixes. Store N copies, post:98123#0 through post:98123#15, which hash to different shards. Readers pick a random suffix; writers update or delete all N. Load per shard falls by N, and writes cost N times more, so this only suits read-heavy keys.
Read from replicas. Redis and Valkey Cluster replicas can serve reads (READONLY on the connection), and managed services expose reader endpoints. Three replicas give up to 4x read capacity for that shard, with replication lag as the price.
Shrink the value. A hot key with a 200 KB value costs 1,000 times more network than one with 200 bytes. Store the hot fields separately from the cold blob.
Big keys
A big key is dangerous even when it is not hot. Redis and Valkey execute commands on one main thread, so HGETALL on a hash with 2 million fields or DEL on a 500 MB list blocks every other client on that node for the duration. Find them with the bigkeys and memkeys scans shown above. Split them into buckets (cart:123:0 to cart:123:63), read with HSCAN instead of HGETALL, and delete with UNLINK, which frees memory in a background thread.
Worked example: the celebrity post
Where it breaks
- Locks that spin. If losers poll the lock every 10 ms, a stampede on the database becomes a stampede on the cache shard holding the lock. Serve stale or wait on a local future instead.
- No stale value to serve. Stale-while-revalidate only works if the entry outlives its soft expiry. Using one TTL for both means there is nothing to serve.
- Caching errors. If the rebuild fails and you cache the error with the normal TTL, you serve errors for minutes. Cache failures with a very short TTL, or not at all, and keep serving the last good value.
- Negative caching gaps. Requests for keys that do not exist bypass every technique above because there is nothing to coalesce on in the cache. Cache “not found” markers for a short time, and rate limit unknown keys.
- Replicated hot keys and writes. Key suffixing makes every write N writes and every invalidation N deletes. Forget one and readers see inconsistent copies depending on the suffix they pick.
- L1 caches and invalidation. A 1-second L1 is safe; a 10-minute L1 on 300 servers is 300 copies you cannot invalidate quickly. Keep L1 TTLs short or use server-assisted invalidation (Redis
CLIENT TRACKING), described in cache patterns.
Real-world systems
- Facebook memcache leases. The 2013 NSDI paper Scaling Memcache at Facebook describes leases that both block stale sets and limit how often a lease is handed out for a key (once every 10 seconds per key in their description), so other readers wait briefly or take a slightly stale value instead of stampeding.
- Go
singleflight. The standard coalescing primitive in Go services, used widely in caches and DNS resolvers. - Caffeine. Its loading cache coalesces concurrent loads for the same key and supports
refreshAfterWrite, which serves the old value while one thread refreshes it. - Varnish, Fastly, Cloudflare, CloudFront. HTTP caches collapse concurrent misses for the same URL into one origin request, the CDN version of singleflight.
- Redis 8.6
HOTKEYSand the redis-cli hotkeys scan. Built-in hot key discovery.
How to apply it
A default stack for a read-heavy service:
- Singleflight on every miss path. It costs nothing and removes the worst case.
- TTL jitter of 10 to 20% on every key.
- Soft and hard expiry with stale-while-revalidate for keys that are expensive to rebuild.
- A short L1 cache (1 to 5 s) for keys known to be hot, or for all keys if the data tolerates it.
- Client-side top-K sampling that alerts when one key exceeds a set share of a shard’s traffic.
- A concurrency cap on the database miss path as the last line of defence.
- Cache warming and gradual traffic shifts for every cluster replacement.
| Problem | First fix | If that is not enough |
|---|---|---|
| One key expires under load | Singleflight | Lock plus stale-while-revalidate, or XFetch |
| Many keys expire together | TTL jitter | Background refresh for the top keys |
| Cold cluster | Warm before shifting traffic | Gradual shift plus miss-path concurrency cap |
| One key too hot for a shard | Short L1 cache | Suffix replication or replica reads |
| One value too big | Split into buckets | Redesign the data model |
Interview angle
Interview questions
Q1: Your homepage key expires every 5 minutes and the database spikes each time. Walk through your fix.
First, singleflight so each app server issues at most one rebuild. Second, store a soft expiry inside the value and a longer hard TTL on the key; when a reader sees the soft expiry has passed, it tries a SET NX PX lock, the winner rebuilds in the background, and everyone else returns the stale value immediately. That gives one rebuild for the whole fleet and zero user-visible misses. Alternatively, use XFetch so one request refreshes slightly before expiry. Finally, because this key is known to be hot, consider a scheduled job that refreshes it every minute so it never expires at all.
Q2: State the XFetch condition and explain each term.
Recompute if now - delta * beta * ln(rand()) >= expiry. delta is how long the last computation took, so expensive values refresh earlier. rand() is uniform in (0, 1], so -ln(rand()) is a non-negative random number with mean 1, which shifts each request’s view of the clock forward by a random amount averaging delta * beta. beta tunes eagerness, with 1 as the default and values above 1 refreshing earlier. Because each request decides independently, the first one to trigger usually does so before expiry, rebuilds, and resets the expiry for everyone else.
Q3: One key receives 1 million reads per second and your cache cluster has 50 shards. Adding shards does not help. Why, and what do you do?
A key maps to exactly one shard, so adding shards spreads other keys but leaves this key’s traffic on one node. Fixes: an in-process cache on each app server with a 1 to 5 second TTL, which caps that shard at roughly one read per server per TTL; replicating the key under N suffixes on different shards and having readers pick one at random (writes and invalidations touch all N); serving reads from that shard’s replicas; and shrinking the value so each read costs less network. I would also add hot key detection so this is caught before the shard saturates.
✅ Key takeaways
- Misses during a rebuild equal request rate times rebuild time, and concurrent rebuilds lengthen the rebuild, so stampedes feed themselves.
- Singleflight per process plus a lock with stale-while-revalidate gives one rebuild per fleet and no user-facing misses.
- XFetch: recompute if now - delta x beta x ln(rand()) is at or past expiry. Expensive keys refresh earlier, with no coordination.
- Jitter TTLs, warm caches before shifting traffic, and cap concurrency on the database miss path.
- Sharding cannot split one key. Hot keys need a short local cache, suffix replication or replica reads, and detection via top-K sampling.
- Big keys block single-threaded command execution; split them and delete with UNLINK.
🧠 Check your understanding
0 / 4-
1A key read 50,000 times per second expires, and rebuilding it takes 100 ms. Roughly how many requests miss before the first rebuild completes, assuming no protection?
Misses equal rate times rebuild time: 50,000 per second x 0.1 s = 5,000. It is tempting to think the first miss fixes it, but the cache stays empty until the rebuild finishes, and in practice the rebuild slows down under the load, so the real number is higher.
-
2Which XFetch condition is correct, given delta is the recompute time and rand() is uniform in (0, 1]?
ln(rand()) is zero or negative, so subtracting delta * beta * ln(rand()) moves now forward by a random positive amount and triggers early refreshes. With a plus sign the term moves now backwards and refreshes would happen late. The other options are not the published algorithm.
-
3Your cache cluster has 40 shards, and one product key is saturating a single shard. What is the most effective first fix?
A short in-process cache caps reads to the shard at about one per app server per TTL, regardless of user traffic. More shards do not help because one key always maps to one shard, LFU only affects eviction, and a longer TTL does not reduce read rate.
-
4With a distributed rebuild lock, what should requests that lose the lock do?
Serving the stale copy keeps latency low and keeps load off both the database and the cache. Polling moves the stampede onto the lock's shard, querying the database defeats the lock, and returning errors triggers client retries that amplify load.
Where to go next
- Cache eviction policies: stampedes start with a key leaving the cache, and eviction decides which keys leave when memory is full.
- CDN and edge caching: request collapsing, origin shields and stale-while-revalidate are the same defences at the HTTP layer.
- Load shedding and backpressure: what to do when protection fails and the database must refuse work to survive.
- Design a news feed: a capstone where celebrity fan-out and hot keys shape the whole architecture.
Finished this lesson?
Mark it complete to track your progress across the roadmap.