· 7 min read
Cache-aside vs write-through vs write-behind caching
Cache-aside, write-through and write-behind keep cache and database in sync differently. How each works, where stale data creeps in, and which to use.

Cache-aside, write-through and write-behind are the three common ways to keep a cache and a database in step. Cache-aside lets the application fill the cache on a miss and delete the entry on a write; write-through updates the cache and the database together on every write; write-behind writes to the cache first and flushes to the database later. Most systems should start with cache-aside plus a TTL, and reach for the others only when their specific trade-off is worth it.
The choice matters less for speed than for correctness. Every strategy has a window where the cache and the database disagree, and the strategies differ mainly in how big that window is and what closes it.
What are the main caching strategies?
A few terms first. A cache hit is a read served from the cache; a miss is one that falls through to the database. A TTL (time to live) is how long an entry stays before it expires. Invalidation is removing or replacing an entry because the underlying data changed.
| Strategy | Read path | Write path | Main risk |
|---|---|---|---|
| Cache-aside | App checks cache, loads DB on miss, fills cache | App writes DB, then deletes cache key | Stale fill races |
| Read-through | Cache library loads DB on miss | Usually paired with write-through | Same as its write path |
| Write-through | Reads hit a warm cache | Write goes to cache and DB synchronously | Slower writes, cache holds unread data |
| Write-behind | Reads hit the cache | Write goes to cache, DB updated later | Data loss if the cache dies before flush |
Read-through is cache-aside with the loading logic moved inside the cache layer, so the application only ever talks to the cache. The consistency behaviour is the same; it is a question of where the code lives.
How does cache-aside work?
Cache-aside (also called lazy loading) keeps the cache out of the write path almost entirely:
async function getProduct(id) {
const key = `product:${id}`;
const hit = await cache.get(key);
if (hit) return JSON.parse(hit);
const row = await db.query("SELECT * FROM products WHERE id = $1", [id]);
await cache.set(key, JSON.stringify(row), { EX: 300 }); // 5 minute TTL
return row;
}
async function updatePrice(id, price) {
await db.query("UPDATE products SET price = $1 WHERE id = $2", [price, id]);
await cache.del(`product:${id}`);
}
Only data someone actually reads ends up cached, and if the cache goes down, reads get slower but nothing is lost. That is why it is the default.
Notice the write deletes the key rather than setting the new value. That is deliberate, and it is the part people most often get wrong.
Why delete the cache key instead of updating it?
Updating the cache on write looks more efficient: the next reader gets a hit. But with two concurrent writers, the database and the cache can apply the writes in different orders.
Writer A sets the price to 20 and writer B sets it to 30. The database sees A then B and ends at 30. The cache updates are separate network calls, so B's lands first and A's lands second. The cache ends at 20. Stepping through that interleaving in a small simulation gives exactly that: database 30, cache 20. Worse, nothing fixes it until the TTL runs out, because the cache has no idea it is wrong.
Deleting avoids this. Two deletes in any order leave the same result: no entry. The next reader loads whatever the database has now.
Deleting has its own, narrower race. A reader misses, reads the old price 10 from the database, and pauses (a GC pause, a slow network hop). Meanwhile a writer updates the database to 20 and deletes the key, which is not there yet. Then the reader resumes and fills the cache with 10. Simulated step by step, that ends with database 20, cache 10. It needs a read and a write to overlap on the same key within milliseconds, so it is rare, but on hot keys rare things happen daily.
How do you close the stale-fill window?
There is no free fix, but there are layers, roughly in order of cost:
- Always set a TTL. It is the backstop for every race you did not think of. A stale entry lives at most one TTL. Pick it based on how long stale data is acceptable, not on hit rate alone.
- Delete after the transaction commits. If you delete inside a transaction that later rolls back or commits slowly, a reader can refill the old value before the commit is visible. Run the delete after commit.
- Delayed second delete. Delete immediately, then delete again a short time later (a few hundred milliseconds, longer than a typical read-and-fill). This catches the slow reader from the race above. It is crude but cheap.
- Versioned fills. Store a version number or
updated_atwith each row, and only write a cache entry if it is newer than what is already there. In Redis this needs a small Lua script so the compare and set are atomic.
The versioned check is the most robust. In the same simulation, a writer fills version 2, then the late reader tries to write version 1 and is rejected, leaving the cache correct:
// Pseudocode for an atomic "set if newer" (run as one Lua script in Redis)
function fillIfNewer(key, value, version) {
const current = cache.get(key);
if (!current || current.version < version) {
cache.set(key, { value, version }, { EX: 300 });
}
}
If you also read from replicas, remember a miss can be filled from a replica that is behind the primary, which reopens the same window. Fill from the primary for keys that were just written, or rely on the version check.
When should you use write-through or write-behind?
Write-through writes the new value to both the cache and the database as part of the same request. Reads right after a write are always hits, which helps when the same data is read immediately after it changes, such as a user's own profile or a session. The costs: every write pays for two stores, the cache fills with data that may never be read, and the dual write still needs ordering care. If the database write succeeds and the cache write fails, you are back to stale data, so treat the cache write as best-effort and keep a TTL.
Write-behind (or write-back) acknowledges the write once the cache has it, then flushes to the database asynchronously, often in batches. It absorbs write spikes and turns many small writes into a few large ones, which suits counters, view tallies and metrics. The cost is durability: anything not yet flushed is lost if the cache node dies, and other services reading the database see old data until the flush. Only use it for data where losing the last few seconds is acceptable.
A fourth option sidesteps application-level invalidation. Instead of deleting keys in request handlers, a separate process reads the database's change stream, known as change data capture (CDC), and deletes or refreshes affected keys. Every write path is covered, including ones that bypass your app, like migrations and admin scripts. It pairs well with the transactional outbox pattern when you want invalidation events tied to commits.
Whichever you pick, hot keys need protection on the read side too. A delete on a popular key is effectively a forced expiry, and that invites a cache stampede if hundreds of readers miss at once.
Key takeaways
- Start with cache-aside: fill on miss, delete on write, and always set a TTL.
- Delete cache keys on write instead of updating them; concurrent updates can leave the cache permanently wrong until expiry.
- Cache-aside still has a stale-fill race; versioned fills or a delayed second delete close most of it.
- Write-through helps read-after-write but costs every write; write-behind trades durability for write throughput.
- Change data capture moves invalidation out of request handlers and covers every write path.
FAQ
Is cache-aside the same as lazy loading?
Yes. Both names describe the application loading data into the cache only when a read misses, rather than populating it on writes.
Should the cache or the database be written first?
Write the database first, then invalidate the cache. Invalidating first lets a reader refill the old value before the database write lands.
Does a short TTL make invalidation unnecessary?
Only if your users can tolerate data that is stale for up to one TTL. For prices, permissions or anything a user just edited, invalidate explicitly and keep the TTL as a safety net.