# Write-Through: Save to the Cache and Database Together Before Success

> Write-through keeps a cache fresh by saving each write to both the cache and the database before the app reports success.

**In short:** Write-through keeps a cache fresh by saving each write to both the cache and the database before the app reports success.

From "System design", a free course by Venkat R. Murty: https://designervenkat.online/learn/system-design/write-through

## What You Will Learn

A cache is a fast copy of data that sits closer to the app than the main store. It makes reads quick, but the copy can fall behind when the real data changes. Write-through is a rule for writing data so the cache and the main store stay in step. This lesson explains how the write path works, what it costs, and when a team should pick it over other choices. By the end, you should be able to explain the rule in your own words, name its two main costs, and match a type of data to the right write strategy.

- **Cache:** A small, fast store that keeps copies of data so the app can answer without going to the slower main store.
- **Database:** The main place where a system keeps its data for the long term.
- **Write:** Saving a new value, such as a changed name or a new stock count.
- **Read:** Asking for a value and getting it back.
- **Stale data:** An old copy of a value that no longer matches the real value.
- **Latency:** How long one request takes from start to finish.
- **Write-through:** A caching rule where each write goes to the cache and the database, and success is reported only after both have saved it.
- **Write-back:** A caching rule where the write is saved to the cache first and copied to the database later.
- **Write-around:** A caching rule where the write goes straight to the database and skips the cache.

## How Does the Write Path Work?

The write path is the route a new value takes from the app to storage. In write-through, the app writes the new value to the cache and also writes the same value to the database. The app waits for both saves before it hears that the write worked.

1. **The app sends the write to the cache:** The app sends the new value to the cache, not to the database. For example, the new display name goes to the cache first.
2. **The cache saves to the database:** Right away, the app writes the same value to the database. The app finishes the database update before it sets the cache value.
3. **Both copies hold the new value:** Now the cache and the database both contain the new value, so they agree.
4. **Success goes back to the app:** Only after both saves finish does the app receive a success reply. If the database save fails, the write does not count as done, and a failed cache save is treated as non-fatal.

Because the success reply waits for both saves, a read that comes right after a write gets the new value. The read does not have to guess which copy is newer, because the cache was updated in the same step.

A caution: this is a cache rule, not a guarantee against every failure. If one save works and the other fails, the two copies can disagree. Handling failed or repeated writes is a separate topic for another lesson.

### Why Do Reads Stay Fresh?

Many caches need a separate step to remove or replace old entries after a change. Write-through removes that step, because every change already passes through the cache. The cache is updated each time the database is updated, so its copy is current. Sources describe this as the cache never holding stale data for values written this way.

A quick way to see it: a reader who asks for a profile just after an edit finds the newest name in the cache. No old copy is waiting to be served.

## What Are the Trade-offs?

Write-through is a choice, and each choice has a cost. Here are the three main points to weigh.

- **Fresh, fast reads:** Reads come from the cache, which holds the latest value. Sources note that the cache is always current, and that writes done this way avoid many misses for recently written data.
- **Slower writes:** Each write makes two trips, one to the cache and one to the database, and the user waits for both. Sources describe this extra delay as one of the costs of the pattern.
- **A cache filled with unused data:** Every written value is placed in the cache, even if nobody reads it again. Those unused entries take up memory and push out data that is read often.

> **Tip:** Users usually tolerate a short wait after they press Save more than a slow page load. The ElastiCache whitepaper notes that end users are more tolerant of latency when updating data than when retrieving it.

Each change means another two-step write.

## When Should You Choose Write-through?

Choose write-through when readers need a new value right after it is written. It fits data that is read often, must be fresh, and changes only now and then. Good examples include user profiles, account settings, and small sets of high-value data such as prices or feature flags.

- **Good fit:** Read-heavy data that must be fresh, such as a profile a user edits and then views again.
- **Poor fit: write-heavy:** Values that change many times a minute pay the two-step cost on every change, so the extra work adds up.
- **Poor fit: rarely read:** Values that are written often but seldom read fill the cache with copies that no one asks for.

Sources also warn that write-through needs cache software that can call the database for you. Teams without that tool often choose another pattern.

**Quick check:** A shopping site changes the stock count for each product hundreds of times a minute. Each product page is viewed only now and then. Would write-through be a good fit for the stock data?

A. Yes, because every stock change reaches the cache at once, so no page shows an old count
B. No, because each change costs two writes, and the cache would hold counts that few pages ever read
C. Yes, because the database is skipped, so stock updates never have to wait

**Answer:** B. Write-through pays two writes for every change. Here the changes are very frequent, and the pages are read rarely, so the cache would hold many values no one reads. The first and third options wrongly assume that the database is skipped or that cost is free.

### How Do the Three Write Paths Compare?

Write-through is easier to understand next to two close relatives. The diagram below shows where each write goes and when the app gets its success reply.

```
WRITE-THROUGH
  App --> Cache --> Database
          (both save, then success)

WRITE-BACK
  App --> Cache --> success now
                    Database gets it later

WRITE-AROUND
  App --> Database (cache skipped)
          Cache fills later, on a read
```

- **Write-through:** Fresh cache and database, slower writes. Best when readers need the latest value right away.
- **Write-back:** Very fast writes for the user, because the database is updated later. The cost is that recent writes can be lost if the cache fails before the copy is made. Best for counters where a small loss is acceptable.
- **Write-around:** Writes skip the cache, so the cache is not filled with unused data. The first read after a write misses the cache. Best for records written once and rarely read.

A simple way to remember them: write-through favors trust, write-back favors speed, and write-around favors a clean cache. Many systems read through a cache and use write-through only for the few values that must always be fresh.

## Worked Example: The Edit Profile Screen

Take a social app with an Edit Profile screen. A user changes their display name and taps Save. The app uses write-through for profile data, so the new name is saved through the cache to the database in one step.

1. **The user taps Save:** The screen sends the new display name to the app's cache layer. The user waits on the screen while this happens.
2. **The cache writes to the database:** The cache saves the name to the database before it finishes. The database now holds the new name.
3. **Both copies match:** The cache holds the new name too, so the two stores agree.
4. **The app reports success:** Only now does the screen show that the profile was saved.
5. **Friends see the change at once:** A friend who opens the profile right after the save reads the name from the cache and sees the new name, not the old one.

The save takes a little longer than it would without the cache step. That short wait is the price, and for a profile page that people read often, it is usually worth paying.

**Quick check:** A messaging app lets users pick a color theme in their settings. The app shows the chosen theme on the next screen, which reads it right away. Changes are rare. Which write strategy fits best?

A. Write-through, because the new theme must show on the next screen
B. Write-around, because the theme is written once and never read
C. Write-back, because the save should finish before the database is touched

**Answer:** A. The theme is read right after each change, so the reader needs the new value at once. Write-through keeps the cache and database in step. Write-around would make the first read miss, and write-back could lose the change if the cache failed first.

## Try It in Python

This short program copies the idea into code. Two dictionaries stand in for the cache and the database. The write function saves to both before it returns the success word. The read function checks the cache first.

```python
cache = {}
database = {}

def write_through(key, value):
    database[key] = value
    cache[key] = value
    return 'saved'

def read(key):
    if key in cache:
        return 'cache hit: ' + cache[key]
    return 'cache miss'

print(write_through('name:17', 'Nate'))
print(read('name:17'))
print(database['name:17'])
print(read('name:99'))

```

Output:

```text
saved
cache hit: Nate
Nate
cache miss

```

Notice that the write function does not return until both stores hold the value. That order is the whole idea of write-through. The last read shows what happens when a key was never written: the cache has nothing to give.

## Key Points to Remember

- **The rule:** A write goes to the cache and the database together, and success is reported only after both save.
- **The benefit:** The cache always holds the latest value, so reads after a write are fresh.
- **The cost:** Writes are slower, and rarely read data can fill the cache with unused entries.

> **Tip:** Ask two questions before you pick write-through: Do readers need the newest value right after a write? Is the data read far more often than it is written? If both answers are yes, write-through is a strong choice.

**Quick check:** A logging service records one event for every click on a website. Each event is written once and almost never read again. Which strategy keeps the cache from filling with these events?

A. Write-through, because every event should be copied to the cache
B. Write-around, because the events go straight to the database and skip the cache
C. Write-back, because the cache should hold events until a later copy to the database

**Answer:** B. Write-around skips the cache on writes, so unread events never take up cache space. Write-through would copy every event into the cache, and write-back would also hold them in the cache first.

## Sources

- [AWS Caching Best Practices (aws.amazon.com)](https://aws.amazon.com/caching/best-practices/)
- [Amazon ElastiCache whitepaper: Caching strategies](https://docs.aws.amazon.com/whitepapers/latest/database-caching-strategies-using-redis/caching-patterns.html)
- [Redis Patterns: Write-Through Caching Pattern](https://redis.antirez.com/fundamental/write-through.html)
- [Hello Interview: Caching for System Design Interviews](https://www.hellointerview.com/learn/system-design/core-concepts/caching)
- [AlgoMaster: Caching Strategies](https://algomaster.io/learn/system-design/caching-strategies)
- [Matthew Swong: Cache-Aside vs Write-Through vs Write-Back](https://www.matthewswong.com/en/blog/cache-aside-vs-write-through-caching/)
- [System Design Space: Caching Strategies](https://system-design.space/en/chapter/caching-strategies/)
- [Computer Weekly: Write-through, write-around, write-back cache explained](https://www.computerweekly.com/feature/Write-through-write-around-write-back-Cache-explained)
- [RLCache paper on caching strategies (arXiv)](https://arxiv.org/pdf/1909.13839)
