Cache-Aside vs Write-Through vs Write-Behind: Pick Your Poison

Lazy, strict, or reckless: cache-aside, write-through, and write-behind trade write latency against consistency in three different ways. Here's how each one really behaves — with an interactive lab that traces every read and write.

Most caching advice stops at “add Redis.” The interesting question isn’t whether to cache — it’s what happens on a write. The moment a value changes, your cache and your database disagree, and how you reconcile them is the whole game. There are three classic answers. Each one is correct somewhere, and each one fails in a specific way you should choose deliberately.

Pick your poison.

The vocabulary, in thirty seconds

Three actors: your app, the cache (Redis — fast, forgetful), and the database (slower, durable, the source of truth). A hit is served from cache; a miss pays for a database round trip. A cached value dies in one of two ways: invalidation (the app explicitly deletes the key, usually on write) or TTL expiry (Redis drops the key after N seconds with no app involvement). Every strategy below is a different choreography of these pieces around reads and writes.

Cache-aside: the lazy one

Cache-aside — also called lazy loading — is the default for a reason: the cache stays out of the write path, and nothing is cached until somebody actually asks for it.

import json
import redis

cache = redis.Redis(host="localhost", port=6379, decode_responses=True)

def get_user(user_id: int) -> dict | None:
    key = f"user:{user_id}"
    if (hit := cache.get(key)) is not None:
        return json.loads(hit)              # hit: the DB is never touched
    row = db.fetchone("SELECT id, name FROM users WHERE id = %s", (user_id,))
    if row is not None:
        cache.set(key, json.dumps(row), ex=300)  # miss: lazy fill, TTL bounds staleness
    return row

def update_user(user_id: int, name: str) -> None:
    db.execute("UPDATE users SET name = %s WHERE id = %s", (name, user_id))
    cache.delete(f"user:{user_id}")          # invalidate — don't update (see below)

Two details matter. First, the write updates the DB first, then deletes the key. Second, it deletes rather than rewriting the cached value. That’s not laziness — it dodges a race: with two concurrent writers, A updates the DB, B updates the DB, B writes the cache, then A writes the cache, and the cache now holds A’s older value while the DB holds B’s. Ordering the cache writes correctly requires distributed coordination; deleting the key sidesteps it entirely. The next read re-fills from the source of truth.

The honest guarantees:

  • Staleness is TTL-bounded in the worst case. Invalidation keeps the common case fresh, but invalidations get lost — a crash between the UPDATE and the DEL, a second writer path nobody told about the cache — and then readers see stale data until the TTL expires. The TTL is the backstop, not the primary mechanism.
  • Thundering herds are the failure mode. When a hot key expires, N concurrent requests all miss and all hit the DB at once — exactly when traffic is highest. The mitigations are well-trodden: request coalescing (one worker refills while the rest wait on the result), a SET NX lock so a single worker does the refill, or probabilistic early refresh (start refreshing at ~80% of TTL on hot keys):
lock = f"user:{user_id}:lock"
if cache.set(lock, "1", ex=10, nx=True):   # only one worker refills
    row = db.fetchone("SELECT id, name FROM users WHERE id = %s", (user_id,))
    cache.set(key, json.dumps(row), ex=300)
    cache.delete(lock)
  • Write latency ≈ 1 DB RTT. The DEL is cheap and usually not the bottleneck.

Reach for cache-aside for read-heavy data where brief staleness is tolerable: product pages, profiles, leaderboards, config.

Write-through: the strict one

Write-through puts the cache in the write path: every write goes to the cache and the DB, synchronously, before the caller gets its ack.

def update_user_writethrough(user_id: int, name: str) -> None:
    db.execute("UPDATE users SET name = %s WHERE id = %s", (name, user_id))
    try:
        cache.set(f"user:{user_id}", json.dumps({"id": user_id, "name": name}), ex=300)
    except redis.RedisError:
        # A failed cache write must never leave the OLD value behind.
        cache.delete(f"user:{user_id}")
        raise

The guarantee is the strongest of the three: readers can never see a torn write, because the cache is updated in the same synchronous step as the DB. After warmup, reads are nearly 100% hits (the very first read of a key still misses and fills, like cache-aside).

The poisons, stated plainly:

  • Write latency is the sum of both stores. Every write pays a cache RTT plus a DB RTT, and a slow or flaky cache makes every write slow. You’ve coupled your write path’s availability to Redis.
  • Partial failures need a policy, not hope. DB succeeded but the cache SET failed? Delete the key and surface the error — a stale cached value is worse than a retried request. Cache succeeded but the DB failed? Delete the cached value, because you must never serve data the database doesn’t have. Either way, the rule is: on any doubt, the cache loses.

Reach for write-through where a stale read is a bug, not a tradeoff: pricing, balances, inventory counts, feature flags that gate money.

Write-behind: the reckless one

Write-behind — also called write-back — takes the cache out of the durability story: writes land in the cache, the caller gets its ack immediately, and a background process flushes the writes to the DB later.

def update_user_writebehind(user_id: int, name: str) -> None:
    key = f"user:{user_id}"
    cache.set(key, json.dumps({"id": user_id, "name": name}), ex=300)
    queue.enqueue({"op": "user.update", "id": user_id, "name": name})
    # ack now — the DB catches up within the flush lag.
    # Crash before the flush and this write never existed.

The appeal is real: write latency drops to ~1 cache RTT, and the DB sees writes batched instead of one panicked RTT at a time. It’s the only strategy that absorbs a true write burst without the DB feeling it.

The poisons, and there are three:

  1. The data-loss window. Anything queued but unflushed dies with the process. The window is exactly the flush lag — and the queue must be durable (Redis Streams, Kafka), never an in-process list, or every deploy becomes a data-loss event.
  2. The database lags the readers. Anything reading the DB directly — analytics, a second service, a replica consumer — sees old data until the flush lands. Your cache and your DB now disagree by design, for a bounded time.
  3. Ordering is your problem. Flushes must preserve per-key order; replay an older write after a newer one and you’ve resurrected stale data. Coalesce per key (last write wins) or sequence the queue — pick one deliberately.

Reach for write-behind for write bursts you can afford to lose or replay: counters, session activity, analytics ingestion, social “likes.” Keep it far away from money.

Invalidation vs TTL expiry, honestly

These two are often presented as alternatives. In production they’re belt and suspenders, and confusing their jobs is how you get paged:

  • TTL alone: simple, no invalidation logic to get wrong. Staleness ≤ TTL, always, provable. Right for data that’s naturally time-bounded or recomputed — “trending now,” leaderboards, rate-limit counters.
  • Invalidation alone, no TTL: one missed DEL — the crash between UPDATE and DELETE, the write path that forgot the cache exists — and the key is stale forever. There is no backstop. This is the 3 AM page.
  • Both: invalidation keeps the common case fresh; the TTL bounds the damage when invalidation fails. This is what most production cache-aside setups actually run, and it’s what I’d recommend as the default posture: invalidation is a promise, TTL is a guarantee.
Read and write paths per strategy: cache-aside reads through to the DB on miss and invalidates on write, write-through writes cache and DB synchronously, write-behind acks from cache and flushes to the DB asynchronously
Who gets contacted, in what order — the read and write paths that define each strategy.

Try it: the caching laboratory

CACHELAB — LIVE
Pick your poison, then watch it play out
A deterministic simulator replays 104 ops against one cache and one DB under the strategy you pick. Every metric below is simulated and illustrative — the shapes of the tradeoffs are what transfer to production.
Read / write ratio80% reads · 20% writes
Write burst4 back-to-back writes on user:1
HIT RATE
67.9%
57 hits / 84 reads · 27 misses
DB LOAD
45.2%
47 DB ops · 27 reads · 20 writes
WRITE LATENCY (illustrative)
~15 ms
1 DB RTT; invalidation is a cheap DEL
STALENESS WINDOW
≤ 30 ops (TTL-bound; oldest served entry was 30 ops old)
9 entries expired by TTL
Crash simulation
No crash simulated. (This strategy keeps nothing unflushed, so a crash loses nothing.)
Step-by-step trace — who is contacted, in what order
READ user:7 · op #0 — cache MISS
1APPGET user:7
2CACHEMISS (nil)
3DBSELECT … WHERE id = 7 ← the miss penalty
4CACHESET user:7 … EX 30 (lazy fill)
5APPreturn row to caller
WRITE user:1 · op #2
1DBUPDATE user:1 … (source of truth first)
2CACHEDEL user:1 (invalidate, don't update)
3APPack
Workload: 104 ops · 84 reads · 20 writes (incl. a 4-write burst on user:1). Fixed seed, TTL 30 ops, flush lag 10 ops, cache RTT 2 ms, DB RTT 15 ms — all illustrative. Real latencies vary; the shapes of the tradeoffs don't.

Three experiments worth running. First, pick write-behind, crank the write burst, and toggle the crash — the lost-writes counter is the data-loss window made concrete, and it scales with the burst. Second, hold the read/write ratio fixed and compare DB load across strategies: write-through hammers the DB on every write but never serves stale data; cache-aside shifts the load onto misses and invalidations. Third, watch the staleness card while you switch strategies — it’s the one metric where write-through wins outright, and the price is printed right next to it in the write-latency card.

Decision guide

Trade-off chart of write latency versus consistency: write-behind is fastest but eventual, cache-aside sits in the middle with TTL-bounded staleness, write-through is slowest with strong consistency; crash safety is a separate axis
Write latency vs consistency — no strategy dominates, and crash safety is a separate axis.
Cache-asideWrite-throughWrite-behind
Read pathcache → miss → DB → fillcache (always fresh)cache (latest)
Write latency≈ 1 DB RTT≈ cache + DB RTT≈ 1 cache RTT
Staleness≤ TTL, on missed invalidationnoneDB lags ≤ flush lag
Crashsafe (DB is truth)safe (DB is truth)queued writes lost
Extra machineryherd mitigationpartial-failure handlingdurable queue + ordering

Rules of thumb, in order:

  • Default to cache-aside. Least machinery for read-heavy data, and the TTL bounds your worst day.
  • Write-through when a stale read is a bug, not a tradeoff — and budget the write-latency tax on every write.
  • Write-behind when writes burst faster than your DB can absorb — and only for data you can afford to lose or replay.
  • Whatever you pick, set a TTL even if you invalidate. One missed delete without a TTL is stale forever.

The poison you pick is the failure mode you can explain to your team at 3 AM. Cache-aside fails with a herd you can see coming; write-through fails slow and obviously; write-behind fails silently, losing exactly the writes you told it were expendable. Choose the failure you can live with — that’s the whole decision.

Keep reading