SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
  • What is Caching?
  • Caching Strategies
  • Cache Eviction Policies
  • Cache Invalidation
  • HTTP Caching (Cache-Control, ETag)
  • Redis vs Memcached
  • Local Cache vs Distributed Cache
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Caching/Caching Basics

Caching Strategies

Cache-aside, read-through, write-through, write-back: who fills the cache, and when?

⏱ 16 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A caching strategy is the rule for who fills the cache and when it is written. It decides how the cache and the database work together.

  • Reading: cache-aside (the app fills the cache) or read-through (the cache fills itself).
  • Writing: write-through (cache and database together), write-back (cache first, database later) or write-around (skip the cache).
  • Fast strategies risk stale or lost data. Safe strategies are slower. There is no free lunch.

02Concept: What is it?

A cache is only useful if it holds the right data. Two questions decide that: on a read miss, who loads the data? and on a write, where does the data go first?

The five strategies at a glance
Reading
🖥️Cache-asideApp loads the cache
⚡Read-throughCache loads itself
Writing
🔒Write-throughCache + database together
🚀Write-backCache now, database later
↪️Write-aroundDatabase only
Read the arrows. Solid arrows happen first, in the order of the steps.
🧠Reads and writes are separate choices
In real systems you mix them, for example “cache-aside for reads” with “write-around for writes”, or “read-through plus write-through”.

03Real-Life Example

🍵A shop and its shelf
A small shop has a shelf at the front (the cache) and a warehouse at the back (the database).
Shop
Strategy
A customer asks for an item. The shopkeeper checks the shelf, then walks to the warehouse and puts a copy on the shelf
Cache-aside
The customer asks a helper at the shelf. The helper fetches from the warehouse by himself
Read-through
New stock is put on the shelf AND in the warehouse before the shopkeeper says “done”
Write-through
New stock goes on the shelf only. The shopkeeper takes it to the warehouse at closing time
Write-back (fast, but lost if there is a fire at noon)
New stock goes straight to the warehouse. The shelf is filled only when someone asks
Write-around

04Why Do We Need It?

Without a clear strategy, the cache and the database drift apart. Users see old prices, lost orders or wrong counts.

🎯Right data in the cache
Only data that is really asked for is stored.
🔁Cache and database agree
Each strategy defines how and when they are brought in line.
⚖️Speed vs safety
We choose how much speed to get and how much risk of stale or lost data we accept.
🧩Simpler code
With read-through, the app does not need cache code at all.

05Where Do We Use It?

StrategyOften used for
Cache-asideThe most common choice: user profiles, product data, API answers with Redis or Memcached
Read-throughCache libraries and services that load data for you; CDNs work like this for files
Write-throughData that must not be lost and is read right after being written (settings, profiles)
Write-backVery write-heavy data where a small loss is acceptable: counters, view counts, metrics, game scores
Write-aroundData written once and rarely read: logs, uploads, bulk imports

06Types / Parts / How It Works

1. Cache-aside (lazy loading)

The app is in charge. The cache is a side store.

🖥️App
→↓1. get
⚡Cache
↓2. miss
🗄️Database3. read, then 4. app saves to cache
  • Good: only requested data is cached. If the cache dies, the app still works (slower).
  • Bad: the first request is always slow. On a write, there is a small race: reader A reads the old value from the database, a writer updates the database and deletes the cache, then A saves the OLD value into the cache. It stays stale until the TTL. A TTL limits the damage.

2. Read-through

The cache is in charge. The app only talks to the cache. On a miss, the cache loads from the database.

  • Good: simple app code.
  • Bad: the cache needs to know how to load data. First read is slow. Same stale-data problems after writes.

3. Write-through

Each write goes to the cache and the database together, and the app waits for both.

  • Good: the cache is always fresh. Nothing is lost.
  • Bad: every write is slower. Data nobody reads is still cached.

4. Write-back (write-behind)

Each write goes to the cache only. The cache copies to the database later, often in batches.

  • Good: very fast writes. Many writes to the same key can become one database write.
  • Bad: if the cache crashes before the copy, the data is lost. The database is stale in between.

5. Write-around

Writes go to the database only. The cache is filled by reads.

  • Good: the cache is not filled with data that is never read.
  • Bad: a read right after a write is a miss. An old cached copy stays stale unless it is removed.

Compare them

StrategyRead speedWrite speedRisk
Cache-asideFast after the first readNormalStale data after races; small
Read-throughFast after the first readNormalStale data after writes
Write-throughFast, always freshSlower (two writes)Low
Write-backFast, always freshFastestData loss if the cache crashes
Write-aroundFirst read after a write is slowNormalStale copy if not removed
VisualizerStep through each strategyPick a strategy, then read or write. Try write-back and press “Crash the cache” before flushing.
Strategy
The app does the work. It looks in the cache first. On a miss, the app reads the database and fills the cache itself. On a write, it updates the database and deletes the cached copy.
🖥️App
↔
⚡Cacheempty
↔
🗄️Databaseprice = v1
Cache is empty

07How to Use It / Steps / Implementation

How to choose

  1. 1
    Is the data read much more than written?
    Use cache-aside or read-through with a TTL. This is the most common case.
  2. 2
    Must you never lose a write?
    Do not use write-back. Use write-through, or write to the database and delete the cache.
  3. 3
    Are writes very heavy and a tiny loss is acceptable?
    Write-back helps (counters, metrics). Protect it with a replicated or persistent cache.
  4. 4
    Is the data written once and rarely read?
    Use write-around so the cache is not wasted.
  5. 5
    Do you want less code in the app?
    Use read-through (and write-through).

A safe default for most apps

  1. Read: cache-aside with a TTL.
  2. Write: update the database first, then delete the cached key.
  3. Why delete and not update? Two writers can update the cache in the wrong order. Deleting avoids that. The next read loads the fresh value.
💡Simple pseudo-code (cache-aside)

get(key): value = cache.get(key). If it is missing: value = db.read(key), then cache.set(key, value, ttl). Return value.

update(key, value): db.write(key, value), then cache.delete(key).

08Key Terms to Know

TermMeaning in easy words
Cache-asideApp checks the cache, loads from the database on a miss and fills the cache itself
Read-throughThe cache loads missing data from the database on its own
Write-throughWrites go to the cache and the database together
Write-back / write-behindWrites go to the cache first and are saved to the database later
Write-aroundWrites skip the cache and go to the database
Dirty dataData changed in the cache but not yet saved to the database
FlushCopying dirty data from the cache to the database
Lazy loadingFilling the cache only when something is asked for
Race conditionTwo actions happen in an unlucky order and give a wrong result
Source of truthThe one place whose data is always the right answer (the database)

09Pros, Cons and Trade-offs

✅ Pros
  • Each strategy fits a clear need
  • Cache-aside is simple and the cache can fail safely
  • Write-through keeps the cache and database in line
  • Write-back gives very fast writes
⚠️ Cons
  • Every strategy has a weak spot
  • Cache-aside can hold stale data after a race
  • Write-through makes writes slower
  • Write-back can lose data
  • Mixing strategies adds complexity

Trade-offs

Safer strategies
write-through, write-around, cache-aside with delete
  • Data is not lost
  • Easy to reason about
  • Writes are slower or reads can be stale a little
Faster strategies
write-back
  • Very fast writes
  • Fewer database writes
  • Risk of data loss and stale database

10Common Problems and Mistakes

Common mistakes

  1. Using write-back for important data (orders, payments) without any safety net.
  2. Updating the cache instead of deleting it when two writers can run at once.
  3. Writing to the cache first, then the database in cache-aside. If the database write fails, the cache holds data that does not exist.
  4. No TTL on cache-aside, so a lost invalidation is never repaired.
  5. Treating the cache as required. The app should still work (slowly) when the cache is down.

Typical problems

🏁Races
Two requests overlap and an old value lands in the cache last.
🧊Cold start
After a restart, cache-aside and read-through start empty.
💾Lost writes
Write-back loses data on a crash before the flush.
📦Wasted space
Write-through can fill the cache with data nobody reads.

11Real-World Examples

🧰Redis / Memcached with cache-aside
The most common set-up for web apps: the app code checks Redis, then the database.
🌍CDNs
Work like read-through: on a miss the CDN fetches the file from your server and keeps it.
🖴Operating systems and disks
File writes are often held in memory and written later (write-back). That is why you eject a USB drive safely.
🗄️Databases
Many databases buffer changes in memory and write them to disk later, but also keep a log so a crash does not lose them.
📊Counters and metrics
View counts are often added up in memory and saved in batches.
🧾Logs and uploads
Written once, rarely read: write-around keeps them out of the cache.
📝Note
These are general ideas. The exact set-up inside each company is more complex.

12Related Topics to Read Next

What is Caching?→

The basics: hits, misses and why caches work.

Cache Eviction Policies→

What to remove when the cache is full.

Cache Invalidation→

Keeping cached data correct after a change.

Cache Stampede→

What happens when a popular entry expires.

Distributed Cache Architecture→

How a shared cache is built.

Idempotency→

Retried writes must be safe, just like retried cache updates.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Read strategies: cache-aside (app fills) and read-through (cache fills).
  • ✔Write strategies: write-through (both), write-back (cache first), write-around (database only).
  • ✔Default: cache-aside with a TTL, and delete the key after you write the database.
  • ✔Write-through: safe, slower writes.
  • ✔Write-back: fastest, but can lose data. Never for money.
  • ✔Write-around: good for write-once data.
  • ✔Always: the database is the source of truth, and the app should survive a cache failure.
  • ✔One line: “Choose who fills the cache and when it is written, then accept the matching risk.”
← Previous
What is Caching?
Next →
Cache Eviction Policies