Skip to content

Lesson 8 of 9 · 25m

Stampede Protection and Hot-Key Resilience

Prevent cache-miss dogpiles with request coalescing, locks, stale-while-revalidate, jitter, and deliberate origin protection.

The cache does not usually fail gradually. It fails at 09:00 when a batch job expires ten thousand entries, a celebrity object disappears, or Redis restarts empty. Every worker sees a miss at the same time and every worker queries the database. The database, which you were trying to protect, becomes the accidental synchronization point. This is the cache stampede.

The failure shape

A hot key expires. One hundred concurrent requests arrive before the first worker recomputes it:

t0  key expires
t1  100 requests miss cache
t2  100 identical database queries start
t3  database queue explodes
t4  first response populates cache, too late

Request coalescing turns many misses into one computation. Go calls this singleflight; other ecosystems call it request collapsing, promise deduplication, or dogpile protection.

Coalesce concurrent misses

The shape is simple: one caller computes, concurrent callers wait for or share that result:

def get_product_coalesced(product_id):
    key = f"catalog:v4:product:{product_id}"
    cached = redis.get(key)
    if cached is not None:
        return decode(cached)

    with singleflight.do(key, lambda: load_and_cache_product(product_id)) as result:
        return result

In a multi-process or multi-host system, in-process singleflight is insufficient. You also need a distributed lock or probabilistic early recompute. Locks must have expiry, otherwise a crashed worker can pin the key forever.

Distributed locking without distributed illusions

A Redis lock can elect one recomputation worker:

lock_acquired = redis.set(
    "lock:" + key,
    worker_id,
    nx=True,
    ex=10,
)

If acquired, recompute and populate. If not, either wait briefly and retry the cache, serve slightly stale data if available, or fail transparently. Do not copy the database query behind the lock as your first reaction; that recreates the stampede with extra latency.

Stale-while-revalidate saves tails

If you have an old value, use it while one worker refreshes asynchronously:

cache-control: max-age=30, stale-while-revalidate=30

The same idea applies inside applications. Store a value with logical expiration earlier than physical expiration. When logically expired, one worker refreshes while others continue serving the old object for a bounded period. This trades bounded staleness for latency stability. For prices, inventory, and authorization, that trade may be unacceptable. For a rendered public page, it is often ideal.

Jitter and soft expiration are cheap insurance

Do not let keys share the same lifetime when they were populated together. Add randomized TTL and consider logical expiry embedded in the value:

{
  "data": {"id": 1042, "name": "Pro"},
  "soft_expire_at": 1810000000,
  "hard_expire_at": 1810000300
}

Soft expiry controls refresh timing. Hard expiry bounds total staleness.

Protect the origin explicitly

Even with perfect coalescing, the origin has finite capacity. Use timeouts, concurrency limits, queues, and backpressure:

db_pool = DatabasePool(max_connections=40, statement_timeout_ms=800)

A cache outage should produce controlled degradation, not unbounded fallback concurrency. Rate-limit recomputation paths separately from normal reads.

Field notes

  • Locking only the cache write does not prevent multiple database reads; coalesce around the load.
  • A lock without expiry is an outage waiting for a crashed worker.
  • Serving stale data is a product decision. Never make it accidentally.
  • Cold starts are stampedes too. Warm critical keys after deployment or cache restoration.
  • Test hot-key expiry at realistic concurrency, not with one curl in a loop.

Was this lesson helpful?

Sign in to rate