Reference · Cheat sheet

Cache-aside & stampede

Lazy-load the cache; then stop the herd. Print it, pin it.

From lesson 0004See also glossary

Cache-aside read path

val = GET key
if val is nil:            # miss
    val = db.query(...)
    SET key val EX (base + jitter)
return val

Patterns at a glance

PatternLoads cacheWhen
Cache-aside (lazy)app coderead miss
Read-throughcache layerread miss (transparent)
Write-throughapp/backendevery DB write (sync)
Write-behindcachecache now, DB later (async)

Cache stampede (thundering herd / dogpile)

A hot key expires → all concurrent requests miss at once → all hit the DB together. Worse when many keys share a TTL (lockstep expiry).

MitigationIdeaUse when
TTL jitterEX base + rand() — desync expiryalways (free)
Single-flight lockSET lock t NX EX: one rebuilds, rest wait/staleexpensive hot keys
XFetch (early recompute)probabilistically refresh before expiryno per-key stall allowed
Stale-while-revalidateserve stale, refresh in backgroundstaleness tolerable
Naive-lock trap

Don't release with a bare DEL — if work outran the lock TTL you'd delete someone else's lock. Store a random token; release with a Lua compare-and-delete:

if redis.call('get',KEYS[1])==ARGV[1]
then return redis.call('del',KEYS[1]) else return 0 end

Locking across nodes? Single-instance locks race under async replication → use Redlock.

← lesson 0004 · Sources: AWS caching patterns · Cache stampede · Redis distributed locks