Cache-aside is the pattern, and the write path is where it goes wrong.
The read path: look in the cache; on a hit, return it; on a miss, read the source of truth, store it in the cache with a TTL, and return it. Straightforward.
The write path: update the source of truth, then delete the cache entry. Not update it. The reason is a specific race: a reader that missed the cache is holding a value it read from the database a moment ago; if a writer updates the database and then writes the new value to the cache, the slow reader can then write its older value over the top, and the cache holds a stale value with a full TTL ahead of it. Deleting cannot be stale - the next read repopulates from the source of truth. This is the single most important correctness rule in caching and it is routinely got wrong.
The remaining race, which you should know and usually accept: a reader can still populate the cache with a value read just before a write committed. The defences are a short TTL (bounding how long the staleness lasts), a delete-after-a-delay in addition to the immediate one, or CAS-based population. For most data, a short TTL is the right answer and the complexity of the alternatives is not worth it.
Serialisation. Values are opaque bytes, so you choose. JSON is readable, debuggable and slow; MessagePack and Protocol Buffers are compact and fast and opaque; language-native serialisation (Python pickle, PHP serialize, Java serialisation) is convenient and is a security problem if the cache can be written by anything untrusted, because deserialising attacker-controlled bytes is remote code execution in several languages. The flags field exists to record which format a value uses, which is how you migrate formats without a flush.
Compression is worth measuring rather than assuming: it trades CPU for memory and network, and most clients will do it above a size threshold.
Key namespaces are how you keep an instance comprehensible: prefix:entity:id:variant, with a version or build component so that a deployment can invalidate a whole class of keys. catalogue:v3:product:SKU-001 means shipping v4 makes every old entry unreachable and lets it expire naturally - no enumeration, no flush.
Invalidation strategies, in increasing order of precision:
- TTL only. Simple, correct in the sense that staleness is bounded, and fine for data where a short staleness window is acceptable.
- Explicit delete on write. Precise, and requires that every write path knows which keys to delete - which is the maintenance burden.
- Namespace versioning. A counter key whose value is part of every derived key. Incrementing it invalidates an entire group in one operation, with no enumeration - and since Memcached has no way to list or pattern-match keys, this is the only way to invalidate a group. It is the most useful technique in this module.
Multi-get matters more than it appears. One get with 50 keys is one round trip; 50 gets are 50. On a 0.5 ms network that is 0.5 ms against 25 ms, which on a page assembling 200 cached fragments is the difference between fast and unusable. The complication: in a multi-node pool the client must group keys by the node each hashes to and issue one multi-get per node - good clients do this, and knowing it happens explains why multi-get latency depends on pool size.
Laboratory exercise 2 - two models, measured.
Design two caching models for the capstone's product catalogue. The contrast: one caching fine-grained entities (one key per product, assembled per page) and one caching coarse composites (one key per rendered category page).
Implement both. Build the operations: read a product, read a category listing of 50 products, read a search result, update a product, and update a category.
Measure both on four axes: hit ratio, round trips per page, memory used, and the invalidation blast radius - how many cache entries one product update invalidates in each model. That last axis is the interesting one and the usual deciding factor.
Implement all three invalidation strategies, including namespace versioning, and demonstrate invalidating a whole category in one operation.
Demonstrate the stale-write race: with a deliberate delay, show a reader writing an old value over a writer's new one when the write path updates the cache; then show the delete-based path not having the problem.
Compare serialisation formats on size and time, and demonstrate migrating formats using flags.
Finally, compare 50 individual gets with one multi-get, in a single-node and then a three-node pool.
Deliverable: both models, all operations, the four-axis comparison table, the three invalidation strategies with the one-operation group invalidation, the stale-write race demonstrated and fixed, the serialisation comparison, the multi-get measurements for both pool sizes, and a page arguing for one model.
# ------------------------------------------------------------------
# CACHE-ASIDE. The read path is easy. The write path is where it
# goes wrong.
# ------------------------------------------------------------------
import json, time, hashlib
from pymemcache.client.hash import HashClient
mc = HashClient([("127.0.0.1", 11211)], use_pooling=True, timeout=0.2,
connect_timeout=0.2, ignore_exc=True)
# ^^^^^^^^^^^^^^^^ a cache failure
# must NOT be an application failure. Treat it as a miss and read
# through. This one flag is the difference between a cache outage and
# a site outage.
TTL = 300
def read_product(sku):
key = f"catalogue:{ns('catalogue')}:product:{sku}"
cached = mc.get(key)
if cached is not None:
return json.loads(cached)
row = db_read_product(sku) # the source of truth
if row is not None:
mc.set(key, json.dumps(row), expire=TTL)
return row
# ------------------------------------------------------------------
# THE WRITE PATH: DELETE, DO NOT UPDATE.
# ------------------------------------------------------------------
def write_product(sku, changes):
db_write_product(sku, changes) # 1. source of truth FIRST
mc.delete(f"catalogue:{ns('catalogue')}:product:{sku}") # 2. DELETE
# WHY NOT UPDATE? This race:
# t0 reader misses, reads the DB -> {"price": 10}
# t1 writer updates the DB -> {"price": 20}
# t2 writer SETS the cache -> {"price": 20} correct
# t3 the SLOW reader SETS the cache -> {"price": 10} STALE,
# with a FULL TTL ahead of it
#
# A DELETE cannot be stale. The next read repopulates from the source
# of truth. This is the single most important correctness rule in
# caching, and it is routinely got wrong.
# THE REMAINING RACE, which you should know and usually accept:
# a reader can still populate the cache with a value it read JUST
# BEFORE the write committed. Defences:
# * a SHORT TTL - bounds how long the staleness lasts <- usually
# the right answer, and the cheapest
# * delete again after a short delay ("delayed double delete")
# * CAS-based population (below)
# For most data the short TTL is correct and the alternatives are not
# worth their complexity. SAY WHICH YOU CHOSE.
# ------------------------------------------------------------------
# NAMESPACE VERSIONING: the only way to invalidate a GROUP.
# ------------------------------------------------------------------
# Memcached has NO key enumeration and NO pattern matching. So you
# cannot "delete all product keys". A version counter in the key
# solves it in ONE operation.
def ns(name):
k = f"ns:{name}"
v = mc.get(k)
if v is None:
mc.add(k, b"1") # add, not set: a race here is
v = mc.get(k) or b"1" # harmless - whoever wins, wins
return v.decode()
def invalidate_namespace(name):
# ONE command invalidates EVERY key built with this namespace.
# The old entries become unreachable and expire naturally - no
# enumeration, no flush, no walking the keyspace.
if mc.incr(f"ns:{name}", 1) is None:
mc.set(f"ns:{name}", b"2")
# catalogue:7:product:SKU-001 <- all unreachable the moment the
# catalogue:7:category:keyboards namespace becomes 8
#
# THE MOST USEFUL TECHNIQUE IN THIS MODULE. It also gives you
# deployment-scoped invalidation for free: put the build id in the
# key and a deploy invalidates everything it should.
# ------------------------------------------------------------------
# MULTI-GET: matters more than it looks.
# ------------------------------------------------------------------
def read_products(skus):
v = ns("catalogue")
keys = {f"catalogue:{v}:product:{s}": s for s in skus}
found = mc.get_many(list(keys)) # ONE round trip per NODE
out, misses = {}, []
for key, sku in keys.items():
if key in found:
out[sku] = json.loads(found[key])
else:
misses.append(sku) # MISSES ARE SIMPLY ABSENT -
# you must diff to find them
if misses:
rows = db_read_products(misses) # ONE query for all misses
pairs = {f"catalogue:{v}:product:{s}": json.dumps(r)
for s, r in rows.items()}
mc.set_many(pairs, expire=TTL)
out.update(rows)
return out
#
# 50 individual gets, 0.5 ms RTT -> 25 ms
# one multi-get -> 0.5 ms
# On a page assembling 200 cached fragments that is the difference
# between fast and unusable.
#
# THE COMPLICATION: in a MULTI-NODE pool the client must GROUP KEYS
# BY NODE and issue one multi-get per node. Good clients do this
# automatically - which is why multi-get latency depends on pool
# size, and why measuring it at one node and three nodes (the lab)
# is worth doing.
# ------------------------------------------------------------------
# SERIALISATION. Record the format in FLAGS so you can migrate.
# ------------------------------------------------------------------
FLAG_JSON, FLAG_MSGPACK = 1, 2
def set_versioned(key, obj, fmt=FLAG_MSGPACK):
import msgpack
blob = msgpack.packb(obj) if fmt == FLAG_MSGPACK else json.dumps(obj).encode()
mc.set(key, blob, expire=TTL, flags=fmt)
def get_versioned(key):
import msgpack
r = mc.get(key, with_flags=True) # client API varies
if r is None: return None
blob, flags = r
if flags == FLAG_MSGPACK: return msgpack.unpackb(blob)
if flags == FLAG_JSON: return json.loads(blob)
return None # unknown format: treat as a miss
# This is how you change serialisation format WITHOUT a flush: write
# the new format, read both, and let the old entries expire.
#
# JSON readable, debuggable, SLOW, larger
# MessagePack compact, fast, opaque
# Protobuf compact, fast, needs a schema
# pickle / convenient, AND A SECURITY PROBLEM if anything
# PHP serialize / untrusted can write to the cache: deserialising
# Java ser. attacker-controlled bytes is REMOTE CODE EXECUTION in
# several languages. Never on a cache reachable by
# anything you do not control.
# ------------------------------------------------------------------
# CAS: safe read-modify-write on a cached value.
# ------------------------------------------------------------------
def increment_view_count(sku, attempts=5):
key = f"views:{sku}"
for _ in range(attempts):
result = mc.gets(key)
if result is None or result[0] is None:
if mc.add(key, b"1", expire=86400):
return 1
continue # someone else created it
value, cas = result
new = int(value) + 1
if mc.cas(key, str(new).encode(), cas, expire=86400):
return new # the token matched
# EXISTS: somebody wrote first. Re-read and retry.
raise RuntimeError("CAS contention")
#
# For a pure counter, `incr` is simpler, atomic and needs no retry.
# CAS is for when you must READ, COMPUTE and WRITE a structured value
# - and note the values are still just bytes, so you deserialise,
# modify, reserialise, and the retry cost is real under contention.
# ------------------------------------------------------------------
# Invalidation strategies, in increasing precision.
# ------------------------------------------------------------------
# 1. TTL ONLY simple; staleness BOUNDED by the TTL.
# Fine wherever a short stale window is OK -
# which is more data than people assume.
# 2. DELETE ON WRITE precise; EVERY write path must know which
# keys to delete. That is the maintenance
# burden, and the usual source of bugs.
# 3. NAMESPACE VERSION a whole group in ONE operation, with no
# enumeration. The only way to do a group.
#
# Every cache decision trades FRESHNESS against LOAD against
# COMPLEXITY, and you cannot have all three. Pick per key, and be
# able to say why.
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.