Skip to main content
← PROBLEMS / ARCHITECTURE
An end-to-end domain learning journey

Solving Dual-Write Cache
Invalidation Races.

Under Cache-Aside, a slow cache-miss reader that fetches v1 from the DB can get preempted while a writer commits v2 and deletes the cache, after which the reader writes stale v1 back into Redis.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

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.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

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. 1-Hour Silent Stale State: All 30,000 reads/sec serve old v1 until the 3,600s TTL expires.
  2. Concurrent Writer Reordering (v2 vs v3): Two writers can also interleave UPDATE v2, UPDATE v3, SET v3, SET v2, leaving v2 in Redis.
4-Step Cache-Aside Race

Preempted Cache-Miss Reader Overwrites Newer Commit v2

Miss ReaderRedis 7Postgres 16Writer (v2)1. GET profile -> MISS2. SELECT returns v1 (GC pause)3. UPDATE -> v2 committed4. DEL profile key5. SET v1 (EX 3600) -> STALE!

Because Redis SET has no version guard, a delayed miss reader overwrites the deleted key with stale v1.

Engineering Decision Framework
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 version Compare-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.
Decision Exercise · Make the Call

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?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

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.

Lifecycle & Failure Recovery

Why Delayed Double Delete and SETNX fail under >500 ms pauses

TTL expiredconcurrent missessingleflight lockvalue cachedCache HitCache MissHot-Key StampedeCoalesced Fill
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

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: Increment version atomically on every UPDATE.
  • 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 where new_ver <= cached_ver.
  • Short Version Tombstones on DEL: If invalidating instead of write-through, write a tiny ver=N, tombstone=1 (EX 60) so a slow v1 reader (ver < N) is still rejected.
  • Alternative: Single-Writer CDC: Stream pgoutput WAL changes in LSN order to a single Redis updater.
Version-Fenced Cache-Aside

Monotonic Version Lua CAS Rejects Stale v1 Fills

Reader / WriterCarries row version NRedis Lua CASRejects if new_ver <=…Version Tombstone60s fence on DELPostgreSQL 16(BIGINT version)UPDATE ... RETURNING…

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
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

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 · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does Delayed Double Delete (DEL -> sleep 500ms -> DEL) not fully guarantee against Cache-Aside stale fills?

Recommended Learning Flow