AlgoViz

Choosing a cache pattern

medium 24 min

Cache-aside, write-through and write-back differ in what happens on a save, what a reader can see and what a crash can take.

Video lesson · Chapter 1 of 5

Start with the decision the stale value could change

0:00 / 3:56

Theory

Read or listen first. About 2 min.

What it is

A cache pattern is a rule for keeping a cache and a database together. Three are used most. With cache-aside the application fills the cache on a miss and deletes the copy on a change. With write-through a save changes both before the caller is answered. With write-back a save changes the cache, and the database follows later.

Choosing means asking how the data is read and written, how old a copy may be, and what may be lost in a crash. The answers point to a pattern, often a different one for each kind of data.

Why it exists

No pattern is best. Each one makes something cheap and something else expensive or risky. If you pick by name, the cost shows up later, usually on a bad day.

In interviews and in design reviews the reason counts more than the choice. A short list of questions gives you that reason, and the numbers to go with it.

A short history

  1. 2003

    Memcached is released in May: a cache that knows nothing about the database, so the application has to apply a pattern.

  2. 2013

    Two papers from Facebook show both sides: a demand-filled look-aside cache in front of databases (NSDI), and TAO, where writes go through a leader cache (ATC).

  3. 2017

    Amazon introduces DAX in April, a managed cache for one database that comes with a pattern built in: write-through.

Words to know

Read and write ratio
How many reads there are for each write.
Staleness
How old a copy may be when someone reads it.
Loss window
How many confirmed saves a crash may take.
Read your own write
A person sees the change they just made.
Cache pollution
Copies that take room and are never read.
Cold start
The time when the cache is empty.
Hybrid
Different patterns for reads and saves, or for different data.
Write-around
A save that goes only to the database.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask. Reads, writes, age, loss

Understand it

Start here

Which shoes today?

Max has three pairs of shoes by the door. None of them is the best pair. It depends on the ground outside.

Look outside first
look firstbootsspikessandalsWhat is outside?

The three

What each pattern does

  • Cache-aside (lazy loading)

    Read from the cache, fetch on a miss. On a change write the database and delete the copy. The application manages both stores.

  • Write-through

    Every save goes to the cache and the database before the answer. It counts only when both are done.

  • Write-back (write-behind)

    Save to the cache and answer. A worker writes the database later, in batches.

Each has its own page with the details: cache-aside, write-through and write-back.

Step by step

StepCache-aside (read)Write-through (save)Write-back (save)
1A read arrivesA save arrivesA save arrives
2Look in the cacheWrite the cache or, in your own code, the database firstWrite the cache
3Hit: return itWrite the other oneAnswer: saved
4Miss: read the databaseWait for bothQueue the key
5Store the copyAnswer: savedA worker collects a batch
6Return the dataReads look in the cache firstWrite the batch to the database

Compare

The comparison

Three patterns, nine questions

QuestionCache-asideWrite-throughWrite-back
Copy and database agreeAfter the delete or the TTLClosely, not as one transactionAfter the flush
Save waits forDatabase and deleteDatabase and setCache only
Read after a saveMissHitHit
First read of old dataMissMissMiss
Confirmed saves lost in a crashNoNoYes, up to the flush
Unread copiesFewManyMany
Cache is downSlow readsSlow reads, saves need a ruleRecent saves at risk, saves stop or fall back
EffortLowMediumHigh
Best forRead-heavySave, then readWrite-heavy
No loss means no loss caused by the cache. The database still needs its own backups.

Save and next read

aside: 11+12=23 ms,through: 11+1=12 ms,back: 1+1=2 ms\text{aside: } 11 + 12 = 23\ \text{ms}, \quad \text{through: } 11 + 1 = 12\ \text{ms}, \quad \text{back: } 1 + 1 = 2\ \text{ms}
Assumed: 1 ms per cache trip, 10 ms per database read or write. A cache-aside save writes the database and deletes the key, and the next read misses: look, read, fill.

Work for the database

R=900/s, W=100/s, h=0.9:aside or through=0.1⋅900+100=190/sR = 900/s,\ W = 100/s,\ h = 0.9: \quad \text{aside or through} = 0.1 \cdot 900 + 100 = 190/s
No cache would be 1,000 a second. Write-back with 20 dirty keys per 5 second flush would be 0.1 x 900 + 20 / 5 = 94 a second. The hit rate is assumed to be the same.

Decide

The questions

From a worry to a pattern

A starting point, not a law. Data that changes every few minutes is often fine with cache-aside and a delete.

What to ask, and why

QuestionChanges the choice because
How many reads for one write?Cache-aside lives from reads between changes
How old may a copy be?Zero means no cache for that decision
What may a crash take?Only write-back can lose confirmed saves
Do people read their own save at once?Write-through gives a hit with the new value
Who else writes the database?Writers that skip the cache leave old copies
What if the cache is away?Cache-aside is the easiest to live without

Cache-aside

Good and bad fits

Best for

  • Read-heavy applications
  • Data that does not change often
  • A cache that may be unavailable
  • Places where slightly old data is fine

Not for

  • Write-heavy data: the copy is deleted before it pays off
  • Values that must be exact
  • Data that changes every moment

In its favour: it caches only what is asked for, a cache failure does not stop the application, and it is simple. Against it: the first request is slow, a miss costs three trips, a copy is stale if someone changes the database directly, and the application has to do the work.

Write-through

Good and bad fits

Best for

  • Reads that follow a save
  • Read-heavy data with some writes
  • Profile and settings updates
  • Data where confirmed saves must be safe

Not for

  • Write-heavy data
  • Very large data that is rarely read
  • Saves that must be very fast

In its favour: the copy is new right after the save, nothing confirmed is lost, and the model is easy to think about. Against it: the save waits for the database, both systems take part in every save, and the cache fills with values nobody reads.

Write-back

Good and bad fits

Best for

  • Write-heavy data
  • Analytics and logs where small gaps are fine
  • Game leaderboards
  • Sensor data, latest value

Not for

  • Financial transactions
  • Data that must never be lost
  • Readers that need the database to be current

In its favour: the fastest saves, fewer database writes, and it absorbs bursts. Against it: confirmed saves can be lost, the database is behind, it is hard to build and to debug, and the cache has to be very reliable.

Mix

One shop, several patterns

Choose per kind of data. Reads and saves can also use different rules: cache-aside for reads together with write-through for saves is a common pair.

One shop, a pattern per kind of data

Shoppers use three parts of one shop. Product pages use cache-aside, own settings use write-through, and view counts use write-back. All three use cache code and Redis in front of one database.
The box in the middle stands for the cache code of each part together with Redis. Only its rule differs.

Cache-aside reads with write-through saves

No cache

When the answer is none

Show from the cache, decide in the database

A buyer pays through checkout, which checks and changes stock and balance in the database. The same buyer looks at a product page, which shows a cached stock count from Redis that may be old.
A cached number may be shown. A decision about money or the last item is made in the database.

Failure

What breaks in each

EventCache-asideWrite-throughWrite-back
Cache restarts emptyAll reads miss for a whileReads miss, need a fallbackUnflushed saves gone, reads miss
Database is downHits still work, saves failHits still work, saves failSaves go on until the buffer is full
App crashes in the middleDelete may be lostOne of two writes may be missingNothing, if the buffer is shared
Someone edits the databaseOld copy until the TTLOld copy until the TTLTheir edit may be overwritten by a flush
Thundering herd covers the rush after a restart, cache consistency the lost deletes.

The cache fails during a write-through save

Lenient is usually better. See circuit breaker.

Change

When to change your mind

TodaySignalMove to
No cacheRepeated reads fill the databaseCache-aside
Cache-asidePeople do not see their own saveSet on save (write-through) for that data
Cache-asideHit rate under about 20% with many deletesNo cache, or cache something else
Write-throughMost copies are never readCache-aside
Write-throughWrites are the limit and loss is fineWrite-back
Write-backThe loss is no longer acceptableA durable log, or write-through
The 20% comes from the assumed numbers on the cache-aside page. Compute your own.

Changing the pattern of live data

Leaving write-back has one extra step: flush everything first.

Summary

The whole topic in one minute.

Ask four things about each kind of data: what hurts most, how old a copy may be, what may be lost, and whether people read their own save. Read-heavy and a little stale: cache-aside. Must see own save: write-through. Write-heavy and a small loss is fine: write-back. Exact decisions: no cache.

Give the reason, the number and the cost, and say what would make you change your mind. Most systems use more than one pattern.

  • Ask about reads, writes, allowed age and allowed loss before you name a pattern.
  • Cache-aside for reads, write-through for reading your own save, write-back for many small writes.
  • A cache-aside save and a write-through save wait about equally long.
  • Write-back is the only one that loses confirmed saves.
  • Choose per kind of data, and keep exact decisions in the database.

Sources