The stampede is the characteristic cache failure, and it is worth understanding exactly.
A popular key expires. In the microsecond after, every in-flight request for it misses. Each of those requests then does what the cache-aside pattern says: it reads the source of truth. So a database that was serving one query per five minutes for that key suddenly receives a thousand identical queries in the same instant. The database slows; the slowness increases the number of concurrent requests waiting; those requests also miss and also query. This is a positive feedback loop, and it is how a healthy system with a 99% cache hit ratio falls over in seconds.
It is worse than it sounds for two reasons. First, the keys most likely to stampede are the most popular ones, which are exactly the keys whose database query is most expensive to run concurrently. Second, a mass expiry - a thousand keys set at the same moment by a deployment or a warm-up script, all with the same TTL - stampedes together, which is a self-inflicted thundering herd on a schedule.
Three defences, and you should implement all three in the laboratory:
1. Jittered TTLs. Instead of expire=300, use expire=300 + random(0, 60). This costs nothing, takes one line, and completely removes the mass-expiry case. It should be the default everywhere, applied by your cache wrapper rather than remembered at each call site.
2. A refresh lock, which is request coalescing. On a miss, attempt add on a lock key with a short TTL. add succeeds for exactly one requester - that is what makes it a lock. The winner reads the source of truth and populates the cache; the losers either wait briefly and re-read the cache, or return a slightly stale value, or return a degraded response. One database query instead of a thousand. The failure mode to handle: the lock holder dies, so the lock TTL must be short enough that progress resumes and long enough to cover the query.
3. Serve stale while revalidating. Store the value with a long TTL and a separate, shorter freshness marker. When the marker has gone, the value is still there: return it immediately and refresh in the background. Nobody waits, the database sees one query, and the cost is serving data that is briefly known to be stale. For a product catalogue this is almost always the right trade; for a bank balance it is not.
Negative caching addresses the opposite problem. A key that does not exist is a miss every time, so a request for a non-existent product hits the database on every attempt. Caching the absence - a sentinel value with a short TTL, because the row may appear - fixes it. This is also the defence against cache penetration, where an attacker requests a stream of random non-existent identifiers specifically to bypass your cache and load your database. Without negative caching that attack works perfectly and costs the attacker nothing.
Staleness, stated honestly. Every cached value is potentially stale, and the useful question is not "how do we prevent staleness" but "how stale can this get, and is that acceptable for this data". A design that can answer that per key is a good design. A design that assumes the cache is always fresh is wrong, and the places where it is wrong are the places where it matters.
Laboratory exercise 3 - cause the stampede, then stop it.
Build a catalogue service in front of a deliberately slow query - at least 200 ms - and run at least 500 concurrent clients.
Cause a real stampede. Warm one popular key, let it expire while the load runs, and measure: the number of database queries in the second after expiry, the latency spike, and the error rate. Make it fall over if you can. This is the measurement the module exists for.
Then implement the three defences one at a time, re-measuring after each: jittered TTLs with a mass-expiry test, a refresh lock with the coalescing proven by counting database queries, and serve-stale-while-revalidate with the staleness window measured. Produce a table.
Demonstrate the lock holder dying and show progress resuming after the lock TTL.
Implement negative caching, then demonstrate cache penetration: send 10,000 requests for random non-existent identifiers with and without it, and record the database load for each.
Finally, demonstrate the cache failure path: stop Memcached entirely while the load runs, and show the service still serving - degraded - rather than erroring.
Deliverable: the service, the stampede measurement with database query counts and latency, the three defences each measured separately, the lock holder failure, the penetration comparison, the cache-down evidence, and a written statement of the staleness window your design accepts for each key type and why.
# ==================================================================
# CAUSE THE STAMPEDE FIRST. The measurement is the lesson.
# ==================================================================
# One popular key expires. Every in-flight request misses. Every one
# of them reads the source of truth, as cache-aside says it should.
#
# before expiry: 1 DB query per 300 s
# the moment after: 1,000 identical queries in the same instant
# the DB slows -> more concurrent requests -> more misses -> more
# queries. A POSITIVE FEEDBACK LOOP.
#
# This is how a healthy system with a 99% hit ratio falls over in
# seconds. And it is worse than it sounds, twice over:
# * the keys most likely to stampede are the MOST POPULAR ones -
# exactly those whose query is most expensive to run 1,000 times
# * a MASS EXPIRY (a deployment or warm-up script setting 1,000
# keys with the same TTL) stampedes TOGETHER. A self-inflicted
# thundering herd, on a schedule.
import random, time, json
# ==================================================================
# DEFENCE 1: JITTERED TTLs. One line. Costs nothing. Do it always.
# ==================================================================
BASE_TTL, JITTER = 300, 60
def jittered(base=BASE_TTL, jitter=JITTER):
return base + random.randint(0, jitter)
mc.set(key, blob, expire=jittered())
#
# This completely removes the MASS-EXPIRY case, and it should be the
# DEFAULT IN YOUR CACHE WRAPPER rather than something remembered at
# each call site. A wrapper is the difference between a policy and
# an intention.
# ==================================================================
# DEFENCE 2: A REFRESH LOCK = REQUEST COALESCING.
# ==================================================================
def read_coalesced(sku, lock_ttl=10, wait_ms=50, tries=6):
key = f"catalogue:{ns('catalogue')}:product:{sku}"
lock = f"lock:{key}"
cached = mc.get(key)
if cached is not None:
return json.loads(cached)
# `add` SUCCEEDS FOR EXACTLY ONE REQUESTER. That is what makes it
# a lock, and it is the whole mechanism.
if mc.add(lock, b"1", expire=lock_ttl):
try:
row = db_read_product(sku) # ONE query. Not 1,000.
if row is not None:
mc.set(key, json.dumps(row), expire=jittered())
else:
mc.set(key, b"__MISSING__", expire=30) # negative
return row
finally:
mc.delete(lock) # release promptly
else:
# A LOSER. Three honest options - pick one and state it:
# (a) wait briefly and re-read <- below
# (b) return a slightly stale value (defence 3)
# (c) return a degraded response immediately
for _ in range(tries):
time.sleep(wait_ms / 1000)
cached = mc.get(key)
if cached is not None:
return None if cached == b"__MISSING__" else json.loads(cached)
# The holder died, or the query is slower than our patience.
# Read through rather than fail - better a slow answer than
# an error:
return db_read_product(sku)
# THE FAILURE MODE TO HANDLE: the lock holder dies. The lock TTL must
# be SHORT ENOUGH that progress resumes and LONG ENOUGH to cover the
# query. Demonstrate the holder dying in the lab and show recovery
# after lock_ttl - that number is a design decision, not a default.
# ==================================================================
# DEFENCE 3: SERVE STALE WHILE REVALIDATING. Nobody waits.
# ==================================================================
# Two keys: the value with a LONG TTL, a freshness marker with a
# SHORT one.
SOFT, HARD = 300, 3600
def read_stale_while_revalidate(sku, executor):
v = ns("catalogue")
key = f"catalogue:{v}:product:{sku}"
fresh = f"fresh:{key}"
lock = f"lock:{key}"
cached = mc.get(key)
if cached is not None and mc.get(fresh) is not None:
return json.loads(cached) # fresh: done
if cached is not None:
# STALE BUT PRESENT. Return it NOW; refresh behind the
# request. One requester wins the lock, so the DB sees ONE
# query - and NOBODY WAITS.
if mc.add(lock, b"1", expire=30):
executor.submit(_refresh, sku, key, fresh, lock)
return json.loads(cached)
# Genuinely cold: no choice but to read through, coalesced.
return read_coalesced(sku)
def _refresh(sku, key, fresh, lock):
try:
row = db_read_product(sku)
if row is not None:
mc.set(key, json.dumps(row), expire=HARD)
mc.set(fresh, b"1", expire=jittered(SOFT, 60))
finally:
mc.delete(lock)
#
# The cost is serving data KNOWN to be briefly stale. For a product
# catalogue that is almost always the right trade. For a bank balance
# it is not. SAY WHICH, PER KEY TYPE.
# ==================================================================
# NEGATIVE CACHING - and CACHE PENETRATION.
# ==================================================================
MISSING = b"__MISSING__"
def read_with_negative(sku):
key = f"catalogue:{ns('catalogue')}:product:{sku}"
cached = mc.get(key)
if cached == MISSING:
return None # cached ABSENCE. No DB query.
if cached is not None:
return json.loads(cached)
row = db_read_product(sku)
if row is None:
# A SHORT TTL, because the row MAY APPEAR. 30-60 s, not 300.
mc.set(key, MISSING, expire=30)
return None
mc.set(key, json.dumps(row), expire=jittered())
return row
#
# CACHE PENETRATION: an attacker requests a stream of RANDOM
# NON-EXISTENT identifiers, specifically to bypass your cache and
# load your database. Without negative caching THAT ATTACK WORKS
# PERFECTLY and costs the attacker nothing.
#
# Measure it: 10,000 requests for random missing ids, with and
# without. The DB load difference is the lesson.
#
# For very large key spaces, a Bloom filter in front ("definitely not
# present") bounds it further - at the cost of maintaining the
# filter. Mention it; do not build it on a first pass.
# ==================================================================
# THE CACHE GOING DOWN MUST NOT TAKE THE SITE DOWN.
# ==================================================================
mc = HashClient([("127.0.0.1", 11211)],
timeout=0.2, # a FAST failure, not a hang
connect_timeout=0.2,
ignore_exc=True, # errors -> treated as a MISS
retry_attempts=1, retry_timeout=2,
dead_timeout=10) # stop asking a dead node
#
# With a 200 ms timeout, a hung Memcached costs 200 ms per request
# rather than hanging the worker. Without ignore_exc, a cache outage
# is a SITE outage - which is the single most common way a cache
# makes availability WORSE instead of better.
#
# Then verify it: STOP MEMCACHED while the load runs. The service
# must keep serving, degraded. Measure the degraded latency and
# whether the database survives it - which is Module 5's cold cache
# problem arriving early.
# ==================================================================
# STALENESS, STATED HONESTLY.
# ==================================================================
# Every cached value is POTENTIALLY STALE. The useful question is not
# "how do we prevent staleness" but "HOW STALE CAN THIS GET, AND IS
# THAT ACCEPTABLE FOR THIS DATA".
#
# product name/description 5 min stale: fine
# product price 30 s: acceptable? ASK. It is a
# commercial decision, not a technical
# one, and somebody owns it.
# stock level do NOT cache the authoritative value;
# cache "in stock / low / out" with a
# short TTL and check at checkout
# user permissions do not cache, or cache for seconds -
# a revoked permission must take effect
# session data NOT in Memcached alone: a restart
# logs everyone out
#
# A design that can answer this per key is a good design. One that
# assumes the cache is fresh is wrong, specifically in the places
# where it matters.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.