The system. A high-traffic product catalogue in front of a deliberately slow database. Product pages, category listings, search results and a navigation tree, all cached. At least 5,000 requests per second of simulated traffic with a realistic popularity distribution - a few keys taking a large share, which is what makes the stampede real.
Three invariants must hold:
- No cached value is ever served after the underlying data has changed by more than the stated staleness window for its key type.
- No single key expiry causes more than one database query - proved by counting queries, not by inspection.
- The service continues to serve, degraded, when the cache is entirely unavailable - with the database surviving it.
Invariant 3 is the one this course exists for, and it has two halves. "The service keeps serving" is the easy half, handled by client timeouts and treating errors as misses. "The database survives it" is the hard half, and it is a capacity question that must be answered with a measurement rather than a hope.
What is assessed. 20% knowledge checks, 35% laboratory portfolio, 15% troubleshooting practical, 30% capstone. Three things carry the capstone.
Stampede protection, demonstrated by query counts. Your test must expire a popular key under full load and show the database receiving one query. A capstone that describes a refresh lock without a query count has not demonstrated anything - the mechanism is easy to write and easy to get subtly wrong, and the count is the only proof.
A measured cold-start and node-loss benchmark against a declared baseline. Declare it first: pool size, hashing scheme, request rate, popularity distribution, TTLs per key type, the database's measured query ceiling, and the hit ratio at steady state. Then measure: one node lost, and a full flush, with the recovery curve for each.
A capacity statement, and a defensible account of failure modes and cost. The capacity statement - database queries per second at steady state, with one node lost, and cold, against the measured database ceiling - is the central artefact. If the cold figure exceeds the ceiling, the design must say which mechanisms make the system survive anyway and treat them as load-bearing architecture rather than optimisations. And the staleness window for each key type must be stated as a decision somebody owns.
Deliverables: architecture diagram with the pool topology and hashing scheme; the cache key design with the TTL and invalidation strategy per key type; source code including the stampede defences, the client failure configuration and the warming tooling; reproducible load test and dataset; benchmark report with the node-loss and cold-start curves; the capacity statement; security review; recovery runbook; cost comparison of managed and self-managed; and a short design defence.
# ================= Invariants, as runnable checks ==================
# 1. STALENESS WITHIN THE STATED WINDOW, per key type. The window is
# a DECISION somebody owns, not a technical default:
STALENESS = {
"product:name": 300, # 5 min: fine
"product:price": 30, # a COMMERCIAL decision. Ask. Record
# who agreed to it.
"product:stock": 0, # NOT CACHED authoritatively. Cache
# "in/low/out" with a 10 s TTL and
# check at checkout.
"category:listing": 600,
"search:results": 120,
"navigation:tree": 3600,
}
# Verified by a test that writes to the database, waits the window,
# and asserts the cache has caught up.
# 2. ONE DATABASE QUERY PER KEY EXPIRY. Proved by COUNTING.
# A capstone that DESCRIBES a refresh lock without a query count
# has demonstrated nothing - the mechanism is easy to write and
# easy to get subtly wrong.
# instrument the DB layer with a counter
# warm one popular key, let it expire under 5,000 rps
# assert the counter increased by EXACTLY 1
# Expected: 1. Not 2. Not 900.
# 3. THE SERVICE SERVES WHEN THE CACHE IS GONE - AND THE DATABASE
# SURVIVES IT. Two halves, and the second is the hard one.
# ================= Declare the baseline BEFORE measuring ===========
#
# Pool: 5 x memcached, -m 4096, -c 4096, -o modern
# Hashing: KETAMA (consistent) - verified, not assumed
# Client: timeout 200 ms, ignore_exc, dead_timeout 0
# (hold the ring: no key in two places - a STALE PRICE
# is worse than a miss, and that is the reason)
# Load: 5,000 rps, Zipf popularity (top 100 keys = 40% of
# traffic) - the skew is what makes the stampede real
# DB: measured ceiling 3,500 qps <- MEASURED, not assumed
# Steady hit: 98.7%
#
# Defences, all four:
# jittered TTLs base + rand(0, 20% of base)
# refresh lock add, 10 s TTL, losers wait 50 ms x 6
# serve-stale hard TTL 4x soft, background refresh
# negative cache __MISSING__, 30 s
# fill admission limit 20 concurrent
# L1 in-process 2 s TTL, 5,000 entries
#
# Claim:
# product page (hit) p99 < 5 ms
# product page (miss) p99 < 250 ms
# category listing p99 < 15 ms
# one node lost hit ratio >= 78%, DB <= 2,600 qps,
# p99 < 60 ms, recovery < 5 min
# FULL FLUSH service stays up, DB <= 3,000 qps,
# p99 < 400 ms, hit ratio back to 95%
# within 10 min
#
# And the numbers that explain it:
# evicted_time per slab class must EXCEED the TTLs
# evicted_unfetched / evictions should be low
# DB queries per key expiry must be 1
# ================= THE CAPACITY STATEMENT ==========================
# The central artefact of this capstone.
#
# steady state 5,000 rps x (1 - 0.987) = 65 DB qps
# one node of 5 5,000 rps x (1 - 0.79) = 1,050 DB qps
# COLD CACHE 5,000 rps x (1 - 0.00) = 5,000 DB qps
# measured DB ceiling = 3,500 qps
#
# => A COLD CACHE EXCEEDS THE DATABASE BY 1.43x.
#
# THEREFORE, and the design document must say this:
# * the FILL ADMISSION LIMITER caps concurrent fills at 20, which
# bounds DB load to ~20 x (1/0.2 s) = 100 qps regardless of
# request rate. Requests above that are DEGRADED, not queued.
# * the GRADUAL RAMP (5% -> 25% -> 100%) is REQUIRED in the
# cold-start runbook, not advisory.
# * the L1 in-process cache absorbs the top keys during the cold
# window, which the measurement shows is worth ~15 points of
# hit ratio in the first minute.
#
# These are LOAD-BEARING PARTS OF THE ARCHITECTURE, not
# optimisations. A design that omits them does not survive its own
# node replacement - and node replacement is routine.
# ================= The assembled read path =========================
def get_product_page(sku, executor):
# L1: in-process, 2 s. Survives a Memcached flush entirely.
v = l1_get(f"product:{sku}")
if v is not None:
return v
# L2: Memcached, with stale-while-revalidate + coalescing +
# negative caching + jitter, and a fill admission limit.
v = read_stale_while_revalidate(sku, executor)
if v is not None:
l1_set(f"product:{sku}", v, ttl=2)
return v
# The tiers are deliberately ordered so that the cheapest protection
# runs first and the database is behind every one of them.
# ================= Failure modes ==================================
# popular key expires A STAMPEDE. The feedback loop takes the
# DB down in seconds. Jitter + coalescing.
# PROVE IT WITH A QUERY COUNT.
# mass expiry after a deploy A SCHEDULED stampede. Jitter, always,
# applied in the WRAPPER not at call sites.
# one node lost ~20% invalidated with ketama, ~80% with
# MODULO. CHECK YOUR CLIENT'S DEFAULT -
# some are still modulo.
# node returns after redistributed keys now exist TWICE and
# redistribution the old copy is STALE. We hold the ring
# instead; a stale price is worse than a
# miss.
# cache entirely down ignore_exc + 200 ms timeout keeps the
# SERVICE up. The ADMISSION LIMITER is
# what keeps the DATABASE up. Both needed.
# flush_all by a person, a tool, or a key-namespace
# change in a deploy. Same as cold start.
# Ramp.
# evicted_time < TTL TTLs ARE FICTION. Add memory or cache
# less. Raising the TTL does NOTHING.
# item grows past 1 MB silently uncacheable, at a size nobody
# predicted. Monitor value sizes; cap
# what you cache.
# slab calcification after evictions high, memory free. slab
# a size distribution change automove, and watch per-class evictions
# after every deploy.
# connection limit reached clients REFUSED; looks like a network
# fault. app instances x pool vs -c.
# penetration attack random missing ids bypass the cache
# entirely. Negative caching, 30 s.
# uptime reset a restart nobody noticed, and therefore
# an unexplained DB spike. Alert on it.
#
# And the rule that outranks all of them:
# NOTHING IN THIS SYSTEM EXISTS ONLY IN MEMCACHED. Every cached
# value is reconstructible from the database, which is what makes
# invariant 3 achievable at all.
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.