Cache consistency
medium 26 minCache consistency is about how closely cached copies follow the source of truth.
See it run
One value, v1 becoming v2. Watch what the cache holds, what the database holds, and who reads in between.
Operations
Strong, with locks
Readers and the writer of this key use the same lock.
Step 1 of 6
In sync
Cache and database both hold v1.
Step 1: In sync
def write(key, value): with lock(key): # readers take it too db.write(key, value) cache.delete(key) return "confirmed"def read(key): with lock(key): return cache.get(key) or fill(key)- Stale reads
- None
- Price
- waiting
- Writers only
- a reader can slip in
The lock must cover readers too. Often it is simpler to read the database.
In the real world
The same cache consistency doing real jobs. Pick one and step through it.
Show from the cache, decide from the source.
Step 1 of 3
The page
The cache says 1 seat. Two people see it, and that is fine.
Step 1: The page
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Delete before write
criticalA reader refills the old value before the write commits.
Wrongcache.delete(key)db.write(key, value)Rightdb.write(key, value)cache.delete(key)No TTL because we invalidate
criticalOne lost delete and the value is wrong for ever.
Wrongcache.set(key, value)Rightcache.set(key, value, ttl=600)Deciding from the cache
criticalTwo orders see the same last item.
Wrongif cache.get("stock") > 0: accept()Rightn = db.execute("UPDATE stock SET n = n - 1 WHERE id = ? AND n > 0")if n == 1: accept()A version counter in the cache
majorThe late reader gets the highest number when it stores the oldest value.
Wrongversion = cache.incr("version")cache.set(key, (value, version))Rightvalue, version = db.read(key)fill_if_newer(key, value, version)
Interview tips
How to explain it
- A cache is a copy and can be late.
- Database first, then delete.
- TTL for lost deletes, versions for late readers.
Memory trick: STALE
- Sync and Timing.
- Atomicity and Locking.
- Expiry as the safety net.
Choose per value
- Money and stock decisions: the source.
- Own edits: read your own writes.
- Feeds and catalogues: eventual.
Be ready for
- A delete that fails.
- A replica that lags.
- A local cache that missed a message.