Skip to content

Cache-aside, write-through, write-back

Working knowledgeConcept

Reading through a cache is simple. Writing is where caches go wrong: data changes in two places at once. Here is who writes the cache in each strategy, when the database hears about it, and what each one risks.

01 The real question: who writes the cache

Reading from a cache is the easy half: look there first, and fall back to the database. The hard half is writes. When data changes, the database and the cache both hold a copy, and something has to keep them in step.

The three common strategies answer two questions differently: who puts data into the cache (your code or the cache layer), and when the database gets a write (first, together, or later). Each answer buys speed or safety and pays with the other.

The three strategies in one line each
StrategyOn a read missOn a write
Cache-asideapp reads the database, then fills the cacheapp writes the database, then deletes the cache key
Write-throughsame as cache-asidedatabase and cache are both written before the write returns
Write-backsame as cache-asideonly the cache is written; the database catches up later

02 Cache-aside: the app does both jobs

In cache-aside (also called lazy loading) the cache is a plain key-value store and your code does all the work. This is the usual way Redis or Memcached is used in front of a database.

Cache-aside: a read, a hit, a write
Step 1 of 8
Misses 0
Cache (Redis)
Empty
Database
user:42→Ana
  • read, or stale
  • just written
  • cache hit
  • deleted

The cache is empty. The database holds user 42, named Ana.

0 hits
users.js
// redis is a node-redis client, db a pg Pool.
async function getUser(id) {
const key = `user:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // hit
const { rows } = await db.query('SELECT * FROM users WHERE id = $1', [id]);
const user = rows[0];
if (!user) return null;
await redis.set(key, JSON.stringify(user), { EX: 600 }); // TTL 10 min
return user;
}
async function renameUser(id, name) {
await db.query('UPDATE users SET name = $1 WHERE id = $2', [name, id]);
await redis.del(`user:${id}`); // delete, don’t set

03 Write-through: write both, every time

In write-through, every write goes to the cache and the database as one operation. Sometimes your code does both; sometimes a caching layer sits in front of the database and does it for you. Either way, the write returns only once both hold the new value.

Write-through, right after Ann renames herself: the app wrote the database and then the cache, before answering.
Cache (Redis)
user:42→Ann
Database
user:42→Ann
  • written by this request

The write is done only when both are written, so it is as slow as the database plus the cache. In return, the next read is a hit with the new value.

Reads right after a write are always hits with fresh data, which suits data that is read soon after it changes. The costs: every write pays for two stores, and the cache fills with values that may never be read, so you still want TTLs.

04 Write-back: write the cache, the database later

In write-back (or write-behind), a write changes only the cache and returns. The cache remembers which keys are dirty and writes them to the database later, in the background. Many writes to one key collapse into one database write.

Write-back: fast writes, and what a crash costs
Step 1 of 7
Cache
Empty
Dirty keys, not yet in the database
Empty
Database
views→10likes→3
  • just written
  • read
  • lost

A post's counters live in the database: 10 views, 3 likes. The write-back cache in front of it is empty, and nothing is waiting to be written.

That is the deal: writes are as fast as memory, and a hot counter does not hammer the database. But until a key is flushed, the only copy of the new value is in the cache. Write-back is safe only when the cache itself is durable or replicated, or when losing a few seconds of writes is acceptable, like view counts.

05 What each one risks

Cache-asideStale readsA short window after a write, or until the TTL, if a delete is missed. The database is always right.
Write-throughSlow writesEvery write waits for two stores. Fresh reads, but if the second write fails the two disagree.
Write-backLost writesWrites the cache confirmed can vanish if it dies before flushing. Fastest writes of the three.
Picking one
If your data is…Reach forBecause
read far more than written (profiles, products)Cache-asideonly hot keys use memory, and a dead cache costs speed, not data
read right after it is written (settings, carts)Write-throughthe next read is a hit with the new value
written constantly, small losses fine (counters, metrics)Write-backwrites coalesce, and the database sees a fraction of them

06 When cache-aside goes stale

On a write, delete the cache key; do not set it. Two writers that each set the cache can finish in the opposite order to their database writes, and the cache keeps the older value with nothing to correct it until the TTL.

read miss → slow DB read → setA slow reader puts old data backA reader misses and reads Ana. Before it sets the cache, a writer saves Ann and deletes the key. The reader then stores Ana. A TTL bounds how long that lasts; always set one.
redis.del() throwsThe delete failsThe database has the new value, the cache the old one. Retry the delete, or publish the change and let a listener delete it, rather than ignore the error.
1,000 reads of one cold keyA popular key expiresEvery request misses at once and all of them query the database. Let one request refill the key while the others wait, or refresh hot keys before they expire.
cache.set(); db failsWrite-through in the wrong orderIf the cache is written first and the database write fails, readers see a value that was never saved. Write the database first.

07 Check yourself

Question

With cache-aside, your app updates a user's email in the database. What should it do to the cache?

Question

A like counter is written thousands of times a second. Losing a few seconds of likes after a crash is acceptable. Which strategy fits?

Question

The cache server restarts and comes back empty. Under cache-aside, what do users lose?

08 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?