Course contents

06. Caching Lesson 5 of 8

Write Behind

Acknowledge writes in the cache and flush them later: see bursts smoothed into steady database load, the flush lag, and what a cache crash costs.

14 minIntermediate8 steps
Loading the interactive simulation…
Loading the knowledge check…

Summary

  • Write-behind acknowledges a write once the cache has it and flushes dirty entries to the database later.
  • Bursts become a backlog drained at the database’s pace: steady load instead of a spike.
  • The backlog drains only at the spare flush capacity; meanwhile the database is behind.
  • Dirty entries held only in memory are lost if the cache dies, after the client was told they succeeded.
  • Batching and coalescing cut database work; durable buffers turn lost writes into delayed writes.
Deep diveHow it works, trade-offs, failure modes, misconceptions and the interview angle.

What it is

Write-behind (also called write-back) is a write policy in which the cache acknowledges a write as soon as it holds the new value, marks the entry dirty, and writes it to the database later, asynchronously, typically in batches. Reads through the cache see the new value immediately; the database catches up.

Why it exists

A synchronous write path (direct writes or write-through) makes every caller wait for the database and makes the database take every write at the moment it arrives. That forces you to size the database for the peak write rate, even if the peak lasts seconds. Write-behind decouples the two: callers get the latency of a memory write, and the database receives writes at a rate it can sustain. Repeated writes to the same key can be merged, so the database may do much less work than the number of writes suggests.

How it works

  1. The application writes to the cache.
  2. The cache stores the value, records it as dirty, and acknowledges.
  3. A flusher periodically (or when enough entries are dirty) takes dirty entries, writes them to the database, often as one multi-row statement or transaction, and marks them clean.

Smoothing. During a burst the dirty set grows; afterwards it drains. The database runs at its own maximum instead of being overloaded.

Drain time. The backlog only shrinks by the spare capacity: drain time ≈ backlog ÷ (flush rate − arrival rate). With 600 dirty entries, a 200 writes/s flush rate and 150 writes/s still arriving, that is 600 ÷ 50 = 12 seconds.

Flush lag. Until an entry is flushed, the database holds the old value. Anything that reads the database directly (reports, search indexers, other services, replicas, change-data-capture consumers) sees the past.

Batching and coalescing. A batch amortises round trips and commits over many rows. If a key changed five times since the last flush, only the latest value needs writing. Both reduce database work and shorten the lag.

Durability. Dirty entries exist only where the cache keeps them. If that is process memory, a crash or eviction loses writes that clients were told had succeeded. Options: replicate the cache (writes acknowledged after a replica has them), persist an append-only log with a suitable fsync policy (every write, or every second, which bounds loss to about a second), or use a durable log such as Kafka as the buffer. Each adds latency back to the write path; the loss you can accept decides how much.

Not more capacity. A buffer absorbs peaks only. If the arrival rate stays above the flush rate, the backlog grows until the buffer is full or memory runs out.

When to use it

  • High write rates with repeated updates to the same keys: counters, view and like counts, "last seen" timestamps, session activity, rate-limit or usage counters, game state checkpoints.
  • Bursty writes where the database must not be sized for the peak.
  • Data where losing or delaying a few seconds of updates is acceptable, or the buffer is made durable.

When not to

  • Payments, orders and anything where an acknowledged write must never disappear, unless the buffer is durable and replicated.
  • When other systems read the database directly and need current data.
  • When writes are sustained above what the database can absorb: fix capacity, not buffering.

Trade-offs

Choice You gain You pay
Write-behind Memory-speed writes, burst smoothing, batching Loss risk, database lags the cache, more moving parts
Durable buffer (replica, log) No acknowledged write lost Extra latency per write, more infrastructure
Larger batches / longer flush interval Less database work Longer lag, more at risk per crash
Write-through Database always current, simple durability Write latency and peak load hit the database

Alternatives

  • Write-through: synchronous, simple, durable; the database takes the peak.
  • A message queue in front of the database: the same smoothing with an explicit, durable log and consumers; see the message queues lesson.
  • Transactional outbox: when the write must be atomic with other database changes and published reliably.
  • Scaling the database's write capacity: partitioning, better hardware, cheaper writes.

Failure modes

  • Cache crash with dirty entries: silent loss of acknowledged writes (memory-only buffers).
  • Buffer overflow: sustained overload fills the buffer; writes then fail or memory is exhausted.
  • Flush failures: the database rejects a batch (constraint, outage); entries must be retried without blocking others forever, and poison entries need a dead-letter path.
  • Ordering and conflicts: flushing out of order, or concurrent writers, can let an older value overwrite a newer one; use versions or last-write timestamps.
  • Stale direct readers: anything reading the database sees the past for the length of the backlog.

In production

Decide the acceptable loss window explicitly and configure durability to match. Bound the buffer and alert on its depth and age of the oldest dirty entry; that age is your current staleness and risk. Batch and coalesce flushes, make them idempotent, and handle failed batches with retries and a dead-letter path. Keep reporting and other direct database readers aware of the lag, or point them at the cache.

Common misconceptions

  • "Write-behind adds database capacity." It moves load in time; the average must still fit.
  • "An acknowledged write is safe." Only if the dirty entry is durable.
  • "Everyone sees the new value immediately." Only readers that go through the cache.
  • "A bigger buffer fixes overload." It only delays the moment it fills up.

Interview angle

Contrast it with write-through in one line (acknowledge after cache vs after database), then cover the costs: loss on crash, database lag, sustained-load limits. Good answers quantify the drain time (backlog ÷ spare capacity), name suitable data (counters, presence), say how to make the buffer durable, and mention batching, coalescing and idempotent flushes.

Model assumptions

The simulation is a simplified model, not a benchmark. The Order API writes as a Poisson process. In the write-through steps the cache (a server model with 64 workers and a queue of 200) writes the database synchronously; the database has 4 connections and a 20 ms mean write (lognormal, cv 0.3), about 200 writes per second, and fails queries that wait over 300 ms. In the write-behind steps the cache records each write in a buffer of dirty entries (a queue of 2,000) and acknowledges at once; the database is drawn as the buffer's consumer, a worker model with 4 slots and the same 20 ms per write, so the flush rate is a little under 200 writes per second. Batching is a cost model: 8 ms per row instead of 20 ms; the engine does not merge repeated writes to one key. When the cache and buffer crash, the simulated buffer keeps its entries and flushes them after recovery, as a durable buffer would; a memory-only buffer would lose them, which the lesson explains rather than simulates. Numbers show behaviour and orders of magnitude only.

The lesson as textEvery step of the simulation, written out.
  1. 1. Starting point: every write waits for the database

    The Order API writes 150 order updates per second through a write-through cache: the cache writes the database, then acknowledges. The database can do about 200 writes per second (4 connections, 20 ms each), so it is around 80% busy.

    Every write’s latency includes the database commit, and the database sees every write at the moment it happens.

    Scene: The Order API sends 150 writes per second to a write-through cache, which writes each one to the database before acknowledging. The database is around 80% busy and nothing fails.

    Key idea: With write-through, the database takes each write in real time and the caller waits for it.

  2. 2. A burst hits the database directly

    One second in, a flash sale triples writes to 450 per second for two seconds. The database can only do 200. Writes queue for connections, the cache’s workers all sit waiting on the database, its own queue fills and writes are rejected. Latency climbs past a second and stays high until the backlog clears, well after the burst.

    The burst is short: averaged over a minute the database would have plenty of capacity. It just cannot take the peak at the moment it arrives.

    Scene: From one to three seconds, writes jump to 450 per second. The database saturates, the cache backs up waiting on it, latency rises past a second and some writes are rejected.

    Key idea: A synchronous write path must be sized for the peak, not the average.

  3. 3. Acknowledge first, write later

    Now the cache acknowledges as soon as it has the write in memory and marks the entry dirty. A flusher writes dirty entries to the database in the background, at the pace the database can take. This is write-behind (also called write-back).

    The same burst replays. Writes are acknowledged in a few milliseconds and none fail. The buffer of dirty entries grows to about 500 during the burst while the database works steadily at its own maximum: the cache has turned a spike into a plateau. Afterwards the buffer drains, but only as fast as the database’s spare capacity, the gap between what it can flush and the 150 writes per second still arriving.

    Scene: The cache now acknowledges writes immediately and keeps dirty entries in a buffer that is flushed to the database in the background. During the same burst writes stay fast and none fail; the buffer grows to about 500 entries and drains slowly afterwards while the database works at full, steady speed.

    Key idea: Write-behind acknowledges after the cache write and flushes asynchronously, smoothing bursts into steady database load.

  4. 4. The database is behind the cache

    Look at the buffer after the burst: seconds later, hundreds of acknowledged orders still exist only in the cache. Drain time ≈ backlog ÷ spare flush capacity, and with little spare capacity that is a long time. Anyone reading the database directly in that window (a report, a search indexer, another service, a replica) sees old data.

    The buffer depth is your staleness window and, as the next steps show, your risk window. Reads that go through the cache are fine: it has the latest value.

    Scene: The same burst. Three seconds after it ends the buffer still holds hundreds of acknowledged writes while the database catches up; the database lags the cache by that backlog.

    Key idea: Under write-behind the database lags the cache by the buffer’s drain time; only cache readers see the latest data.

  5. 5. Flush in batches

    Flushing one row at a time wastes the database’s effort on round trips and commits. Real flushers group dirty entries: one multi-row insert or one transaction per batch, and if a key was written five times since the last flush, only its latest value is written.

    In this model batching lowers the cost per row from 20 to 8 ms. The same burst now leaves a backlog of under a hundred entries that is gone within a second of the burst ending: a shorter staleness and risk window, and the database does less work for the same data.

    Scene: The flusher now writes in batches at 8 ms per row. The same burst leaves a backlog of under a hundred entries that drains within a second after the burst.

    Key idea: Batching and coalescing repeated writes cut database work and shorten the flush lag.

  6. 6. The cache crashes with dirty entries

    Back to per-row flushing. Two and a half seconds in, near the end of the burst, the cache crashes. Writes in flight fail and new writes are refused, which the API at least knows about.

    The real damage is in the buffer: hundreds of orders were acknowledged to customers but never reached the database. In this model the frozen buffer survives (it is drawn as a durable queue). In a cache that keeps dirty entries only in memory, those writes are simply gone, and nobody gets an error for them.

    Scene: Near the end of the burst the cache and its buffer crash. In-flight and new writes fail. The buffer still holds hundreds of acknowledged writes that never reached the database; with memory-only storage they would be lost.

    Key idea: Write-behind’s risk: acknowledged writes that are still only in cache memory are lost if the cache dies.

  7. 7. Make the dirty entries survive

    The same crash, but now the dirty entries are durable: replicated to a second cache node or appended to a log on disk (or the buffer is a real log such as Kafka). A second and a half later the cache restarts, finds its backlog and flushes it. Writes refused during the outage still failed, but no acknowledged write is lost.

    The cost: durability adds a replication or disk step to every write, giving back part of the latency write-behind saved. How much loss you accept (none, or "up to one second of writes") decides how you configure it.

    Scene: The cache and buffer crash during the burst and restart a second and a half later. The durable buffer still holds its acknowledged writes and flushes them to the database; afterwards nothing fails.

    Key idea: Durable dirty entries (replication, append-only log) turn lost writes into delayed writes.

  8. 8. When to choose write-behind

    Write-behind gives the fastest writes and turns bursts into steady database load. It fits data where losing or delaying a little is acceptable or can be made safe: counters, view counts, session activity, metrics, game state checkpoints.

    Avoid it, or make the buffer durable, for money, orders and anything with legal or customer-visible consequences. Remember that the database lags the cache, that the buffer must be sized and monitored, and that a buffer only absorbs peaks: if writes stay above the flush rate, it fills up.

    Scene: The cache acknowledges writes and flushes them in the background at 150 writes per second; the buffer stays nearly empty and nothing fails.

    Key idea: Write-behind trades durability and database freshness for write speed and smoothing; it absorbs peaks, not sustained overload.