Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 3

Surviving stampedes and hot keys

Defend distributed systems against cache stampedes, dogpile effects, and hot key saturation using single-flight coalescing, probabilistic early expiration, and jittered TTLs.

Contentsand lesson path

What you will learn

  • Prevent cache stampedes, hot-key overload and cache-induced inconsistency with techniques such as request coalescing, jittered TTLs and versioned writes.

01. Goal and setup

A cache can fail without crashing: one popular key expires, fifty requests miss at once, and all fifty ask the database the same question. In this lab you cause that stampede against a real Redis, count the database queries, and remove it three ways: coalescing inside one process, a short Redis lock across processes, and jittered expiry times. Then you spread one hot key over several hash slots and stop a slow reader from caching an old value.

The database is a stand-in: an async function that sleeps 80 ms and counts its calls, so every number below is a count, not a timing.

You need: Python 3.12 or newer, uv, and Docker for Redis (or any Redis 7 or 8 on port 6379). Versions in this run: Python 3.12.13, redis-py 8.1.0, Redis 8.10.3.

Terminal · a throwaway Redis and a virtual environment
mkdir stampede-lab && cd stampede-lab
docker run -d --name stampede-redis -p 6379:6379 redis:8-alpine
docker exec stampede-redis redis-cli ping

uv venv --python 3.12 .venv && source .venv/bin/activate
uv pip install "redis==8.1.0"
python -c "import redis; print(redis.__version__)"
Expected output (the container id that docker run prints first is left out)
PONG
8.1.0

Save the whole lab as one file. Each step runs one function: python stampede.py naive, then singleflight, pods, jitter, slots and versions. Every step first deletes the keys it uses, so you can rerun any step.

Python · stampede.py
"""Cache stampede lab: reproduce it against Redis, then defend against it."""
import asyncio
import json
import random
import sys
import uuid
from collections import Counter
from typing import Any, Awaitable, Callable

import redis.asyncio as aioredis
from redis.crc import key_slot

REDIS_URL = "redis://localhost:6379/0"
DB_QUERIES = 0  # how often the fake database was asked


async def database_lookup(product_id: str) -> dict:
    """Stands in for an 80 ms SQL query."""
    global DB_QUERIES
    DB_QUERIES += 1
    await asyncio.sleep(0.08)
    return {"product_id": product_id, "stock": 42}


async def naive_get(r: aioredis.Redis, product_id: str) -> dict:
    """Plain cache-aside: every caller that misses queries the database."""
    key = f"product:{product_id}"
    if (cached := await r.get(key)) is not None:
        return json.loads(cached)
    value = await database_lookup(product_id)
    await r.set(key, json.dumps(value), ex=300)
    return value


class SingleFlight:
    """Collapse concurrent calls for the same key into one in-flight call."""

    def __init__(self) -> None:
        self._calls: dict[str, asyncio.Future] = {}

    async def do(self, key: str, work_fn: Callable[[], Awaitable[Any]]) -> Any:
        # No await between the lookup and the insert: on one event loop no
        # other coroutine can slip in between, so no lock is needed.
        fut = self._calls.get(key)
        if fut is not None:
            # shield(): one cancelled follower must not cancel the shared future
            return await asyncio.shield(fut)
        fut = asyncio.get_running_loop().create_future()
        self._calls[key] = fut
        try:
            result = await work_fn()
        except BaseException as exc:
            # Resolve the future on EVERY exit, cancellation included, so
            # followers get an error instead of waiting for ever.
            if isinstance(exc, Exception):
                fut.set_exception(exc)
            else:
                fut.set_exception(RuntimeError(f"leader for {key!r} cancelled"))
            fut.exception()  # mark as retrieved: no warning if nobody waited
            raise
        else:
            fut.set_result(result)
            return result
        finally:
            self._calls.pop(key, None)


async def coalesced_get(r, flight: SingleFlight, product_id: str) -> dict:
    """Cache-aside whose misses go through one process's single-flight."""
    key = f"product:{product_id}"
    if (cached := await r.get(key)) is not None:
        return json.loads(cached)
    return await flight.do(key, lambda: naive_get(r, product_id))


async def locked_get(r, product_id: str) -> dict:
    """Cluster-wide: one caller wins a short Redis lock, the others wait."""
    key = f"product:{product_id}"
    for _ in range(50):  # wait at most about 2.5 s for the leader
        if (cached := await r.get(key)) is not None:
            return json.loads(cached)
        token = uuid.uuid4().hex
        if await r.set(f"lock:{key}", token, nx=True, px=5000):
            try:
                return await naive_get(r, product_id)
            finally:  # release only our own lock (a real one uses a Lua check)
                if await r.get(f"lock:{key}") == token.encode():
                    await r.delete(f"lock:{key}")
        await asyncio.sleep(0.05)
    raise TimeoutError(f"no value for {key} after waiting for the leader")


async def burst(r, reader, n: int = 50) -> int:
    """n concurrent requests for a cold key; returns how many hit the database."""
    global DB_QUERIES
    await r.delete("product:999", "lock:product:999")
    DB_QUERIES = 0
    await asyncio.gather(*(reader(i) for i in range(n)))
    return DB_QUERIES


async def step_naive(r) -> None:
    queries = await burst(r, lambda i: naive_get(r, "999"))
    print(f"naive cache-aside: 50 requests on a cold key -> {queries} DB queries")


async def step_singleflight(r) -> None:
    flight = SingleFlight()
    queries = await burst(r, lambda i: coalesced_get(r, flight, "999"))
    print(f"single-flight:     50 requests on a cold key -> {queries} DB query")

    async def slow(value: str, seconds: float) -> str:
        await asyncio.sleep(seconds)
        return value

    leader = asyncio.create_task(flight.do("A", lambda: slow("a", 1.0)))
    await asyncio.sleep(0)  # let the leader for A register its future
    await flight.do("B", lambda: slow("b", 0.01))
    print(f"key B answered while A was still in flight: {not leader.done()}")
    follower = asyncio.create_task(flight.do("A", lambda: slow("a", 1.0)))
    await asyncio.sleep(0)  # let the follower start waiting
    leader.cancel()
    try:
        await follower
    except RuntimeError as err:
        print(f"follower of the cancelled leader got: {err}")


async def step_pods(r) -> None:
    pods = [SingleFlight() for _ in range(4)]  # one map per process, as in 4 pods
    queries = await burst(r, lambda i: coalesced_get(r, pods[i % 4], "999"), n=80)
    print(f"4 pods, single-flight each: 80 requests -> {queries} DB queries")
    queries = await burst(r, lambda i: locked_get(r, "999"), n=80)
    print(f"4 pods, Redis SET NX lock:  80 requests -> {queries} DB query")


async def step_jitter(r) -> None:
    random.seed(7)
    pipe = r.pipeline()
    ttls = []
    for n in range(1000):
        ttl = 3600 + random.randint(-360, 360)  # 1 hour +/- 10%
        ttls.append(ttl)
        pipe.set(f"warm:{n}", "1", ex=ttl)
    await pipe.execute()
    pipe = r.pipeline()
    for n in range(1000):
        pipe.ttl(f"warm:{n}")
    stored = await pipe.execute()  # one round trip; TTL may already be 1 s lower
    in_range = all(3240 - 1 <= t <= 3960 for t in stored)
    print(f"1000 warmed keys, TTL between 3240 and 3960 s: {in_range}")
    for label, chosen in (("constant", [3600] * 1000), ("jittered", ttls)):
        per_second = Counter(chosen).most_common(1)[0][1]
        per_minute = Counter(t // 60 for t in chosen).most_common(1)[0][1]
        print(f"{label} TTL: busiest second {per_second:>4},"
              f" busiest minute {per_minute:>4}")


async def step_slots(r) -> None:
    print(f"product:999 -> slot {key_slot(b'product:999')}")
    copies = [f"product:999:{i}" for i in range(1, 6)]
    print("salted copies ->", [key_slot(c.encode()) for c in copies])
    for c in copies:
        await r.set(c, json.dumps({"product_id": "999", "stock": 42}), ex=300)
    random.seed(1)
    picks = Counter(random.choice(copies) for _ in range(1000))
    print("1000 reads spread over copies:", sorted(picks.values()))


SET_IF_NEWER = """
local cur = redis.call('GET', KEYS[1])
if cur and cjson.decode(cur)['version'] >= tonumber(ARGV[2]) then
  return 0
end
redis.call('SET', KEYS[1], ARGV[1], 'EX', ARGV[3])
return 1
"""


async def step_versions(r) -> None:
    key = "user:400"
    stale = {"version": 1, "name": "Ada"}       # what slow reader A loaded
    fresh = {"version": 2, "name": "Ada L."}    # what writer B committed
    # Plain cache-aside: B deletes the key, then A's delayed SET lands.
    await r.delete(key)
    await r.set(key, json.dumps(stale), ex=300)
    held = json.loads(await r.get(key))["version"]
    print(f"DEL on write, plain SET: cache holds version {held}")
    # Versioned: B stores version 2, and every SET goes through the Lua check.
    set_if_newer = r.register_script(SET_IF_NEWER)
    await r.delete(key)
    for who, row in (("B", fresh), ("A", stale)):
        args = [json.dumps(row), row["version"], 300]
        stored = await set_if_newer(keys=[key], args=args)
        print(f"  {who} sets version {row['version']}:"
              f" {'stored' if stored else 'rejected'}")
    held = json.loads(await r.get(key))["version"]
    print(f"versioned SET via Lua:   cache holds version {held}")


STEPS = {"naive": step_naive, "singleflight": step_singleflight,
         "pods": step_pods, "jitter": step_jitter, "slots": step_slots,
         "versions": step_versions}


async def main(step: str) -> None:
    r = aioredis.from_url(REDIS_URL, socket_timeout=2, socket_connect_timeout=2)
    try:
        await STEPS[step](r)
    finally:
        await r.aclose()


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1]))

02. How stampedes and hot keys hurt

A cache stampede (also called the dogpile effect or thundering herd) happens when a hot key expires under heavy concurrent reads. Take a product page read 2,500 times a second. When its key expires, every request that arrives before someone refills it misses: with a 50 ms rebuild, about 2,500 × 0.05 = 125 requests run the same query. If the query slows down under that load, the window grows and more requests miss. Step 1 reproduces this with 50 requests.

A hot key hurts even when it never expires. Redis Cluster maps every key to one of 16,384 hash slots, and one primary serves each slot, so all reads of one key land on one node and adding nodes does not help. The remedies spread the reads: a short in-process (L1) cache, reads from replicas (accepting slightly stale data), or salting, which stores copies under several keys and reads a random one (step 5).

03. Step 1: cause a stampede

naive_get is ordinary cache-aside: GET the key, and on a miss query the database and SET the result with a TTL. burst deletes the key and sends 50 concurrent requests. All 50 run their GET before the first database answer arrives 80 ms later, so all 50 miss:

Terminal
python stampede.py naive
Expected output
naive cache-aside: 50 requests on a cold key -> 50 DB queries

Fifty identical queries for one value. Nothing is wrong with any single request; the damage comes from all of them missing in the same window.

04. Step 2: coalesce the misses in one process

Request coalescing, often called single-flight after the Go package, lets one caller per key run the expensive work while the others await its result. SingleFlight.do keeps a dictionary of in-flight futures. The dictionary is only touched between awaits, so waiting callers hold no lock and a slow key never delays another key. And the leader resolves the shared future on every exit path, including cancellation (a client disconnect or asyncio.timeout), so followers get an error instead of waiting for ever. The step checks both properties after the burst:

Terminal
python stampede.py singleflight
Expected output
single-flight:     50 requests on a cold key -> 1 DB query
key B answered while A was still in flight: True
follower of the cancelled leader got: leader for 'A' cancelled

One query instead of fifty: the other 49 requests waited about 80 ms for the leader's result. The dictionary lives in one process's memory, though, which the next step tests.

05. Step 3: four pods, and a lock in Redis

A real service runs several processes. step_pods gives each of four "pods" its own SingleFlight and spreads 80 requests across them. Then it repeats the burst with locked_get, which picks the leader in Redis with SET lock:<key> <token> NX PX 5000: NX writes only if the lock key does not exist yet, and PX 5000 expires the lock after five seconds even if its holder crashes. The losers poll the cache every 50 ms:

Terminal
python stampede.py pods
Expected output
4 pods, single-flight each: 80 requests -> 4 DB queries
4 pods, Redis SET NX lock:  80 requests -> 1 DB query

In-process coalescing gives one query per pod, so 20 pods could send 20. The Redis lock brings it down to one for the whole cluster, at a price: losers wait by polling, the lock needs a timeout longer than the slowest rebuild, and the release must check the token, so that a leader whose lock expired cannot delete someone else's. The script's GET-then-DEL release leaves a small gap; production code does both in one Lua script. Across a failover the lock can be lost, so treat it as load shedding, not as a correctness guarantee.

06. Step 4: spread expiry times with jitter

Stampedes also come from the calendar. A warm-up job that writes many keys with EX 3600 makes them all expire in the same second an hour later. TTL jitter adds a random offset to each TTL. step_jitter writes 1,000 keys with 3,600 s ± 10% (seeded, so the numbers repeat), reads the TTLs back in one pipeline, and counts the keys that expire in the busiest second and the busiest minute, for jittered and for constant TTLs:

Terminal
python stampede.py jitter
Expected output
1000 warmed keys, TTL between 3240 and 3960 s: True
constant TTL: busiest second 1000, busiest minute 1000
jittered TTL: busiest second    7, busiest minute  100

The jittered keys expire over a 12-minute window instead of in one second, at a rate the database can absorb. Jitter does nothing for a single hot key. For that, probabilistic early expiration (the XFetch algorithm of Vattani, Chierichetti and Lowenstein) lets each read refresh the value early when -beta * delta * ln(random()) >= ttl_remaining, where delta is the recompute time, beta a tuning constant (1.0 by default) and random() uniform between 0 and 1. The chance grows as expiry nears and is higher for expensive values, so one request usually refreshes a hot key shortly before it expires. A rarely read key still expires and misses.

07. Step 5: spread one hot key over several slots

Redis Cluster picks the node for a key from its hash slot. redis-py's key_slot computes the same CRC16-based slot, so no cluster is needed to see where keys would land. The step prints the slot of product:999, the slots of five salted copies, and how 1,000 random reads spread over them:

Terminal
python stampede.py slots
Expected output
product:999 -> slot 10114
salted copies -> [14607, 2412, 6477, 10666, 14731]
1000 reads spread over copies: [189, 191, 199, 204, 217]

All reads of product:999 would go to the node that owns slot 10114. The five copies sit in five slots, which a cluster usually spreads over different nodes, and each copy takes about a fifth of the reads. The price is five writes per update and a short window in which copies disagree, so salting suits hot keys that change rarely.

08. Step 6: stop a slow reader from caching an old value

Plain cache-aside also fails quietly when a read and a write overlap. Client A misses on user:400 and reads version 1. Client B updates the row to version 2 and deletes the key. Then A, delayed, runs SET user:400 <version 1>, and the cache hides B's change until the key expires. step_versions plays this twice: with a plain DEL and SET, then with a versioned write, where B stores the new value with its row version instead of deleting the key, and every SET goes through a Lua script that refuses a lower version. Redis runs the script atomically, so nothing lands between the check and the write:

Terminal
python stampede.py versions
Expected output
DEL on write, plain SET: cache holds version 1
  B sets version 2: stored
  A sets version 1: rejected
versioned SET via Lua:   cache holds version 2

The check needs something to compare against, so B must leave a value or a tombstone such as {"version": 2} rather than delete the key; after a plain DEL, A's version 1 would be accepted. Leases, as in Facebook's memcache, are the alternative: a delete invalidates outstanding fill tokens. When you are done, run docker rm -f stampede-redis.

09. Check your understanding

Practice check · 3 questions

Stampede prevention and concurrency resilience check

Three scenario questions on hot keys in a cluster, early refresh, and single-flight across pods.

Q1. One product key receives 150,000 reads per second in a 12-shard Redis Cluster. One shard's CPU sits at 100% while the others are idle. Which change spreads the load?
Q2. For which key does probabilistic early expiration (XFetch) help the least?
Q3. A service runs 20 pods, each using the in-process single-flight from this lesson. A hot key expires while every pod is busy. How many database queries for that key can run at once?
Practice only: not graded, not saved, not evidence.

10. Apply it

Carry the defences into a service you know:

  • Coalesce misses on hot, expensive keys, such as menus or feature-flag sets, with a single-flight helper (or Go's singleflight.Group), and add a short Redis lock when the number of pods times the query cost is still too much.
  • Jitter TTLs wherever many keys are written at once, such as warm-up jobs and batch imports, by about 10–15% of the base TTL.
  • Version the writes of a cache that sees concurrent updates, for example a stock count edited on an admin screen while shoppers read it: store the row version with each value and route every fill through a check like the step 6 script.
  • Refresh expensive keys early with XFetch, handing the recompute to a background task.

11. Review prompt

Without looking back: describe, request by request, what happens when a hot key expires under concurrent reads. How does single-flight reduce that to one query, why is it per process, and what does a Redis SET NX PX lock add and cost? Why do keys written together need jittered TTLs? Walk through the delete-on-write race and explain how a versioned write closes it.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check