Write-back
medium 22 minWith 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
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
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.
1993
The Intel Pentium processor appears with a write-back data cache on the chip.
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.
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 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
One write
- 1
The application sends a save
For example a new score for player 9.
- 2
The cache stores it
This is the only wait.
- 3
The entry is marked dirty
It is newer here than in the database.
- 4
It joins the buffer
The caller has its answer already.
- 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
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)Numbers
What it saves
The same save in three patterns
| Pattern | Caller waits | Database writes for 5 changes of one key |
|---|---|---|
| Cache-aside | 10 + 1 = 11 ms | 5 |
| Write-through | 10 + 1 = 11 ms | 5 |
| Write-back | 1 ms | 1, if they fall in one flush |
Fewer database writes
The price
What a crash can take
The loss window
The bad moment
Making the window smaller
| Measure | Covers | What remains |
|---|---|---|
| Shorter flush interval | Every kind of crash | One interval |
| Log on disk (Redis append-only file) | A process crash or restart | About one second with the default sync every second |
| Replica on another machine | A dead machine | What was not copied yet: replication is asynchronous by default |
| Durable log first (write-ahead) | Nearly all | The log write becomes part of the wait |
Waiting for replicas (WAIT) | More failovers | Redis says this does not make it strongly consistent |
A safer write-back
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
Failure
When the flush fails
- 1
Keep the batch
Entries stay dirty until the database confirmed them.
- 2
Retry with a pause
Wait longer after each failure. See retries.
- 3
Make writes repeatable
Use an upsert of the latest value, or an id per change, so a second try does no harm.
- 4
Keep the order per key
An older value must not overwrite a newer one. One worker per group of keys, or versions.
- 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
| Data | Why it fits | Loss means |
|---|---|---|
| Game leaderboards | Scores change all the time | A few points, until the next score |
| Metrics and analytics | Many small additions | A tiny gap in a chart |
| Session activity, last seen | Only the newest value matters | A time that is seconds old |
| Views and likes | Huge numbers, nobody counts them by hand | A few missing |
| Sensor readings | Latest value per sensor | One 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.