Write-Behind: Fast Writes Now, Database Updates Later
Write-behind saves each write in a cache first and copies it to the database later, trading some safety for speed.
In short
Write-behind saves each write in a cache first and copies it to the database later, trading some safety for speed.
12 min readFree
What You Will Learn
Every app saves data somewhere. Often that somewhere is a database, which is a program that keeps data safe on disk so it survives restarts. Saving to a database takes time. When many users save at once, the database can become the slow part of the whole system. Write-behind is one design pattern that tackles this problem. In this lesson you will learn what write-behind is, how it works step by step, why teams use it, what it costs, and when it is a good fit. You will also see one worked example and a short code sample.
Key words
- Cache
- A fast, small store that keeps a copy of data close to the app, usually in memory, so the app does not always need the slower database.
- Database
- The main place where a system keeps its data for the long term.
- Write
- Any action that saves a new or changed value somewhere.
- Write latency
- How long the app waits from the moment it sends a write until the write is confirmed.
- Write throughput
- How many writes the system can handle in a given amount of time.
- Acknowledgment
- A reply that tells the app its write was accepted.
- Flush
- Copying saved changes from the cache into the database.
- Batch
- A group of changes sent to the database together as one job.
- Dirty data
- Data that changed in the cache but has not yet been copied to the database.
- Write-through
- A pattern where each write goes to the cache and the database at the same time, before the app gets a reply.
How Does Write-behind Work?
Write-behind is also called write-back. The core idea is simple. The app writes to the cache only. The cache confirms the write right away. Later, the cache copies the changes to the database. The copy happens in the background, so the app does not wait for it. Many sources describe the same flow: the application writes to the cache, and a background process moves those changes to the database later, often in batches.
- 1
The app writes to the cache
When a user action changes data, the app sends the new value to the cache and nothing else.
- 2
The cache confirms at once
The cache replies right away. The app can finish its work and show the user a result without waiting for the database.
- 3
The cache marks and queues the change
The cache notes that this item is dirty, meaning it differs from the database. It may also place the change in a queue, which is a line of waiting jobs.
- 4
The cache flushes later
After a set delay, or when enough changes have built up, the cache writes the pending changes to the database, often as one batch.
Some systems let the delay be a fixed number of seconds. For example, one caching product lets you set a delay, and it stores the changed entries after that time passes. Another common approach is to flush on a schedule, which is like sending the day's mail in one trip instead of many small trips.
Tip
Write-behind is not a promise that the database is updated right away. It is a promise that the cache has the newest value, and the database will catch up later.
Hardware designers use the same idea. The software version works in the same spirit, but it runs in application servers and data stores instead of on a chip.
Write-behind is also called write-back in many texts. The two names describe the same pattern. Write-back is more common in hardware. Write-behind is more common in application and database work.
The biggest contrast is with write-through. In write-through, the app writes to the cache and the database together. The app waits until both finish before it gets a reply. This keeps the two copies in step, but every write costs the time of the slower database write. Write-behind removes that wait from the app's path.
Write-behind
The app waits only for the cache. The database is updated later, in the background. The database can be briefly behind the cache.
Write-through
The app waits for both the cache and the database. Both copies match after each write, but writes are slower.
The key difference
The question is when the database gets the change: before the app gets its reply, or some time after.
Why Do Teams Use It?
Write-behind is chosen for speed on the write side. It does not make reads faster by itself. Its main benefits fall into three groups, and each one matters for a different reason.
Low write latency
The app gets its reply from the cache, which is much faster than a database write. Users feel the page respond quickly, and the app can move on to the next task sooner.
Higher write throughput
Because the cache takes writes quickly, the system can accept more writes per second. The slow database no longer limits every single user action.
Fewer database writes
Many changes can become one write. This lowers the load on the database and saves its capacity for other work.
Write-behind is most useful when the same item changes many times in a short period. Think of a player's score that changes after every move. Without write-behind, each move may trigger a database write. With write-behind, the cache keeps only the newest score. When the flush comes, one write saves the latest value.
Coalescing is the name for this merging of changes. Some products do it by default. That means earlier updates to the same key are skipped. This is useful for totals and states, but not for records where every change matters.
Tip
Ask two questions before you choose write-behind. How often does the same item change? Can the system survive losing the last few seconds of changes? If the answers are often and yes, the pattern is worth a look.
What Are the Costs and Risks?
Write-behind has a clear cost. The speed comes from delaying the database write, and that delay creates risk. Here are the three main trade-offs.
Data can be lost
Changes that exist only in the cache are at risk. If the cache crashes before the flush, those changes may never reach the database. The app already told the user the write succeeded, so the loss can be hidden until someone checks.
The database is briefly out of date
Any other system that reads the database directly may see old values. The cache knows the newest value, but the database does not yet. Consistency here means that copies agree; write-behind lets them disagree for a while.
More complexity
The system must track dirty items, handle retries when the database is down, keep the queue from growing without limit, and recover after a crash. Simple designs are easier to test and to explain to a new team member.
The data loss risk is the one that surprises beginners most. A write-behind cache can confirm a write, then lose it. This is why many guides say write-behind should not hold money, orders, or other records where one lost write causes real harm.
The risk is not all or nothing. The size of the risk depends on how long the flush waits. A short delay means fewer changes are at risk at any moment. A long delay means more changes are at risk, but fewer database writes are needed.
Replication means keeping copies of the same data on more than one machine. Persistence means saving the cache's changes to disk or another durable place, so a restart does not erase them. A durable write queue is a queue that saves its jobs to disk before it confirms them, so pending changes survive a crash. Each of these reduces the risk, but each adds cost and complexity.
Tip
Mitigations lower the risk. They do not remove it. Even a replicated or persistent cache can fail in ways its designers did not plan for, so test what happens after a crash.
There are also practical details. A queue that grows without limit can use up memory. Retries also matter. If the database rejects a flush, the cache must try again without losing the change or writing it twice in a way that breaks the data.
What Are Good and Bad Fits?
The right choice depends on the data. Write-behind suits data that changes often, can be rebuilt or slightly wrong for a short time, and is not a legal or money record. Many sources agree on the same type of example: counters, tallies, and analytics that track how many times something happened.
Good fit: counters and view counts
A few seconds of lost views rarely matters to the business. The total is useful, and it can be corrected or estimated later.
Good fit: game scores and leaderboards
Scores change quickly. Losing the last short window may be annoying, but it may not be a disaster for a casual game.
Poor fit: payments and orders
A lost payment or order can cost real money and trust. These records should be written to durable storage before the app says the work is done.
Poor fit: account and profile settings
Users expect a setting they just saved to stay saved. Write-through or a direct database write is safer here.
Write-through is a better fit when reads must always match the database and losing a write is not acceptable. Write-behind is a better fit when write speed matters more than a short window of risk. Neither pattern is always right. The best systems often mix them, using different patterns for different kinds of data.
Worked Example: Counting Video Views
Here is a worked example based on a video platform like YouTube. This is an illustration of the idea, not a description of how YouTube is built inside. Imagine a popular video that receives a very large number of views. If every view caused its own database write, the database would be overloaded. Write-behind offers a simpler plan. Follow the steps below.
- 1
A viewer watches the video
The app adds one to the view counter for that video in the cache. The viewer gets the video and the app does not wait for a database write.
- 2
More views arrive
Each new view adds one more to the same cached counter. The cache keeps only the newest total, not a separate database write for each view.
- 3
The timer fires
Every few seconds, the system flushes the counter. It writes the combined total to the database as one update.
- 4
The database catches up
A huge number of view events become a few database writes. The database stays calm, and the total shown to users is close to live.
- 5
A crash is possible
If the cache fails between flushes, the views counted since the last flush may be lost. For a view counter, this loss is usually acceptable, which is why this is a good fit.
The code below uses the same idea in a small program. It writes 100 updates to a cache, but the database sees only one write when the flush runs. The sample uses only standard tools and gives the same output every time.
cache = {}
dirty = set()
db = {}
db_writes = 0
def write(key, value):
cache[key] = value
dirty.add(key)
def flush():
global db_writes
for key in sorted(dirty):
db[key] = cache[key]
db_writes += 1
dirty.clear()
for i in range(1, 101):
write("views", i)
print("cache value:", cache["views"])
print("db before flush:", db.get("views", 0))
flush()
print("db after flush:", db["views"])
print("database writes:", db_writes)
Output
cache value: 100 db before flush: 0 db after flush: 100 database writes: 1
Read the output carefully. The cache holds the newest value right away. The database holds nothing until the flush. After the flush, the database has the right total, and only one write happened. If the program crashed before the flush, the database would still show zero. That gap is the trade-off in action.
Check Your Understanding
Try the two short scenarios below. Each one asks you to use the idea, not just repeat a definition.
Quick check
A game app updates a player's score in the cache after every move. It saves the score to the database once a minute. The cache server crashes 30 seconds after the last save. What happens to the player's recent moves?
Quick check
A team builds a shopping cart feature for an online store. Each item added is a write, and the store must never lose an item a customer chose. Which approach fits best?
Key Takeaways
Write-behind lets an app write to the cache and get an immediate reply. The cache copies the changes to the database later, often in batches. This lowers write latency, raises write throughput, and cuts the number of database writes, especially when the same item changes many times. The cost is real: changes that exist only in the cache can be lost in a crash, the database can lag behind the cache, and the design is harder to build and run.
Use write-behind for write-heavy data where losing a little is tolerable, such as counters and view counts. Avoid it for money, orders, and records that must never disappear. When you are unsure, compare it with write-through, and ask what would happen if the cache failed one second after a write.
Sources
- Enjoy Algorithms: Caching Strategy, Write-Behind (Write-Back) Pattern
- Hello Interview: Caching for System Design Interviews
- Hazelcast Documentation 5.0: Working with an External Data Store
- Hazelcast Documentation 5.2: Configuring a MapStore
- Hazelcast Cloud: Build a MapStore (write-through and write-behind settings)
- Redis blog: Is your caching strategy holding you back?
- Redisson glossary: Write-Through vs Write-Back Cache
- Codemia: Caching Strategies, Cache-Aside, Write-Through, and Write-Behind
- DEV Community: Cache-Aside, Write-Through, Write-Behind: Six Caching Patterns, Two Decisions
- Systemdr: Caching: Write-Through, Write-Back, Write-Around
- Software System Design: Write-through, Write-back Cache
- Levelop: Caching Strategies in System Design: 4 Patterns
- USPTO patent 9519581: Storage integration for host-based write-back caching
Last updated on 17 November 2026
Related lessons
- System designWrite-Through: Save to the Cache and Database Together Before Success
- System designAsynchronism: Accept the Request Now, Do the Slow Work Later
- System designDatabase Caching: Keep Copies of Repeated Reads in Fast Memory
- System designBusy Database: Why Too Much Work on the Database Slows Everything
Learn with me
Every lesson is free. I add new ones as I learn. Have a question, or want help with your own work? Book a short call.