Cache Stampede Prevention

Compare cache-stampede controls by the duplicate work they prevent and the failure modes they add, from local single-flight to distributed leases.

published: reading time: 7 min read author: Geek Workbench updated: November 8, 2026
Quick Summary

A cache stampede sends many concurrent misses for the same key to the source. This guide compares process-local single-flight, distributed refresh leases, stale serving, TTL jitter, and early refresh, including the new failure each approach introduces.

Cache Stampede Prevention: Single-Flight, Leases, and Refresh

A cache stampede happens when many requests miss the same popular key and each starts the same expensive fetch. A synchronized expiry can trigger it, but so can an eviction, cache restart, or slow refresh.

The goal is to control duplicate work without serving data beyond the product’s freshness rules. The right mechanism depends on whether requests share a process, whether stale data is acceptable, and how the system handles a failed refresh.

The race

Imagine several requests read an expired product_catalog key at nearly the same time. Each sees a miss, starts a database query, and tries to fill the cache. The cache still returns a miss until one refresh completes. With a popular key, duplicate work can push the database into higher latency, which makes the refreshes last longer and keeps the miss window open.

Choose a coordination boundary

Single-flight means that requests for the same key share one in-flight fetch. A process-local promise, future, or lock coordinates only callers in that process. If four service replicas each receive misses, each replica can start its own fetch.

A distributed lease coordinates across replicas through shared state. A lease has a bounded lifetime so a crashed holder does not block refresh forever. That bound creates a race: a paused holder can outlive its lease, another worker can acquire it and write a fresh value, then the old holder can resume and overwrite the newer result. Use a source version or fencing token when stale holders must be prevented from publishing. The lease backend also becomes a dependency.

Approach Race it prevents Failure mode or cost it adds
Process-local single-flight Duplicate fetches for the same key in one process. Other replicas can still fetch; all local waiters inherit the fetch’s latency or error.
Distributed lease Multiple workers refreshing the same key while one valid lease is held. Lease expiry, process pauses, clock/network failures, and unsafe release or stale writes need handling.
Serve stale while refreshing A miss burst while a refresh runs, if an older value is still available. Users can receive stale data; define a maximum stale age and what happens when refresh fails.
TTL jitter Many different keys expiring at the same instant. It spreads expirations but does not stop duplicate work for one hot key.
Probabilistic early refresh Many callers waiting for the same hard expiry. Multiple early refresh attempts can still occur; it may refresh unnecessarily and should be bounded.

These techniques can be combined. For example, TTL jitter spreads expiry across keys while single-flight limits concurrent refreshes for each key. Stale serving is suitable only when the data contract allows it.

A refresh flow

The following is illustrative pseudocode, not a drop-in implementation:

get(key):
    value = cache.read(key)
    if value is fresh:
        return value

    if an older value is still within the allowed stale window:
        start_or_join_one_refresh(key)
        return older value

    return join_or_start_one_refresh(key)

refresh(key):
    acquire coordination for key
    read source of truth
    publish only if source version is newer than cached version
    release coordination only if still its owner

For a process-local implementation, keep an in-flight task or promise per key and remove it after success or failure. All callers that join that task receive its result or error. Make sure a failed task is cleaned up so the next request can try again. This pattern avoids an unsafe hand-written queue that loses waiters or leaves a key permanently marked as refreshing.

For a shared lease, use the locking mechanism’s documented acquire and release procedure. Redis’s distributed locks documentation, checked 2026-11-08, explains owner tokens, expiry, and why a client must not release a lock that another client has since acquired. Supported commands and behavior depend on the Redis version; apply the procedure for the version you run.

Failure timeline: a lease expires early

Illustrative scenario: Four application replicas receive a miss for the same key. Replica A acquires a 10-second lease and starts a slow source query. A pauses for longer than 10 seconds. Replica B acquires the expired lease, gets a newer value, and stores it. A resumes with its older result.

If A writes unconditionally, the cache moves backward. A lease alone limits ordinary overlap; it does not prove the holder is still current when it writes. Store a source version with the value and reject an older version, or use a fencing mechanism the downstream store checks. If neither is possible, avoid relying on a lease for correctness-sensitive data.

Tune freshness and refresh behavior

  • Add TTL jitter when a large set of keys is written together and expires together. The jitter range should fit the data’s freshness contract.
  • Use early refresh when a hot key takes a long time to rebuild and some work can happen before expiry. Keep refresh concurrency bounded; randomization reduces synchronization but does not guarantee one refresher.
  • Use stale-while-revalidate only when returning a slightly old value is acceptable. Set both a normal TTL and a hard limit on stale serving.
  • Use single-flight for same-process duplicate work. Add a shared lease only when cross-replica refresh load justifies its operational and failure costs.

Do not extend TTL indefinitely to hide a slow source. It can leave outdated data in circulation without fixing duplicate refresh work.

Measure the result

Track cache misses and source fetches for hot keys, refresh duration and errors, how many callers join an in-flight refresh, lease acquisition failures, stale responses, and the age of served values. A falling source-query count is useful only if refresh latency and value freshness remain within the service’s requirements.

Continue reading

Interview Questions

1. What does process-local single-flight coordinate?

It lets callers in one process share the same in-flight fetch for a key. Separate replicas still have separate in-flight maps, so they can each start a fetch.

2. What new race does a distributed lease introduce?

A holder can pause beyond its lease, then resume after another worker has acquired the lease and written a newer result. Owner-checked release prevents deleting another worker's lock; version checks or fencing can prevent stale publication.

3. When is serving stale data a reasonable choice?

When the product can tolerate an older value for a defined period. Set a hard stale-age limit and decide what callers receive if refresh fails or the stale window ends.

4. Does TTL jitter prevent a hot-key stampede?

No. Jitter spreads expirations across different keys. Concurrent misses for one popular key still need single-flight, a lease, stale serving, or another same-key control.

Category

Related Posts

Caching Strategies: A Practical Guide

Compare cache-aside, read-through, write-through, and write-behind. See how cache layers, invalidation, freshness goals, and workload shape the choice.

#caching #redis #distributed-systems

Cache Patterns: Choosing Read and Write Strategies

Compare cache-aside, read-through, write-through, write-around, and write-behind patterns, their freshness trade-offs, and update races to plan for.

#system-design #caching #distributed-systems

Distributed Caching: Scaling Cache Across Multiple Nodes

Learn how distributed cache clusters route keys, replicate data, recover from node failures, and manage capacity and eviction trade-offs.

#system-design #caching #distributed-systems