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
- The application writes to the cache.
- The cache stores the value, records it as dirty, and acknowledges.
- 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.