AlgoViz

Write-back

medium 22 min

With write-back, also called write-behind, a save is answered as soon as it is in the cache, and a worker writes it to the database later in batches.

Video lesson · Chapter 1 of 5

The customer has saved an email the database cannot yet see

0:00 / 3:16

Theory

Read or listen first. About 2 min.

What it is

Write-back is a way to save data in which only the cache is written while the caller waits. The database is brought up to date later, by a background worker.

A changed entry that has not reached the database yet is called dirty. The worker collects dirty entries, writes them in one batch, and marks them clean. This is the flush. It runs every few seconds, or when enough entries are waiting.

Write-back and write-behind mean the same thing here.

Why it exists

Memory answers in about a millisecond. A database that makes every row durable takes longer, and it can only do so many writes a second. When the same values change again and again, most of those writes are wasted: only the last value matters.

Deferring the write hides the wait and turns many small writes into a few large ones. The price is a window in which the cache holds the only copy. Whether that is acceptable is a question about the data, not about the technology.

A short history

  1. 1984

    Papamarcos and Patel publish a protocol that keeps write-back processor caches in step with each other. It became known as the Illinois or MESI protocol.

  2. 1993

    The Intel Pentium processor appears with a write-back data cache on the chip.

  3. 2009

    Linux 2.6.32, released in December, rewrites the code that writes dirty file pages to disks, with separate flushing for each device.

Words to know

Dirty
Newer in the cache than in the database.
Clean
The same in both.
Flush
Writing dirty entries to the database.
Write buffer
The list of entries waiting for the flush.
Coalescing
Several changes of one key become one write.
Loss window
How much confirmed data a crash can take away.
Back pressure
Slowing callers down because the buffer is nearly full.
Idempotent
Safe to repeat, such as an upsert of the latest value.

How it works

Step through the idea, or press Play.

Step 1 of 3

Write. The cache takes the value and the caller is answered

Understand it

Start here

A newspaper round

Asha delivers newspapers and writes changes in a small note pad. The big book at home is the real record. Walking home after every door would take all day, so the notes are copied once, at night.

The pad and the big book
47Note padNo. 4: 2Big bookat homein the pocketOne quick note

The idea

Four things that define it

  • Very fast saves

    Only memory is written while the caller waits.

  • Later, in batches

    A worker writes the database in the background.

  • A write buffer

    Dirty entries wait in line, the newest value per key.

  • Loss is possible

    What was not flushed is gone if the cache dies.

The whole picture

Answer now, store later

The fast part and the slow part

A writer saves through the app, which sets the value in Redis and marks it dirty. A flush worker takes a batch every five seconds and bulk writes it to the database, which is a little behind.
Solid arrows happen while the caller waits. Dashed arrows happen later.

One write

  1. 1

    The application sends a save

    For example a new score for player 9.

  2. 2

    The cache stores it

    This is the only wait.

  3. 3

    The entry is marked dirty

    It is newer here than in the database.

  4. 4

    It joins the buffer

    The caller has its answer already.

  5. 5

    The worker flushes

    When the timer fires or the buffer is full, a batch goes to the database and the entries become clean.

A save and a flush

Text
function write(key, value):    cache.set(key, value)    cache.markDirty(key)    return SUCCESS              // no wait for the databasefunction flushWorker():         // in the background    every FLUSH_INTERVAL, or when the buffer is full:        entries = cache.copyDirty()        database.batchWrite(entries)        cache.markClean(entries that did not change since)
Both halves of the pattern. Entries are marked clean only after the database confirmed.

Numbers

What it saves

The same save in three patterns

PatternCaller waitsDatabase writes for 5 changes of one key
Cache-aside10 + 1 = 11 ms5
Write-through10 + 1 = 11 ms5
Write-back1 ms1, if they fall in one flush
Assumed: 1 ms for a cache trip, 10 ms for a database write.

Fewer database writes

200 keys5 s=40 rows/sinstead of1,000 writes/s,1,00040=25×\frac{200\ \text{keys}}{5\ \text{s}} = 40\ \text{rows/s} \quad \text{instead of} \quad 1{,}000\ \text{writes/s}, \qquad \frac{1{,}000}{40} = 25\times
Assumed: 1,000 updates a second on 200 keys, flushed every 5 seconds. If the updates were on 5,000 different keys, the batch would have 5,000 rows and nothing would be saved except the round trips.

The price

What a crash can take

The loss window

at risk=writes/s×interval=1,000×5=5,000 saves\text{at risk} = \text{writes/s} \times \text{interval} = 1{,}000 \times 5 = 5{,}000\ \text{saves}
These saves were confirmed to people. With a flush every second it is 1,000, and the database works harder.

The bad moment

The caller saw saved, and the value is gone.

Making the window smaller

MeasureCoversWhat remains
Shorter flush intervalEvery kind of crashOne interval
Log on disk (Redis append-only file)A process crash or restartAbout one second with the default sync every second
Replica on another machineA dead machineWhat was not copied yet: replication is asynchronous by default
Durable log first (write-ahead)Nearly allThe log write becomes part of the wait
Waiting for replicas (WAIT)More failoversRedis says this does not make it strongly consistent

A safer write-back

The app sets the value on cache machine A, which keeps it in memory and in a log on disk and copies it to a replica on cache machine B. A flush worker that retries in order takes batches and upserts them into the database.
Two machines and a log on disk. The risk is smaller, not zero.

Reading

Who has the truth?

For a dirty entry the cache is right and the database is behind. For everything else the database is right. So reads look in the cache first and fall back to the database, exactly as in cache-aside. Reading only from the cache would lose every row that was never cached.

A read

This is only safe if a dirty entry is never evicted.

Failure

When the flush fails

  1. 1

    Keep the batch

    Entries stay dirty until the database confirmed them.

  2. 2

    Retry with a pause

    Wait longer after each failure. See retries.

  3. 3

    Make writes repeatable

    Use an upsert of the latest value, or an id per change, so a second try does no harm.

  4. 4

    Keep the order per key

    An older value must not overwrite a newer one. One worker per group of keys, or versions.

  5. 5

    Limit the buffer

    When it is nearly full, slow callers down or refuse. A buffer without a limit only delays the crash.

One flush

Counters

Two servers, one counter

If every server counts on its own and writes its total, the last one wins. Either keep one shared counter in the cache and flush that value, or flush the difference and let the database add it up. A repeated difference counts twice, so give each batch an id and remember which ids were applied.

Other readers

Who else looks at the database?

Reports, exports and other services that read the database see the past. Tell them how far behind it is, let them read the cache, or do not use write-back for data that others need fresh.

Trade-offs

Strengths and weaknesses

Strengths

  • The fastest saves of the three patterns
  • Batches make database writes cheaper
  • Coalescing removes wasted writes
  • Absorbs short bursts of writes
  • The database can be away for a moment

Weaknesses

  • Confirmed saves can be lost
  • Recovery after a failure is hard
  • The database is behind for other readers
  • Harder to debug and to audit
  • The cache must be as reliable as a database

When to use it

Where it fits

DataWhy it fitsLoss means
Game leaderboardsScores change all the timeA few points, until the next score
Metrics and analyticsMany small additionsA tiny gap in a chart
Session activity, last seenOnly the newest value mattersA time that is seconds old
Views and likesHuge numbers, nobody counts them by handA few missing
Sensor readingsLatest value per sensorOne reading, replaced soon

Summary

The whole topic in one minute.

Write-back answers from memory, marks the entry dirty, and flushes batches to the database later. It suits counters, scores and readings that change all the time and may lose a little.

State the loss window in numbers, make it smaller with a log and a replica, keep failed batches, never evict a dirty entry, and flush on shutdown. If nothing may be lost, choose another pattern.

  • A save is answered from memory. The database follows in batches.
  • Dirty means newer in the cache than in the database.
  • Loss window = writes per second x flush interval. Say the number.
  • Keep failed batches, repeat safely, keep order, limit the buffer, never evict dirty entries.
  • Compare it with the others in choosing a cache pattern.

Sources