Design a Cache Stampede Protection System: Single-Flight, TTL Jitter and Safe Refresh

Tags:

Cache stampede protection: coordinated refresh and staggered expiration. Stale reads are subject to freshness policy.

At noon, a popular product page loses its cached entry. The database query normally takes 100 milliseconds, but suddenly hundreds of identical queries arrive together. Adding more API replicas makes the problem worse: every replica independently tries to rebuild the same value. This is the cache stampede problem. In this design walkthrough, we build a cache that protects its origin even when the hottest key expires.

1. Define the problem and requirements

Functional requirements

Return fresh cached values without contacting the database.Refresh expired keys without duplicating expensive work.Support cold misses, invalidation and bounded stale reads.

Non-functional requirements

Bound database concurrency even during cache outages.Keep tail latency predictable; define explicit freshness limits.Recover from crashed refresh workers without indefinite locks.

2. Capacity estimation

Assume 10,000 requests per second for a hot key, a 100 ms database query and a 60-second fresh TTL. By Little’s law, approximately 1,000 requests arrive during a 100 ms refresh. Without coalescing, many of these may query the origin. This estimate assumes steady arrivals and no other bottleneck; actual load must be measured.

ParameterIllustrative valueImplicationHot-key traffic10,000/sHigh amplification riskOrigin latency100 msAbout 1,000 arrivals during refreshFresh TTL60 sOne coordinated refresh per window in healthy operationStale grace30 sOptional availability buffer

3. High-level architecture

Place stateless API replicas in front of a shared Redis cache and authoritative database. Each replica reads the cache, checks freshness and uses a per-key refresh lease when necessary. A bounded origin bulkhead prevents different hot keys from overwhelming the database together.

Fresh hit: return immediately.Stale hit: return stale data only if policy allows, and attempt a background refresh.Cold miss: elect a refresh owner; other callers wait briefly with jitter or fail gracefully.Origin failure: retain allowed stale data; otherwise return a controlled error.

4. Low-level design

FieldPurposepayloadSerialized responseversionAuthoritative revision used to reject older writesfresh_untilTime after which refresh is neededstale_untilHard deadline for serving stale datalock:keySeparate expiring lease with unique owner token

Use Redis SET with NX and PX to acquire the lease atomically. Release it using an atomic compare-and-delete operation. A lease is not a guarantee of exclusive execution: a paused worker may resume after its lease expires. Where ordering matters, use an atomic version comparison or fencing token enforced by the destination.

5. Python example: local single-flight

The following runnable asynchronous example coalesces simultaneous loads within one Python process. It is intentionally not a distributed lock implementation. A production multi-replica deployment must also coordinate across replicas and enforce an origin concurrency budget.

import asyncio

class SingleFlight:
def __init__(self):
self.tasks = {}
self.guard = asyncio.Lock()

async def get(self, key, loader):
async with self.guard:
task = self.tasks.get(key)
if task is None:
task = asyncio.create_task(self._load(key, loader))
self.tasks[key] = task
return await asyncio.shield(task)

async def _load(self, key, loader):
try:
return await asyncio.wait_for(loader(), timeout=2)
finally:
async with self.guard:
self.tasks.pop(key, None)

async def main():
sf = SingleFlight()
calls = 0
async def load():
nonlocal calls
calls += 1
await asyncio.sleep(0.1)
return {“price”: 100}
results = await asyncio.gather(
*(sf.get(“product:42”, load) for _ in range(100))
)
assert calls == 1
assert len(results) == 100

asyncio.run(main())

Shielding prevents cancellation of one waiting caller from cancelling the shared refresh. The loader timeout bounds the shared task. This example does not persist values or limit the number of distinct keys; add a cache and bounded admission control before using it in production.

6. Design patterns and alternatives

PatternStrengthLimitationCache-asideSimple ownershipMisses need coordinationSingle-flightCoalesces same-key workLocal scope unless distributedStale-while-revalidateLow read latencyNot suitable for strict freshnessTTL jitterSpreads expiry across keysDoes not solve one hot keyBulkheadProtects origin across keysMay reject excess requests

7. API contract and failure recovery

GET /products/{id} returns a representation under the endpoint’s freshness policy. For public catalog descriptions, stale reads may be acceptable; checkout prices and authorization decisions may require authoritative validation. Never reuse one freshness policy for every data type.

Redis outage: apply a bounded origin semaphore and reject excess requests rather than bypassing the cache without limits.Worker crash: allow the lease to expire; retry with jitter.Slow origin: enforce deadlines and avoid synchronized retries.Late refresh: reject older versions atomically.Invalidation race: coordinate writes and invalidations using authoritative versions.

8. Testing and observability

ScenarioExpected outcome100 concurrent same-key requestsOne local loader invocation in the exampleSynchronized expiry across keysOrigin concurrency remains within budgetWorker dies during refreshLease expires and recovery is possibleOrigin unavailableStale data served only within policyOld worker resumesOlder version cannot overwrite newer value

Track fresh and stale hit rates separately, origin requests per key, lock contention, refresh latency, rejected requests and p99 latency. Compare results against a baseline with coordination disabled. A high hit rate alone can hide dangerous bursts at expiry.

9. System design interview questions and answers

Why does a cache stampede occur?

Concurrent misses trigger duplicate origin work. The problem becomes severe for popular keys or synchronized expiration.

Does TTL jitter eliminate stampedes?

No. It reduces correlated expiration across keys but a single popular key can still stampede. Combine it with per-key coalescing.

Is a distributed lease enough?

No. Expiry and process pauses can produce overlapping refreshes. Use owner-safe release and enforce version ordering where needed.

How do you handle Redis failure?

Limit origin concurrency, use deadlines and shed excess traffic. Do not let every replica bypass the cache freely.

When is stale data unacceptable?

When business or security correctness requires current information, such as authorization or final checkout pricing. Validate against the authoritative source.

How would you validate the design?

Load-test hot-key expiry and failures, then compare origin amplification, p99 latency and errors against the baseline.

10. Conclusion and implementation roadmap

The core design decision is to protect the database from unbounded work, not merely to maximize cache hit rate. Start with local single-flight and a bounded origin pool. Add shared leases when replicas multiply, and use stale-while-revalidate only for endpoints with explicit freshness tolerance.

Before rollout, establish baseline metrics and test synchronized expiry, worker crashes and Redis outages. Introduce the design gradually on a hot read endpoint and compare origin load and tail latency. If freshness requirements are strict, prioritize correctness over stale availability. A cache that remains predictable under failure is more valuable than one that performs well only on the happy path.

Further reading

Redis distributed locksdistributed job scheduler design

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *