Academy · Caching & CDNs

Cache-aside, write-through, write-back

When exactly do you write to the cache vs the database? Get it wrong and you serve stale or lose data.

Open the interactive version → diagrams, practice & more

The problem

When exactly do you write to the cache vs the database? Get it wrong and you serve stale or lose data.

The idea

Three common patterns trade freshness against speed and durability.

How it works

Cache-aside: the app reads cache, on miss loads the DB and fills the key; writes go to the DB and invalidate the key (not update it). Write-through: writes hit cache and DB synchronously — fresh, slower writes. Write-back: writes land in cache and flush to the DB later — fastest, but a crash loses the unflushed window. The subtle bug is the cache-aside race: a reader fills a stale value just as a writer invalidates, leaving the cache wrong until the next write.

The tradeoff

Cache-aside is simplest and most common but carries a stale-read window and that fill/invalidate race (mitigate with short TTLs or versioned keys). Write-through keeps cache and DB in lockstep at write-latency cost. Write-back trades durability for speed. Prefer invalidating over updating the cache — updating re-introduces the dual-write consistency problem.

In the wild

Most web apps use cache-aside with Redis + a TTL.

Interview deep dive

Flow

  1. Read: check cache; on miss load DB and populate with a TTL.
  2. Write: update the DB, then invalidate the key (don't update it).
  3. Next read repopulates the cache from the source of truth.
  4. Keep a TTL as a backstop against missed invalidations.

Watch for

Interviewer trap

Default to cache-aside + invalidate + TTL, and name the stale-read window you accept.

Related Academy

Part of Academy on SystemLore — system design interview prep with 148 deep topics, interactive diagrams, and a practice game. Practice this one →