Mental model
A database remains the durable authority; a cache is a disposable view that can lag. With write-through, an application commits a row and updates its matching cache value on the write path, while cache-aside usually deletes a key and fills it on a later miss. A safe design must handle concurrent readers, failed cache calls, retries, and replica lag.
Learning outcomes
- Distinguish cache-aside, write-through, and write-behind by their write and failure behavior.
- Use a transactional outbox and monotonic record versions to make cache updates retryable.
- Estimate stale-read exposure and explain why a TTL is a fallback bound rather than a consistency protocol.
Theory
In cache-aside, a read checks the cache first, queries the database on a miss, then populates the cache. A write typically commits to the database and invalidates the key. This keeps cache misses cheap to implement, but a read already in flight can fetch an old row and repopulate the key after invalidation. Write-through sends each mutation through a cache-aware write path: the durable row is written and the corresponding cached representation is installed or invalidated. It reduces the interval in which a successful write is invisible to cache readers, but it does not create a distributed atomic transaction between a database and Redis.
The database should commit the new row and an outbox event in the same local transaction. A worker then applies that event to the cache. If Redis is unavailable, the event remains durable and can be retried; the API must report the database commit accurately and use an idempotency key for client retries. Each event carries a monotonically increasing row version. An atomic cache operation accepts a value only when its version is at least the cached version, so a delayed event for version 8 cannot overwrite version 9. Deletes need versioned tombstones for the same reason: deleting the cache key alone lets an old in-flight read resurrect stale data.
Redis server-assisted client-side caching solves a related but distinct problem. With tracking enabled, Redis sends invalidations to clients that have cached keys read from that server. A disconnected client cannot rely on invalidations it missed; it must flush or rebuild its local cache before trusting entries again. Tracking can also add server memory proportional to tracked client-key relationships. It is useful when network round trips dominate and the client can tolerate invalidation-driven misses; it does not replace durable database-to-cache delivery.
For a cache value installed at time t₀, let T_delivery be the time until its matching invalidation or replacement is applied and T_ttl be its fixed expiry age. If fills use the authoritative database and do not extend the old value's lifetime, stale exposure is bounded by the earlier event:
Here all three quantities are elapsed seconds from the version becoming stale. This is a conditional bound, not a guarantee under replica lag, stale refill, or sliding TTL refresh. For example, if an outbox event takes 180 ms to reach the cache and the fallback TTL is 60 s, normal stale exposure is about 0.18 s; if delivery stalls, expiry limits the old entry to 60 s. A p99 queue delay is an operational percentile, not a hard maximum.
Trade-offs
| Strategy | Read and write behavior | Main cost or limit |
|---|---|---|
| Cache-aside | Reads fill on misses; writes commonly invalidate after the database commit. | A failed invalidation or stale refill can expose an old value. |
| Write-through | The write path updates the durable store and cache representation. | Adds cache work to writes; a second system still cannot join the database transaction automatically. |
| Write-behind | The cache accepts writes and flushes them to durable storage later. | Faster acknowledgements trade away durability until the flush succeeds. |
Choose write-through when reads are frequent and the service can afford synchronous cache work or a short, observable outbox lag. Cache-aside is simpler when stale reads are acceptable for a documented interval. Write-behind is a different durability decision: an acknowledged cache-only mutation can disappear if the cache fails before persistence. Keep the database primary, bound outbox retention, and alert on oldest-event age, retry count, cache hit ratio, and version lag rather than using hit ratio as a correctness signal.
Failure modes and misconceptions
- Database commit succeeds, cache update fails. The client may see an error even though the row is durable. Persist the outbox event with the row, make replay idempotent, and return an outcome that lets callers query or safely retry by operation ID.
- Out-of-order delivery regresses a value. Compare versions inside one atomic cache operation. A read fill from an old snapshot must not overwrite a newer cached version.
- Delete followed by stale refill. Store a versioned tombstone or use an invalidation generation fence; a bare
DELhas no memory of the version it invalidated. - Invalidation consumer falls behind. Expose queue age and backlog. TTL limits a fixed entry's lifetime only if stale replicas cannot refill it and expiry is not extended on reads.
- Client tracking connection drops. Discard affected local entries or establish a fresh tracking epoch before serving them; missed invalidations are not replayed merely because the client reconnects.
Decision scenario
An account service writes 2,400 profile changes per second. Its p99 outbox-to-cache delay rises from 45 ms to 900 ms during a Redis failover, while the profile TTL is 60 seconds. Keep the database writes available only if the service can retain and replay the outbox within its storage budget; expose the 900 ms stale window, avoid filling from lagging replicas, and shed or defer cache-dependent work if the queue's oldest-event age exceeds the product's freshness limit. A short TTL alone would mask a growing delivery failure until entries expire.
Implementation pattern
This runnable SQLite example commits each profile version and its cache event together. The cache adapter applies versions monotonically; a production adapter should implement that comparison atomically, for example with a Redis script. The in-memory lock here represents that one atomic cache operation in this single-process demonstration.
pythonimport sqlite3from threading import RLockdb = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE profiles (user_id TEXT PRIMARY KEY, version INTEGER NOT NULL, name TEXT NOT NULL);CREATE TABLE outbox (event_id INTEGER PRIMARY KEY, user_id TEXT, version INTEGER, name TEXT);""")cache: dict[str, tuple[int, str]] = {}cache_lock = RLock()def read_profile(user_id: str) -> str | None:with cache_lock:if user_id in cache:return cache[user_id][1]row = db.execute("SELECT version, name FROM profiles WHERE user_id = ?", (user_id,)).fetchone()if row is None:return Nonewith cache_lock:current = cache.get(user_id)if current is None or current[0] <= row[0]:cache[user_id] = (row[0], row[1])return cache[user_id][1]def replay_outbox() -> None:events = db.execute("SELECT event_id, user_id, version, name FROM outbox ORDER BY event_id").fetchall()for event_id, user_id, version, name in events:with cache_lock:current = cache.get(user_id)if current is None or current[0] <= version:cache[user_id] = (version, name)with db:db.execute("DELETE FROM outbox WHERE event_id = ?", (event_id,))def write_profile(user_id: str, version: int, name: str) -> None:with db:old = db.execute("SELECT version FROM profiles WHERE user_id = ?", (user_id,)).fetchone()if old is not None and old[0] >= version:raise ValueError("version must increase")db.execute("""INSERT INTO profiles VALUES (?, ?, ?)ON CONFLICT(user_id) DO UPDATE SET version = excluded.version, name = excluded.name""",(user_id, version, name))db.execute("INSERT INTO outbox (user_id, version, name) VALUES (?, ?, ?)", (user_id, version, name))replay_outbox()write_profile("u-7", 1, "Amina")assert read_profile("u-7") == "Amina"