AlgoViz

Write-through

medium 22 min

With write-through, a save goes to the cache and to the database in the same request, and the caller hears success only when both are done.

Video lesson · Chapter 1 of 5

A saved name should appear on the next device

0:00 / 3:17

Theory

Read or listen first. About 2 min.

What it is

Write-through is a way to save data when there is a cache in front of a database. Each save changes the cache and the database, one right after the other, before the caller is told that it worked.

In the pure form the application writes only to a cache layer, and that layer passes the write on to the database. In many systems the application makes both writes itself. The idea is the same, but the failures are different.

It describes saves only. Reads still need a rule for values that are not in the cache, usually the same fallback as in cache-aside.

Why it exists

People often look at what they just saved: settings, a profile, a message. If the save also refreshes the cache, the next read is fast and shows the new value.

It also avoids the empty moment after a delete, when the next reader has to wait for the database. The cost is paid on the write: the caller waits for the database, and every saved value takes memory, read or not.

A short history

  1. 1968

    IBM announces the System/360 Model 85 in January, with a cache between the processor and main memory. From then on processor designers have to decide how writes reach main memory.

  2. 1984

    Papamarcos and Patel publish the Illinois protocol for write-back processor caches, which saves traffic compared with writing everything through.

  3. 2013

    The TAO paper describes a cache for the social graph at Facebook in which all writes to a shard go through one leader cache, instead of each web server handling a look-aside cache.

  4. 2017

    Amazon introduces DynamoDB Accelerator (DAX) in April, a cache that works in write-through mode.

Words to know

Synchronous
The caller waits until it is done.
Cache layer
A library or service that owns both the copy and the write to the database.
Read-through
The cache layer loads a missing value itself. The usual partner of write-through.
Write amplification
One save causes more than one write.
Undo
Removing the new value from the cache because the database refused it.
Unread copy
A value that was cached on save and never asked for.
Version
A number that grows with every save, used to refuse older ones.

How it works

Step through the idea, or press Play.

Step 1 of 3

Save. The caller sends a change

Understand it

Start here

Keeping score

At a match, one person keeps the score in two places: a match book that counts as the official record, and a big board that everyone can see.

The book and the board
MATCH BOOK0goalsSCOREBOARD0goalsA goal

The idea

Four things that define it

  • Two writes, one answer

    The caller hears success only when both are done.

  • Fresh copy

    The cache holds the new value right after the save.

  • Ready for the first read

    A saved value does not need a miss to get into the cache.

  • Slower saves

    The caller waits for the database.

The whole picture

The cache layer owns the write

One call, two stores

A writer saves through the app, which makes one call to a cache layer. The cache layer writes to the database and waits for it before the answer goes back.
The app makes one call. The layer behind it keeps both stores in step.

A save, then a read

Assumed: 1 ms for the cache, 10 ms for the database write.

What the caller waits for

tsave=tcache+tdb=1+10=11 ms,tread=1 mst_{save} = t_{cache} + t_{db} = 1 + 10 = 11\ \text{ms}, \qquad t_{read} = 1\ \text{ms}
Cache-aside waits about as long for a save, because it also writes the database and then deletes a key. Only write-back skips the wait. If your database write takes 50 to 200 ms, that wait is what the caller feels.

Order

Which write comes first?

When your own code makes both writes, the order decides what can go wrong. With the cache first, readers can see a value that the database then refuses. With the database first, the worst case is an old copy for a while.

Safer and risky order

Top: database first. The app updates the database, then sets the value in Redis, which holds the old value until then. Bottom: cache first. The app sets the new value in Redis and then the database write fails, so Redis holds a value that was never saved.

One of the two writes fails

OrderSecond write failsWhat readers seeRepair
Cache, then databaseDatabase refusesA value that was never savedDelete the key, return an error
Database, then cacheCache is unreachableThe old value for a whileQueue a delete, rely on the TTL
The undo itself can fail too. That is why every key keeps an expiry time.

A save, step by step

Limits

Why it is not a transaction

The database and the cache are two systems. A process can stop between the two writes, and no database transaction covers the cache. So write-through keeps the two close, not identical.

Two writers, two orders

Ways to keep one order

  1. 1

    One owner per key

    All writes for a key go through one cache node, which applies them in order.

  2. 2

    Versions

    The database returns a growing version. The cache refuses a lower one.

  3. 3

    Delete instead

    After the database write, delete the key. Then you have cache-aside, and the next read is a miss.

  4. 4

    Change log

    Feed the cache from the database's own ordered log. See cache consistency.

Reading

Reads still need a fallback

It is tempting to say that every read is a hit. That is only true for values that were saved since the cache started, have not expired and were not evicted. A new cache node starts empty, and rows saved before the cache existed were never in it. The Amazon ElastiCache guide names this missing data as the first weakness of write-through and suggests adding lazy loading.

Where a miss comes from

CauseExampleCure
New nodeA cache machine was replacedFall back and fill
EvictedMemory was fullFall back and fill, watch evictions
ExpiredThe TTL endedFall back and fill
Old rowSaved before the cache existedFall back and fill, or warm it

Memory

Copies nobody reads

Unread copies

1,000 saves/s×3,600 s=3,600,000 copies,× 1 KB=3.6 GB1{,}000\ \text{saves/s} \times 3{,}600\ \text{s} = 3{,}600{,}000\ \text{copies}, \quad \times\, 1\ \text{KB} = 3.6\ \text{GB}
Assumed: 1,000 different keys saved each second, 1 KB each, kept one hour. If one in ten is read, 3.24 GB of that is waste. A TTL of 10 minutes brings the total to 0.6 GB.

Should this save go into the cache?

Writing only to the database, past the cache, is called write-around.

Deleting

Removing a row

A delete goes to both places as well. Remove the row from the database first, then the key. In the other order a reader could load the row again in between.

Trade-offs

Strengths and weaknesses

Strengths

  • People see their own save at once
  • Reads of saved values are fast, also the first one
  • Acknowledged saves are in the database
  • Reading code stays simple: look, with a fallback
  • Very good for save, then read

Weaknesses

  • The caller waits for the database
  • Two writes for each save
  • Caches values that are never read, so memory grows
  • If a save needs both, a cache outage stops saves
  • Every writer must use the same door
  • Not for write-heavy data

When to use it

Where it fits

DataWhy it fitsWatch out
Profiles and settingsRead right after savingScripts that write the database directly
User sessionsSaved and read on each requestCost of a database write each time
Stock count on a product pageShould change with each saleCheck the database at checkout
Account balance on a home screenPeople expect the new numberPayments are decided in the database
Read-heavy data with some writesFast reads, safe savesMemory for unread copies

Write-through and cache-aside

Write-throughCache-aside
On a saveSets the new valueDeletes the old one
Caller waits forDatabase and setDatabase and delete
First read after a saveHitMiss
What is cachedEverything savedEverything read
Empty cacheNeeds a fallbackFills itself
They are often used together: cache-aside for reads, write-through for saves. Choosing a cache pattern adds write-back to the comparison.

Summary

The whole topic in one minute.

Write-through saves to the cache and the database before it answers. The next read is a hit and shows the new value, at the cost of waiting for the database and caching things nobody reads.

It is not a transaction. If your code makes both writes, write the database first, keep a TTL, order writers with one owner or a version, and give reads a fallback.

  • A save changes the cache and the database before the caller hears success.
  • Two systems, two writes: close, but not a transaction.
  • In your own code, write the database first and the cache second.
  • Keep one order per key with an owner or a version.
  • Reads need a fallback, and every copy needs a TTL.

Sources