To keep the architecture evolvable without sacrificing reliability, eliminate Cache-Aside read-write races using monotonic row `version` Compare-And-Swap (Lua CAS) in Redis or by moving cache population/invalidation to a single-writer CDC stream.
TL;DR30-second simplified summary▾
Core Mechanics: In a user profile service handling 30,000 reads/sec and 800 writes/sec against PostgreSQL 16 and Redis 7, classic Cache-Aside (UPDATE + redis.del on write; SELECT + redis.set on miss) has a 4-step interleaving bug.
Visual & Structural Flow: Depicts Preempted Cache-Miss Reader Overwrites Newer Commit v2 (Miss Reader -> Redis 7 -> Postgres 16 -> Writer (v2)); Monotonic Version Lua CAS Rejects Stale v1 Fills (Reader / Writer -> Redis Lua CAS -> Version Tombstone -> PostgreSQL 16 (BIGINT version)).
Trade-Offs & Production: Deleting the cache before DB commit widens the race window. Eliminate read-write and write-write races with zero read locks (< 5 ms p99): PostgreSQL BIGINT version + RETURNING version: Increment version atomically on every UPDATE.
Failure Modes & Application: Version-fenced invalidation is standard across high-read user and catalog services: User Profiles & Auth Sessions: Prevents reverted passwords, avatars, or MFA settings.
Why Cache-Aside read-write races silently revert user updates.
Why this matters: The mechanism: understand how Why Cache-Aside read-write races silently revert user updates works from first principles.
Think of Why Cache-Aside read-write races silently revert user updates as the intuition layer for Solving Dual-Write Cache Invalidation Races: The mechanism: understand how Why Cache-Aside read-write races silently revert user updates works from first principles.
In a user profile service handling 30,000 reads/sec and 800 writes/sec against PostgreSQL 16 and Redis 7, classic Cache-Aside (UPDATE + redis.del on write; SELECT + redis.set on miss) has a 4-step interleaving bug. Whenever a slow miss reader fetches v1, pauses for GC or scheduling, and writes v1 after a concurrent writer commits v2 and calls DEL, ~0.05% of updates (~35/day) silently revert.
Stale v1 pinned in Redis for 3,600 seconds.
Why this matters: The problem: see what breaks without Stale v1 pinned in Redis for 3,600 seconds under real concurrency or scale.
Once the preempted reader executes redis.set(key, v1, ex=3600) after the writer's DEL, two things break:
- 1-Hour Silent Stale State: All
30,000reads/sec serve oldv1until the 3,600s TTL expires. - Concurrent Writer Reordering (
v2vsv3): Two writers can also interleaveUPDATE v2,UPDATE v3,SET v3,SET v2, leavingv2in Redis.
Preempted Cache-Miss Reader Overwrites Newer Commit v2
Because Redis SET has no version guard, a delayed miss reader overwrites the deleted key with stale v1.
- Problem
- How to implement Solving Dual-Write Cache Invalidation Races without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- To keep the architecture evolvable without sacrificing reliability, eliminate Cache-Aside read-write races using monotonic row
versionCompare-And-Swap (Lua CAS) in Redis or by moving cache population/invalidation to a single-writer CDC stream. - Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Solving Dual-Write Cache Invalidation Races experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Why Delayed Double Delete and SETNX fail under >500 ms pauses.
Why this matters: The problem: see what breaks without Why Delayed Double Delete and SETNX fail under >500 ms pauses under real concurrency or scale.
Deleting the cache before DB commit widens the race window.
Using Delayed Double Delete (DEL, sleep 500 ms, DEL) is only heuristic—any GC pause or replica lag > 500 ms still pins v1.
Why Delayed Double Delete and SETNX fail under >500 ms pauses
Enterprise solution: Monotonic Version Lua CAS (or Single-Writer CDC).
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Eliminate read-write and write-write races with zero read locks (< 5 ms p99):
- PostgreSQL
BIGINT version+RETURNING version: Incrementversionatomically on everyUPDATE. - Redis Lua Compare-And-Swap (
EVALSHA): Store{ver, data}in a Redis Hash; both writers and miss-readers populate Redis via a Lua script that rejects any write wherenew_ver <= cached_ver. - Short Version Tombstones on
DEL: If invalidating instead of write-through, write a tinyver=N, tombstone=1(EX 60) so a slowv1reader (ver < N) is still rejected. - Alternative: Single-Writer CDC: Stream
pgoutputWAL changes in LSN order to a single Redis updater.
Monotonic Version Lua CAS Rejects Stale v1 Fills
1.Zero Read Locks: Cache hits remain pure HGET/GET (<1ms); Lua CAS runs only on miss fills and writes.
2.Writer Reorder Safe: If v3 arrives before v2, Lua CAS keeps v3 and drops v2.
3.CDC Single Writer: For zero app-level dual writes, let Debezium LSN order drive Redis updates.
Monotonic version CAS in Redis makes stale v1 overwrites mathematically impossible regardless of GC pause length.
-- Atomic Redis Lua CAS: only write if incoming version > cached/tombstone version
local key = KEYS[1]
local new_ver = tonumber(ARGV[1])
local payload = ARGV[2]
local ttl = tonumber(ARGV[3])
local cur = redis.call("HGET", key, "ver")
if cur and tonumber(cur) >= new_ver then
return 0
end
redis.call("HSET", key, "ver", new_ver, "data", payload)
redis.call("EXPIRE", key, ttl)
return 1
Where version-fenced caches protect consistency.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Version-fenced invalidation is standard across high-read user and catalog services:
- User Profiles & Auth Sessions: Prevents reverted passwords, avatars, or MFA settings.
- Multi-Tier L1/L2 Caches: Propagates monotonic version numbers across Caffeine L1 and Redis L2.
- Search & Derived Views: Uses DB
version/ LSN watermarks to drop out-of-order async updates.
Practice: Make the trade-off yourself.
Why does Delayed Double Delete (DEL -> sleep 500ms -> DEL) not fully guarantee against Cache-Aside stale fills?