Cache Stampede Prevention Pattern
Prevent thundering herd cache misses with locks, single-flight, stale-while-revalidate and early refresh strategies that keep the database safe.
Overview
When a hot cache key expires under load, every request landing in the gap sees the same miss — and each one goes to the database for the same value. That pile-up is a cache stampede (also called thundering herd or dogpile), and on a database sized for the healthy miss rate it escalates to timeouts and cascading failures fast.
Stampede prevention makes sure one request rebuilds the entry while the rest wait or take a slightly stale copy. N concurrent misses collapse into a single database query. For the wider context — TTL choice, cache-aside, invalidation — see the Caching Strategies recipe.
When to Use
Reach for this pattern when:
- A hot key — homepage payload, feature flags, pricing — expires and hundreds of misses pile onto the same query
- Latency graphs show a recurring spike aligned with your cache TTL
- Deploys or cache flushes trigger a database burst the connection pool can’t absorb
- Several app instances share Redis and all of them miss on the same key at once
- Tail latency matters more than the average: a stampede is a p99 problem, not a mean problem
You can skip it when a key gets a handful of reads — the lock adds a Redis round-trip that costs more than the rare duplicate load it prevents.
Solution
Strategy 1: Single-Flight with In-Memory Lock (Single Instance)
import json
import threading
from typing import Any, Callable
import redis
class SingleFlightCache:
def __init__(self, redis_client: redis.Redis, ttl: int = 3600):
self.redis = redis_client
self.ttl = ttl
self._locks: dict[str, threading.Event] = {}
self._lock_guard = threading.Lock()
def get_or_load(self, key: str, loader: Callable[[], Any]) -> Any:
cached = self.redis.get(key)
if cached is not None:
return json.loads(cached)
# Single-flight: only one thread loads, others wait
with self._lock_guard:
if key in self._locks:
event = self._locks[key]
else:
event = threading.Event()
self._locks[key] = event
event = None # This thread will load
if event is not None:
# Wait for the loading thread to finish
event.wait(timeout=30)
cached = self.redis.get(key)
if cached is not None:
return json.loads(cached)
# Still missing — load ourselves (timeout or loader failure)
return self._load_and_cache(key, loader)
# This thread is the loader
try:
return self._load_and_cache(key, loader)
finally:
with self._lock_guard:
evt = self._locks.pop(key, None)
if evt:
evt.set() # Notify waiting threads
def _load_and_cache(self, key: str, loader: Callable[[], Any]) -> Any:
value = loader()
self.redis.setex(key, self.ttl, json.dumps(value))
return value
cache = SingleFlightCache(redis.Redis(host="localhost", port=6379))
def get_user(user_id: str) -> dict:
return cache.get_or_load(
f"user:{user_id}",
lambda: db.query_one("SELECT * FROM users WHERE id = %s", [user_id])
)
Strategy 2: Distributed Lock with Redis (Multi-Instance)
import json
import time
import uuid
from typing import Any, Callable
import redis
class StampedeSafeCache:
def __init__(self, redis_client: redis.Redis, ttl: int = 3600, lock_timeout: int = 30):
self.redis = redis_client
self.ttl = ttl
self.lock_timeout = lock_timeout
def get_or_load(self, key: str, loader: Callable[[], Any]) -> Any:
cached = self.redis.get(key)
if cached is not None:
return json.loads(cached)
lock_key = f"lock:{key}"
lock_value = str(uuid.uuid4())
# Try to acquire lock
acquired = self.redis.set(lock_key, lock_value, nx=True, ex=self.lock_timeout)
if not acquired:
# Another instance is loading — wait and retry
return self._wait_and_read(key, loader)
try:
# Double-check cache after acquiring lock
cached = self.redis.get(key)
if cached is not None:
return json.loads(cached)
value = loader()
self.redis.setex(key, self.ttl, json.dumps(value))
return value
finally:
# Release lock only if we still own it
self._release_lock(lock_key, lock_value)
def _wait_and_read(self, key: str, loader: Callable[[], Any]) -> Any:
for _ in range(10):
time.sleep(0.5)
cached = self.redis.get(key)
if cached is not None:
return json.loads(cached)
# Timeout waiting — load directly (fallback)
value = loader()
self.redis.setex(key, self.ttl, json.dumps(value))
return value
def _release_lock(self, lock_key: str, lock_value: str) -> None:
# Lua script for atomic check-and-delete
script = """
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
"""
self.redis.eval(script, 1, lock_key, lock_value)
cache = StampedeSafeCache(redis.Redis(host="localhost", port=6379))
TypeScript with Redis Distributed Lock
import { createClient } from 'redis';
import { randomUUID } from 'crypto';
class StampedeSafeCache {
private redis: ReturnType<typeof createClient>;
private ttl: number;
private lockTimeout: number;
constructor(redisClient: ReturnType<typeof createClient>, ttl = 3600, lockTimeout = 30) {
this.redis = redisClient;
this.ttl = ttl;
this.lockTimeout = lockTimeout;
}
async getOrLoad<T>(key: string, loader: () => Promise<T>): Promise<T> {
const cached = await this.redis.get(key);
if (cached !== null) {
return JSON.parse(cached) as T;
}
const lockKey = `lock:${key}`;
const lockValue = randomUUID();
const acquired = await this.redis.set(lockKey, lockValue, { NX: true, EX: this.lockTimeout });
if (!acquired) {
return this.waitAndRead(key, loader);
}
try {
// Double-check after acquiring lock
const doubleCheck = await this.redis.get(key);
if (doubleCheck !== null) {
return JSON.parse(doubleCheck) as T;
}
const value = await loader();
await this.redis.set(key, JSON.stringify(value), { EX: this.ttl });
return value;
} finally {
await this.releaseLock(lockKey, lockValue);
}
}
private async waitAndRead<T>(key: string, loader: () => Promise<T>): Promise<T> {
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, 500));
const cached = await this.redis.get(key);
if (cached !== null) {
return JSON.parse(cached) as T;
}
}
// Timeout — load directly as fallback
const value = await loader();
await this.redis.set(key, JSON.stringify(value), { EX: this.ttl });
return value;
}
private async releaseLock(lockKey: string, lockValue: string): Promise<void> {
const script = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
`;
await this.redis.eval(script, { keys: [lockKey], arguments: [lockValue] });
}
}
Strategy 3: Early Refresh (Probabilistic TTL)
Instead of waiting for expiration, each request refreshes the entry with a probability that grows as the TTL approaches zero. Reloads spread over time instead of firing all at once. The canonical version is XFetch, from the 2015 VLDB paper Optimal Probabilistic Cache Stampede Prevention; the code below uses a simpler linear ramp that’s close enough for most workloads. For a dedicated treatment, see the Refresh-Ahead Cache pattern.
import json
import random
from typing import Any, Callable
import redis
r = redis.Redis(host="localhost", port=6379)
def get_or_load_probabilistic(
key: str,
loader: Callable[[], Any],
ttl: int = 3600,
early_refresh_window: int = 300,
) -> Any:
cached = r.get(key)
if cached is not None:
data = json.loads(cached)
ttl_remaining = r.ttl(key)
# Probability ramps from 0 to 1 as the remaining TTL drops to zero
if ttl_remaining < early_refresh_window:
refresh_probability = 1 - (ttl_remaining / early_refresh_window)
if random.random() < refresh_probability:
# This request refreshes; everyone else still gets cached data
try:
value = loader()
r.setex(key, ttl, json.dumps(value))
return value
except Exception:
pass # Fall back to the stale value on refresh failure
return data
# Full miss — load and cache
value = loader()
r.setex(key, ttl, json.dumps(value))
return value
The full XFetch formula triggers a rebuild when the remaining TTL drops below delta * beta * -ln(random()), where delta is the expected recompute time and beta a risk factor (1.0 by default). If you know your loader’s latency distribution, use that form; the linear ramp above is easier to tune.
Strategy 4: Stale-While-Revalidate
The most latency-friendly option: nobody waits. The entry stays readable past its logical TTL while exactly one request rebuilds it in the background. You trade a few seconds of staleness for a flat p99.
import json
import threading
import time
from typing import Any, Callable
import redis
r = redis.Redis(host="localhost", port=6379)
def get_swr(
key: str,
loader: Callable[[], Any],
ttl: int = 3600,
stale_window: int = 300,
) -> Any:
packed = r.get(key)
if packed is not None:
entry = json.loads(packed)
age = time.time() - entry["stored_at"]
if age < ttl:
return entry["value"]
if age < ttl + stale_window:
# Past logical TTL but still in the stale window — serve it and
# let a single caller rebuild in the background.
if r.set(f"refreshing:{key}", "1", nx=True, ex=stale_window):
threading.Thread(
target=_refresh,
args=(key, loader, ttl, stale_window),
daemon=True,
).start()
return entry["value"]
# Cold or fully expired — load inline
return _refresh(key, loader, ttl, stale_window)
def _refresh(key: str, loader: Callable[[], Any], ttl: int, stale_window: int) -> Any:
value = loader()
entry = {"value": value, "stored_at": time.time()}
# Physical TTL covers logical TTL + stale window so the entry survives
r.setex(key, ttl + stale_window, json.dumps(entry))
return value
Jittered TTL for Mass Expiry
The strategies above protect one hot key. There’s a second kind of stampede: a warm-up job or a deploy writes thousands of keys with the same TTL, and they all die together minutes later. Adding ±10% random jitter to each TTL spreads those expirations so the database sees a trickle of reloads instead of a wave.
# Spread mass expirations: ±10% jitter keeps a warm-up batch from expiring together
ttl = base_ttl + random.randint(-int(base_ttl * 0.1), int(base_ttl * 0.1))
r.setex(key, ttl, json.dumps(entry))
- Companion code: the cache-stampede-prevention-pattern companion repo packages a stampede simulator in Python and TypeScript — 20 concurrent callers on an expired key, counting database queries per strategy.
Explanation
The bug here is coordination, not caching. Every caller checks the cache within the same millisecond window, finds nothing, and they all decide to rebuild. Each strategy breaks that coordination differently:
- Single-flight — the first request to miss marks the key as in-progress; everyone else waits on that mark and reads the result once it lands. Cheap, but the coordination lives in process memory.
- Distributed lock — in-memory coordination stops working the moment you run a second instance, since each has its own locks. A Redis
SET NX EXlock gives the same guarantee across the fleet; losers of the race poll until the entry appears. One caveat: the lock TTL has to outlast a slow reload yet expire fast enough that a crashed loader doesn’t park the key. - Early refresh — rather than blocking the stampede, it dissolves it. Requests near expiry rebuild with growing probability, so the refresh lands before the synchronized miss would happen. No lock round-trip, but a request or two still pays full loader latency.
- Stale-while-revalidate — nobody waits at all. The entry stays readable past its logical TTL while one request refreshes it in the background. Flat p99 at the cost of briefly serving older data — the trade most latency-sensitive APIs take.
- Jittered TTL — solves the other stampede: mass expiry. If a warm-up writes 10,000 keys with a 3600 s TTL, they all expire within the same second. Jitter decorrelates them.
Watch the waiting window in the lock strategies: if reloads take 8 s and waiters give up after 5 s, every waiting instance falls back to loading — you’ve postponed the stampede, not prevented it. Size lock_timeout and the poll loop against your loader’s p95, not its average.
Variants
Three implementation families cover most deployments; pick by scope and by how much staleness you can tolerate:
| Strategy | Scope | Complexity | Best For |
|---|---|---|---|
| Single-flight (in-memory) | Single instance | Low | Single-process applications |
| Distributed lock (Redis) | Multi-instance | Medium | Fleets needing a strict single loader |
| Probabilistic early refresh (XFetch) | Any | Low | High-traffic keys with long TTLs |
| Stale-while-revalidate | Multi-instance | Medium | Latency-sensitive reads that tolerate briefly stale data |
| Jittered TTL | Any | Low | Mass expiry after bulk writes or warm-up jobs |
| Request coalescing | Single instance | Low | Batch-oriented workloads |
Single-flight and SWR keep tail latency lowest; the distributed lock is the only option that guarantees a single loader across instances.
Best Practices
- Always give the lock a timeout. If the loader crashes, an unexpiring lock parks the key and every later request hangs. Use your loader’s p95 or 30 s, whichever is larger.
- Re-check the cache after winning the lock. Between your miss and your lock acquisition another request may have filled the entry — the second
GETcosts nothing next to a duplicate reload. - Prefer probabilistic refresh on very hot keys. It skips the lock round-trip entirely, and a refresh window of 5–10% of the TTL is usually enough.
- Degrade to stale, not to an error. When the loader fails, the last cached value (even expired) beats a 500 for almost every workload.
- Watch lock contention, not just hit rate. A queue of waiters means the TTL is too short or the loader too slow — measure
load_time_msbefore adding more locks. - For a deeper treatment of when entries should die, see the Cache Invalidation pattern.
Common Mistakes
- A lock with no timeout is a parked key. One crashed loader and every later request waits until someone intervenes.
- Skipping the double-check wastes a reload. Between your miss and your lock win, another request may have already filled the entry. Harmless, but it doubles the load the pattern exists to remove.
- In-memory locks don’t cross instances. The second instance never sees the first one’s flag, so each instance runs its own “single” reload — the stampede just gets smaller, not prevented.
- One global lock serializes all misses. Lock per key: a slow reload of
user:42shouldn’t hold upproduct:7. - Falling back to “just load anyway” reopens the stampede. When
SET NXfails, the request has to wait and retry. Loading anyway is exactly the behavior the lock exists to stop.
Further Reading
- Optimal Probabilistic Cache Stampede Prevention — the VLDB 2015 paper that introduced XFetch.
- Redis Distributed Locks — official docs on the
SET NX PXpattern and its edge cases. - Cache stampede — Wikipedia — taxonomy of mitigation approaches (locking, external recomputation, probabilistic).
Frequently Asked Questions
What's the difference between cache stampede and cache penetration?
A stampede happens when a valid key expires and a burst of requests misses at once. Penetration is requests asking for keys that don't exist anywhere — every single one hits the database. Different problems: stampedes need coordination, penetration needs bloom filters or negative caching.
Is single-flight enough for multi-instance deployments?
No — in-memory locks are per-process. With three instances you get three simultaneous reloads. Coordinate across the fleet with a Redis SET NX distributed lock, or pick a strategy that doesn't need one (early refresh, stale-while-revalidate).
How does probabilistic early refresh work?
The closer an entry gets to expiring, the more likely any given request is to rebuild it early. With a 1-hour TTL and a 5-minute window, a request arriving 4 minutes before expiry has roughly a 20% chance of refreshing. The rebuild lands before the synchronized miss instead of during it.
What is XFetch?
XFetch is the probabilistic early-expiration algorithm from the 2015 VLDB paper Optimal Probabilistic Cache Stampede Prevention (Vattani, Chierichetti, Lowenstein). A request rebuilds when the remaining TTL drops below delta * beta * -ln(random()), where delta is the expected recompute time. The linear ramp in this pattern is a simpler approximation.
Should I return stale data while refreshing?
Usually, yes. If a value exists in the stale window, serve it while one request refreshes in the background — that's the stale-while-revalidate strategy. You trade a few seconds of staleness for a p99 that never waits on a reload.
Related Resources
Read-Through Cache Pattern
A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.
PatternRefresh-Ahead Cache Pattern
Proactively refresh cache entries before they expire to eliminate cache misses on hot keys and maintain consistent read latency.
PatternCache Invalidation Pattern
Strategies for keeping cached data fresh: TTL expiration, explicit invalidation, write-through, and event-driven cache eviction.
RecipeCaching Strategies: Browser, CDN, Redis & Database
Implement effective caching at every layer of the stack: browser cache, CDN edge, Redis application cache, and database query cache — with invalidation strategies that keep data fresh.
DocCache Eviction Policy Template
Template for documenting cache eviction rules per cache layer: LRU, LFU, TTL, FIFO, random eviction. Includes policy selection matrix, per-layer configuration, memory limits, and monitoring rules with code examples.