Caching in front of the database
Cache-aside with Redis: the race that leaves a stale value forever, the invalidation strategies that close it, and the day the cache becomes the thing holding the database up
Product pages are cached in Redis with no TTL. Reads use cache-aside: GET, and on a miss SELECT from Postgres and SET. A price change runs UPDATE, commits, then DEL on the key. Can a page show the old price for longer than a moment after the update has committed?
Every chapter so far made the database answer faster: indexes, the planner, replicas, partitions. This one puts something in front of it so that most reads never reach it. A cache is the cheapest capacity you can buy, and it is the source of a class of bugs the database alone never had: values that are wrong, and stay wrong, while every individual component behaves correctly.
You need the cache-aside lesson for the mechanism; this chapter is about running it in front of a real database, with real invalidation, replicas and failure modes.
What the cache buys, and what it costs
Take the shop’s product page: the product, its stock and the number sold. In Postgres that is a join plus an aggregate over order_items, tens of milliseconds at scale 0.1 without an index on product_id. A Redis GET over a local network is 0.1 to 0.5 ms. Two numbers decide everything else:
- Effective latency is
h × hit + (1 − h) × miss. At a hit ratiohof 95%, a 0.3 ms hit and a 30 ms miss give about 1.8 ms on average, and your p99 is still the miss. - Database read load is
(1 − h) × reads. Going from 95% to 99% hits does not improve latency much, but it cuts the reads reaching Postgres by a factor of five.
The second number is the trap. Once the database is sized for a 1% miss rate, it cannot serve the other 99%. A cache flush, a Redis failover to an empty replica, a deploy that changes the key format, or a TTL that expires a million keys in the same second sends up to a hundred times the usual read load to a database that was never provisioned for it. The cache has become load-bearing: losing it is a database outage. The Facebook incident above is that feedback loop with an extra twist, where errors caused deletes and deletes caused more load.
So a cache is a decision with two halves. The upside is latency and database capacity. The downside is a second copy of the data that can be stale, and a dependency that the database now cannot run without.
Cache-aside and its neighbours
Cache-aside (also called look-aside or demand-filled) is the default: the application reads the cache, on a miss reads the database and fills the cache, and on a write updates the database and then deletes the key. The cache knows nothing about the database. That is why it is popular: any key-value store works, and the cache can fail without taking writes down.
The alternatives move work around:
| pattern | read path | write path | what it costs |
|---|---|---|---|
| cache-aside | app: GET, on miss SELECT and SET | app: UPDATE, commit, DEL | stale-fill race; every writer must invalidate |
| read-through | cache library loads on miss | as cache-aside | same races, hidden inside a library |
| write-through | from cache | write cache and database together | a failure between the two leaves them different; two-system writes are not atomic |
| write-back | from cache | write cache, flush to database later | fast writes, data loss on cache failure; the write-policies lesson has the trade-off |
For a cache in front of Postgres, write-back is almost never right: you would be moving durability from a system built for it to one that is not. Write-through is tempting for small, hot objects, but it is a dual write, and the chapter on change data capture and the outbox pattern in module four treats dual writes as the bug they are. Cache-aside with careful invalidation is where most teams end up.
Delete, do not set
On a write, it looks natural to SET the new value into the cache instead of deleting the key. Do not. Two writers can commit to Postgres in the order A then B and reach Redis in the order B then A. The cache now holds A’s value, which is older than the database, and no future event corrects it. Deletes are idempotent and order-independent: whichever arrives last, the result is an empty key and the next read loads the truth. The Memcache paper gives the same reason for the same choice.
Delete after the commit, not before
Delete before the commit, and a reader can miss, read the old row (your transaction has not committed, so it is invisible), and fill the old value before you commit. Delete inside the transaction and the same thing happens. The delete belongs after COMMIT returns. If your framework wraps the request in a transaction, find its after-commit hook. Even then a delete can fail (Redis unreachable, the process crashes between the commit and the delete), which is the first reason for a TTL.
The stale-fill race
Deleting after the commit leaves one race open, the one from the Predict. Watch it in the simulation:
function read(key) {
const hit = cache.get(key);
if (hit) return hit.value;
const row = db.get(key); // may be the old row...
cache.set(key, row); // ...written after the writer's DEL
return row.value;
}
function write(key, value) {
db.put(key, value);
cache.del(key); // runs once; a late SET undoes it
}// Lease (memcached-style): a miss hands out a token; DEL revokes it.
function read(key) {
const r = cache.getOrLease(key); // { value } | { lease }
if (!r.lease) return r.value;
const row = db.get(key);
cache.setIfLease(key, row, r.lease); // no-op if a DEL ran since the miss
return row.value;
}
function write(key, value) {
db.put(key, value);
cache.del(key); // also revokes outstanding leases
}
// Alternative: versioned fill. The writer sets { value, version } with
// setIfNewer, and a reader's late fill of an older version is ignored. Run STALE FILL: reader A misses and reads version 1, writer B updates to version 2 and deletes the key, then A fills version 1. The invariant cache never holds a value older than the last acknowledged write goes red and stays red. LUCKY TIMING is the same code in a different order, and it is fine; that is why the race survives testing. SHORT TTL does not prevent the stale fill. It bounds how long it lasts. FIX: LEASED FILL refuses A’s late write.
No TTL, delete-on-write. Run every step of A and B in an order that leaves the cache holding the old name after the write is acknowledged.
GOAL: both finish and the cache holds v1 while the DB has v2
The window is the time between the reader’s SELECT and its SET. In a healthy service that is a millisecond, and the race is rare. It gets common exactly when things are already going wrong: a garbage-collection pause, a CPU-starved pod, a slow Redis, a database under load returning slowly. At Facebook’s scale “rare” was often enough that they built a mechanism for it.
Four ways to bound or close it
A TTL bounds the damage. Every entry expires, so a stale fill lasts at most one TTL. This is the backstop you always want, and it is not a fix: during the TTL every read sees the wrong value. Choose it by asking how long the business can tolerate a wrong value for this key, not by how long you would like hits to last.
A lease closes it. On a miss the cache hands out a token for that key. A delete revokes outstanding tokens. A fill succeeds only with a valid token. Memcached at Facebook does this natively; on Redis you build it with SET lease:key token NX PX 10000 on the miss and a short Lua script that writes the value only if the lease still holds that token. The lab builds it in 15 lines.
A versioned fill closes it when the data carries a version (an updated_at, a version column, an LSN). The fill writes only if the cached version is older. On its own this fails after a delete, because an empty key has no version to compare against, so writers SET a small tombstone with the new version instead of deleting.
Delayed double delete deletes after the commit and again a few hundred milliseconds later. It shrinks the window to stalls longer than the delay. It is common in blog posts and it is a probability, not a guarantee. Prefer a lease.
Make the read path safe against a write that lands between your DB read and your cache fill. The grader pauses readThrough right after db.get, runs a full write, then resumes you. The cache must still match the DB afterwards, and a quiet read must still populate the cache.
Invalidation strategies
The second problem is knowing that a key needs deleting at all. Cache-aside assumes the application performs every write. In a real shop the price changes from the admin UI, a nightly import job, a pricing service another team owns, and an engineer running UPDATE in psql during an incident. Each writer that does not delete the key leaves a stale entry for one TTL.
| strategy | who deletes | what it misses | cost |
|---|---|---|---|
| TTL only | nobody; entries expire | everything, for up to one TTL | none; you accept staleness |
| app deletes after commit | the code path that wrote | every other writer; a crash between commit and delete | one call per write |
database trigger + NOTIFY |
Postgres, at commit, to a listener | notifications sent while the listener is disconnected | a trigger per table and a listener process |
| change data capture | a consumer of the WAL (logical decoding, Debezium) | nothing that commits, as long as the slot is retained | a replication slot, a consumer to run and monitor |
| versioned keys | nobody; readers look up the current version and read product:42:v17 |
nothing; old versions age out | an extra lookup per read, usually in the cache itself |
NOTIFY is the cheapest way to get the database involved. A row trigger calls pg_notify('cache_inval', 'product:42'). Postgres queues the notification inside the transaction and delivers it to every session that has run LISTEN cache_inval only when the transaction commits, and drops it if the transaction rolls back. That is exactly the after-commit timing you want, enforced by the database. The weakness is that notifications are not stored: a listener that is restarting misses them, so keep the TTL as a backstop.
Change data capture is the durable version. A logical replication slot retains every committed change until the consumer confirms it, so an invalidator that crashes picks up where it left off. Facebook’s design is this pattern at scale: a daemon called mcsqueal on each database tails the commit log and broadcasts deletes to every cache cluster. The cost is the one the replication chapter warned about: a slot whose consumer stops holds WAL on the primary’s disk until it fills.
In practice the strong combination is: the app deletes after commit (fast, covers the common path), a database-driven invalidator catches every other writer, a lease closes the stale-fill race, and a TTL bounds whatever is left.
Read-your-writes, with a cache and a replica
Add read replicas and the race gets a second, slower cause. A customer changes their delivery address. The write commits on the primary, the key is deleted, and the confirmation page reads the address. It misses, and the fill reads from a replica that has not replayed the change yet. The cache now holds the old address, filled after the delete, and every read for one TTL serves it: a read-your-writes violation, and a stale fill that no lease prevents, because the filler’s lease was valid. The consistency chapter measured how often a replica serves a stale read; a cache multiplies the window by the TTL.
Three fixes, cheapest first:
- Fill from the primary. Misses read the primary, hits come from the cache. With a high hit ratio the primary barely notices, and the replica serves only queries that never go through the cache.
- Pin the writer. After a session writes, record the time or the commit LSN (
pg_current_wal_lsn()) in the session. For a few seconds, or until a replica’spg_last_wal_replay_lsn()has passed it, that session bypasses the cache and reads the primary. Other users may see the old value briefly, which is usually acceptable; the writer never does. - Write the writer’s own view. For data only its owner sees (a cart, a profile page), the write path may SET that user’s key after commit, because there is one writer per key and the reordering argument does not apply.
The Memcache paper solves the cross-region version with remote markers: a write from a non-primary region sets a marker that tells readers in that region to go to the primary region’s database until the replica has caught up.
Stampedes and hot keys
When a hot key expires, every concurrent request misses at once and every one of them runs the query. Twenty readers of a 30 ms page during one expiry is 20 identical queries. A popular product during a sale is hundreds. The stampede lesson has the full set of defences; the ones that matter in front of a database are:
- One loader per key. Leases do this too if the losers wait. Memcache returns a token at most once every 10 seconds per key and tells other clients to wait briefly and retry; on a week of keys prone to herds this took the peak database query rate from 17 000 per second to 1300 per second. A Redis
SET NXlock with a short expiry does the same job. - Serve stale while one request refreshes. Store a soft expiry inside the value, longer real TTL outside it.
- Jitter TTLs. A batch job that warms 100 000 keys with the same TTL schedules a herd for exactly one TTL later. Add 10 to 20% random spread; the TTL jitter and negative caching lesson also covers caching “not found” so that lookups for missing ids do not all reach the database.
A single hot key also concentrates load on one Redis node, whatever the cluster size. The answers are the same as for a hot shard: a short-lived copy in each application process (an in-process cache with a TTL of a second or two absorbs most of it), or several copies of the key under different names.
Running the cache
- Memory and eviction. Set
maxmemoryand a policy. For a pure cache,allkeys-lruorallkeys-lfuevicts cold keys when memory fills. The default policy,noeviction, makes every write fail withOOM command not allowedinstead, which in cache-aside means misses keep hitting the database because fills fail. Do not mix cache keys and data you cannot lose (sessions you cannot recreate, queues) in one Redis with an eviction policy. - Cold start. Plan for an empty cache: warm the hottest keys before shifting traffic, rate-limit fills, and make sure the database can survive the miss rate of a cold cache for the minutes it takes to warm, or shed load until it can.
- What not to cache. Values used to make a decision that must be correct: stock at checkout, a balance before a transfer, a permission check after a revocation. Read the cache for display; read the database, under a transaction, to decide.
- Measure. Hit ratio per key prefix, fill latency, evictions per second (
evicted_keysinINFO stats), and database reads per second. A falling hit ratio is the earliest warning that the database is about to see more load.
The feed-cache capstone puts these pieces in one timeline if you want to see them interact.
The lab stack
The lab uses the shop’s db from labs/databases/compose.yaml and one Redis container, d3-cache, on host port 6392 (the key-value chapter used 6390 and 6391). The Python code lives in a new directory, labs/databases/d3-cache/.
1. Start Redis and the client environment.
cd labs/databases
docker run -d --name d3-cache -p 6392:6379 redis:8.6.8 --maxmemory 64mb --maxmemory-policy allkeys-lru
docker exec d3-cache redis-cli CONFIG GET maxmemory-policy
mkdir -p d3-cache && cd d3-cache
python3 -m venv .venv
.venv/bin/pip install "psycopg[binary]==3.3.6" redis==8.1.0
docker compose -f ../compose.yaml exec db psql -U atlas -d shop -c '\di order_items*'CONFIG GET prints maxmemory-policy and allkeys-lru. The last command lists the indexes on order_items. If you see one on product_id from an earlier chapter, the page query below is fast and the gap between hit and miss is smaller; leave it, the mechanism is the same.2. Write the cache and measure it.
Create d3-cache/shop_cache.py. It has the plain cache-aside read, a leased read for step 4, and the write path:
"""Cache-aside for the shop's product page: Redis in front of Postgres."""
import json, os, time, uuid
import psycopg, redis
PG = os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")
r = redis.Redis(port=int(os.environ.get("REDIS_PORT", "6392")), decode_responses=True)
TTL = int(os.environ.get("CACHE_TTL", "300")) # seconds
stats = {"hit": 0, "miss": 0, "db": 0, "fill_refused": 0}
PAGE = """SELECT p.id, p.name, p.price_cents, i.on_hand,
(SELECT coalesce(sum(oi.qty), 0) FROM order_items oi WHERE oi.product_id = p.id) AS sold
FROM products p JOIN inventory i ON i.product_id = p.id WHERE p.id = %s"""
COLS = ["id", "name", "price_cents", "on_hand", "sold"]
def db():
return psycopg.connect(PG, autocommit=True)
def load(conn, pid):
stats["db"] += 1
row = conn.execute(PAGE, (pid,)).fetchone()
return dict(zip(COLS, row)) if row else None
def get_page(conn, pid, pause=0.0):
"""Plain cache-aside: GET; on a miss read Postgres and SET."""
key = f"product:{pid}"
hit = r.get(key)
if hit is not None:
stats["hit"] += 1
return json.loads(hit)
stats["miss"] += 1
page = load(conn, pid)
time.sleep(pause) # stands in for a GC pause or a slow network
r.set(key, json.dumps(page), ex=TTL)
return page
# Fill only if our lease is still there. A writer's DEL removes the lease, so a fill
# that started before the write is refused.
FILL_IF_LEASED = r.register_script("""
if redis.call('GET', KEYS[2]) == ARGV[1] then
redis.call('SET', KEYS[1], ARGV[2], 'EX', ARGV[3])
redis.call('DEL', KEYS[2])
return 1
end
return 0""")
def get_page_leased(conn, pid, pause=0.0):
key, lease = f"product:{pid}", f"lease:product:{pid}"
hit = r.get(key)
if hit is not None:
stats["hit"] += 1
return json.loads(hit)
stats["miss"] += 1
token = uuid.uuid4().hex
r.set(lease, token, nx=True, px=10_000) # someone else's lease wins; then our fill is refused
page = load(conn, pid)
time.sleep(pause)
if not FILL_IF_LEASED(keys=[key, lease], args=[token, json.dumps(page), TTL]):
stats["fill_refused"] += 1
return page
def set_price(conn, pid, cents):
conn.execute("UPDATE products SET price_cents = %s WHERE id = %s", (cents, pid)) # autocommit: committed here
r.delete(f"product:{pid}", f"lease:product:{pid}") # then invalidateCreate d3-cache/bench.py:
"""Product page latency: Postgres alone, cache misses, cache hits."""
import random, statistics, time
from shop_cache import db, load, get_page, r, stats
conn = db()
n = conn.execute("SELECT max(id) FROM products").fetchone()[0]
ids = random.Random(1).sample(range(1, n + 1), 200)
def timed(f):
out = []
for pid in ids:
t = time.perf_counter(); f(pid); out.append((time.perf_counter() - t) * 1000)
return f"p50 {statistics.median(out):7.2f} ms max {max(out):7.2f} ms"
r.delete(*[f"product:{i}" for i in ids])
print("postgres only ", timed(lambda pid: load(conn, pid)))
print("cache, cold ", timed(lambda pid: get_page(conn, pid)))
print("cache, warm ", timed(lambda pid: get_page(conn, pid)))
print(stats).venv/bin/python bench.pyproduct_id index (a few milliseconds at scale 0.01, or with the index). The cold pass costs the same plus a Redis round trip. The warm pass is 0.2 to 0.5 ms through Docker’s port forwarding, with a max close to its median: no page touches Postgres. The counters show 200 hits, 200 misses and 400 database loads (200 from the first line, 200 from the cold pass).3. Make the stale fill happen.
Create d3-cache/race.py. The reader misses, reads the row, then stalls for 500 ms before its SET; the writer commits a new price 100 ms in:
"""The stale-fill race, on purpose. python race.py [plain|lease]"""
import sys, threading, time
from shop_cache import db, load, get_page, get_page_leased, set_price, r
get = get_page_leased if sys.argv[1:] == ["lease"] else get_page
pid, a, b = 42, db(), db()
r.delete(f"product:{pid}", f"lease:product:{pid}")
old = load(b, pid)["price_cents"]
def reader(): # misses, reads the old row, then stalls for 500 ms before the SET
get(a, pid, pause=0.5)
def writer(): # 100 ms later: commit a new price, delete the key
time.sleep(0.1)
set_price(b, pid, old + 100)
ts = [threading.Thread(target=reader), threading.Thread(target=writer)]
[t.start() for t in ts]; [t.join() for t in ts]
time.sleep(0.1)
cached, real = get(a, pid)["price_cents"], load(b, pid)["price_cents"]
print(f"database {real}, cache serves {cached}, ttl {r.ttl(f'product:{pid}')} s ->", "STALE" if cached != real else "fresh")
set_price(b, pid, old) # put the price back.venv/bin/python race.pydatabase N, cache serves N-100, ttl 300 s -> STALE (the numbers depend on product 42’s price). The write committed and the delete ran, in the right order, and the cache still serves the old price, with five minutes left to live. Run it three times: it is stale every time, because the pause makes the bad interleaving certain. In production the pause is a GC or a slow network, and the result is the same, only rarer.4. Close it with a lease.
.venv/bin/python race.py lease-> fresh. The reader took a lease on its miss; the writer’s DEL removed the lease along with the key; when the reader tried to fill, the Lua script found no lease with its token and wrote nothing. The next read missed and loaded the new price. Read FILL_IF_LEASED again: the check and the write run inside one script, so no other command can run between them, which is what makes it correct. In Redis Cluster both keys must hash to the same slot, so you would name them product:{42} and lease:product:{42}.5. Invalidate from the database.
The app’s set_price deletes the key. An engineer in psql does not. Make Postgres announce every committed change to a product or its stock. Create d3-cache/invalidate.sql:
CREATE OR REPLACE FUNCTION cache_invalidate() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
PERFORM pg_notify('cache_inval', 'product:' || (to_jsonb(NEW) ->> TG_ARGV[0]));
RETURN NULL;
END $$;
DROP TRIGGER IF EXISTS cache_invalidate ON products;
DROP TRIGGER IF EXISTS cache_invalidate ON inventory;
CREATE TRIGGER cache_invalidate AFTER UPDATE ON products FOR EACH ROW EXECUTE FUNCTION cache_invalidate('id');
CREATE TRIGGER cache_invalidate AFTER UPDATE ON inventory FOR EACH ROW EXECUTE FUNCTION cache_invalidate('product_id');And d3-cache/invalidator.py:
"""Delete cache keys when Postgres says a row changed. Notifications arrive at COMMIT."""
import time
import psycopg
from shop_cache import PG, r
with psycopg.connect(PG, autocommit=True) as conn:
conn.execute("LISTEN cache_inval")
print("listening on cache_inval", flush=True)
for n in conn.notifies():
r.delete(n.payload, "lease:" + n.payload)
print(f"{time.strftime('%H:%M:%S')} DEL {n.payload}", flush=True)docker compose -f ../compose.yaml exec -T db psql -U atlas -d shop < invalidate.sql
.venv/bin/python invalidator.py # terminal 2, leave it runningIn terminal 1, fill the cache for product 7, then change its stock from psql in a transaction that waits three seconds before committing:
.venv/bin/python -c "from shop_cache import *; print(get_page(db(), 7)['on_hand'])"
docker compose -f ../compose.yaml exec db psql -U atlas -d shop -c \
"BEGIN; UPDATE inventory SET on_hand = on_hand - 1 WHERE product_id = 7; SELECT pg_sleep(3); COMMIT;"
.venv/bin/python -c "from shop_cache import *; print(get_page(db(), 7)['on_hand'], stats)"DEL product:7 three seconds after you run the UPDATE, at the moment of the COMMIT, not when the UPDATE ran. The last command prints the stock one lower and 'miss': 1: the psql write, which knew nothing about Redis, invalidated the key. Run the same psql command with ROLLBACK in place of COMMIT and terminal 2 prints nothing: a rolled-back change sends no notification.6. Lose an invalidation.
Stop the invalidator (Ctrl-C in terminal 2), fill product 7 again with the first command from step 5, run the psql UPDATE again, then start the invalidator and read the page.
listening on cache_inval and nothing else. The page shows the old stock, and will for the rest of its 300-second TTL. NOTIFY is not stored for absent listeners. This is the gap that change data capture closes with a replication slot, and the reason the TTL stays even when invalidation is good.d3-cache/stampede.py: set os.environ["CACHE_TTL"] = "2" before import shop_cache as sc, then start 32 threads that each open sc.db() and call sc.get_page(conn, 42) in a loop for 10 seconds, and print sc.stats. Expect five expiries and, at scale 0.1, tens of database loads per expiry instead of one: every thread that misses during the 30 ms load runs the same query. Swap in sc.get_page_leased: the count of database loads barely changes and fill_refused is nearly as large, because the lease stops stale fills but every loser still reads the database. Make losers that fail the SET NX sleep 50 ms and retry the GET instead of loading, and loads drop to about one per expiry. That is the memcache lease’s second job. Clean up with docker rm -f d3-cache, and drop the triggers and their function with DROP TRIGGER cache_invalidate ON products; DROP TRIGGER cache_invalidate ON inventory; DROP FUNCTION cache_invalidate();. Left in place, they would send a notification for every product and stock update in later chapters.The shop caches product pages in Redis with a 10-minute TTL and the app deletes the key after it updates a price. Merchants complain that price changes sometimes take up to ten minutes to show, and twice last month a customer was charged a price different from the page. Prices are changed by the admin UI, a nightly supplier import job written in another language, and a pricing service owned by another team. Postgres has two async replicas; cache misses read from a replica. What do you change?
- PAPER Scaling Memcache at Facebook Nishtala et al., 2013
The design behind most of this chapter, at a scale where rare races happen every second: leases for stale sets and herds, mcsqueal invalidation from the database's commit log, and read-after-write across regions. Skip the network-level sections unless you run memcached yourself. Read: section 3.2.1 (leases), section 4.1 (invalidation from the commit log), section 5 (remote markers); skim the rest.
- POST More Details on Today's Outage Robert Johnson, 2010
The incident in the Why, in one page. Read it for the feedback loop: errors interpreted as invalid values caused deletes, and deletes caused more load. Short, and still the clearest account of a cache taking a database down.
- BOOK Designing Data-Intensive Applications, chapter 5: Problems with Replication Lag Martin Kleppmann, 2017
The session guarantees that a cache filled from replicas breaks, with the standard fixes. Pairs with the read-your-writes section above. Read: chapter 5, the section on replication lag: read-your-writes, monotonic reads, consistent prefix reads.
- DOC Redis: key eviction
maxmemory, every eviction policy and what each does when memory fills, including why noeviction is wrong for a cache. Read the part on approximated LRU before you trust LRU to keep your hot keys.
- DOC PostgreSQL 17: NOTIFY
The delivery rules the lab relies on: notifications are sent at commit, dropped on rollback, folded when identical within a transaction, and not kept for listeners that are not connected. Also the 8000-byte payload limit and the queue size.
- DOC Redis: client-side caching
How Redis tells clients to drop keys they cached in-process (tracking and broadcasting modes). Read it when a hot key needs an in-process copy and you want invalidation instead of a short TTL.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.