Caching strategies explained: cache-aside vs read-through vs write-through vs write-back

Every cache has to answer three questions: when does data go into it, where do writes go first, and who keeps it in step with the database? The four caching strategies are four different answers. Learn how each one works, when to use it, and the bugs that come with it.

Four signposts at a crossroads, each pointing down a different road, under a banner that asks 'Who keeps the cache in step?'. Cache-aside: the app checks the cache, and fills it on a miss. Read-through: the cache fills itself from the database. Write-through: every write goes to the database and the cache together. Write-back: writes land in the cache first and reach the database later. The two read signs are blue, the two write signs are yellow.
Fig. 1 — Two strategies for reading, two for writing. Most real systems use more than one.

In the last article we added a cache and saw how fast it makes things. Here’s the part that trips people up: the moment you have two copies of the same data, one in the cache and one in the database, you have to keep them in step.

Every caching setup quietly answers three questions:

  1. When does data go into the cache? On the first read? On every write?
  2. Where does a write go first? The database, the cache, or both?
  3. Who keeps them in sync? Your code, or the cache itself?

The four classic caching strategies are four different answers. Two are about reading and two are about writing:

A two by two grid. Top row, reading strategies. Cache-aside: the app asks the cache, and on a miss the app itself reads the database and fills the cache. Read-through: the app only talks to the cache, and on a miss the cache loads from the database by itself. Bottom row, writing strategies. Write-through: a write goes to the database and the cache at the same time, and the user waits for both. Write-back: a write goes only to the cache, the user gets an instant reply, and the cache sends it to the database later in a batch.
Cache-aside and read-through decide how the cache gets filled. Write-through and write-back decide where writes go.

Let’s take them one at a time.

1. Cache-aside (lazy loading)

This is the one you’ll use most. The cache sits to the side. Your app checks it first, and only on a miss goes to the database and fills the cache. Data is loaded lazily: only when someone actually asks for it.

When data changes, the app updates the database and deletes the cached copy. The next read loads the fresh value.

// Java · Spring Boot + Redis
public Product getProduct(Long id) {
    String key = "product:" + id;
    Product cached = redis.opsForValue().get(key);
    if (cached != null) return cached;                       // hit

    Product product = productRepo.findById(id).orElseThrow(); // miss: read the database
    redis.opsForValue().set(key, product, Duration.ofHours(1));
    return product;
}

public void updateProduct(Product product) {
    productRepo.save(product);                     // 1. update the database
    redis.delete("product:" + product.getId());    // 2. delete the old copy
}

Why it’s popular:

  • It only caches what people use. With millions of products, you don’t waste memory on the ones nobody opens.
  • It survives a dead cache. If Redis goes down, the app just reads the database. Slower, but still working.

The catch:

  • The first read is slow. A miss costs three steps: check the cache, read the database, write the cache.
  • Stale data if a delete fails, or in the race we’ll see below.

Use it for: product catalogs, user profiles, search results. Anything read much more than it’s written.

2. Read-through

Read-through works like cache-aside, but the cache does the loading instead of your code. Your app only ever asks the cache. On a miss, the cache itself fetches from the database, stores it, and returns it.

Why bother? With cache-aside, every developer has to remember the “check, miss, load, save” steps in every method. Read-through puts that logic in one place.

In Spring, the @Cacheable annotation gives you this feel. You write only the database part, and Spring handles the cache around it:

// Java · Spring Cache
@Cacheable(value = "products", key = "#id")
public Product getProduct(Long id) {
    // runs only on a cache miss; Spring saves the result for next time
    return productRepo.findById(id).orElseThrow();
}

Caching libraries like Caffeine (a LoadingCache) and managed caches like Amazon DynamoDB Accelerator (DAX) work as true read-through caches.

Good: cleaner code, the same caching rules everywhere. The catch: less control for special cases, and when something goes wrong, the “magic” is harder to debug.

3. Write-through

Now the write side. In write-through, every write goes to the database and the cache together, and the user waits until both are done. The cache always holds the latest value, so reads right after a write are hits.

// Java · write the database, then the cache
public Product updateProduct(Product product) {
    Product saved = productRepo.save(product);              // database first: it's the source of truth
    redis.opsForValue().set("product:" + saved.getId(), saved, Duration.ofHours(1));
    return saved;
}

Good: the cache stays fresh, and a “read your own update” is always a hit. The catch:

  • Slower writes. Each write pays for the database (10–50 ms) and the cache.
  • Wasted work. You update the cache even for data nobody reads again.

Use it for: data that’s read right after it’s written, like shopping carts, user settings and profiles.

4. Write-back (write-behind)

Write-back flips the order. A write goes only to the cache, and the user gets an answer immediately. A background job sends the changes to the database later, often in batches.

Two timelines side by side. Left, write-through: the user saves, the app writes the database (20 ms) and the cache (1 ms), then replies. Total about 21 ms, and the database is always up to date. Right, write-back: the user saves, the app writes only the cache (1 ms) and replies at once. Every 5 seconds a background job writes a batch of 100 changes to the database. A red warning shows that if the cache crashes before the batch is written, those changes are lost.
Write-through: slower, but the database always has the data. Write-back: very fast, but changes can be lost if the cache crashes before they're saved.

It shines when there are lots of small writes where losing a few isn’t a disaster:

// Java · a page-view counter: fast increments, saved to the database in batches
public void trackView(String pageId) {
    redis.opsForValue().increment("views:" + pageId);   // instant
    // a scheduled job copies the counters to the database every few minutes
}

Good: the fastest writes, and far fewer database calls (100 changes in one batch). The catch: data loss. If the cache crashes before the batch is saved, those writes are gone. The database is also always a little behind.

Use it for: view counts, likes, analytics, game leaderboards. Never for: payments, orders, account balances, stock levels.

If you need write-back speed but can’t lose data, put the changes on a durable queue like Kafka instead of only in memory. A consumer writes them to the database, and if anything crashes, the queue still has them.

How to choose

Strategy Reads Writes Fresh data? Risk Best for
Cache-aside Fast after the first miss Database, then delete the cache Mostly Stale data from races Catalogs, profiles
Read-through Fast after the first miss (pair it with a write strategy) Mostly Harder to debug Same as cache-aside, cleaner code
Write-through Always hits after a write Slower: database + cache Yes Slower writes Carts, settings
Write-back Fast Fastest: cache only Database lags Losing writes Counters, analytics

You don’t have to pick just one. A typical online shop mixes them:

  • Products: cache-aside, with a 24-hour TTL and a delete whenever an admin edits one.
  • Shopping cart: write-through, because the user reads the cart right after adding to it.
  • “Viewed 1,204 times” counter: write-back, because losing a few views doesn’t matter.
  • Account balance and payments: no cache at all.

The classic cache-aside race

Here’s a bug that catches almost everyone using cache-aside. Two requests arrive at nearly the same moment:

A timeline with two lanes. Reader: at step 1, it misses the cache. At step 2, it reads the database and gets the old price, 100 rupees. Writer: at step 3, it updates the database to 80 rupees. At step 4, it deletes the cache entry, which is already empty. Reader again: at step 5, it finally saves its old value, 100, into the cache. Result: the database says 80, the cache says 100, and the wrong price stays until the TTL runs out.
The slow reader saves an old value after the writer has already cleared the cache. Now the cache is wrong until it expires.

The reader loaded the old value just before the update, and saved it after the writer cleared the cache. The cache is now wrong, and nothing will fix it until the TTL runs out.

You can’t remove this race completely with cache-aside, but you can make it rare and short:

  • Always set a TTL. It’s your safety net: a wrong value can only live so long.
  • Delete again, a moment later. After the update, delete the key once more after a short delay (say, half a second). This is called a delayed double delete, and it catches most slow readers.
  • For data that must be exact, like prices at checkout, read from the database.

What breaks, and how to fix it

What breaks What you see The fix
The cache is down during a write-through Users can’t save anything, because the cache write fails and the whole update errors out The database is the source of truth. Save to it, and if the cache write fails, log it and carry on. Delete the key later
Write-back loses data A cache crash wipes out the last few seconds of changes Use write-back only where loss is OK. Otherwise put changes on a durable queue like Kafka
A failed cache delete The database is updated but the cache still has the old value Retry the delete, and keep a TTL as the backstop
The cache-aside race Old value stuck in the cache after an update TTL, plus a delayed second delete

Puzzle 1: two quick price changes

Each request does two steps: write the database, then write the cache. With two requests running at once, the steps can interleave:

  1. Admin A writes ₹100 to the database.
  2. Admin B writes ₹200 to the database. (The database now says ₹200.)
  3. Admin B writes ₹200 to the cache.
  4. Admin A, a little slower, writes ₹100 to the cache. (The cache now says ₹100.)

The last write to the database and the last write to the cache came from different requests. That’s why many teams prefer to delete the cache entry on update instead of setting it. A delete can’t put an old value back. The next read simply loads whatever the database says now.

Puzzle 2: caching a bank balance

None of them. A balance has to be exactly right, every time. A stale balance means approving a withdrawal that should fail. Write-back could even lose a deposit.

Read balances straight from the database. If the database is busy, scale it with read replicas and a good connection pool, not a cache. Save caching for things like the bank’s branch list or exchange-rate tables, which change rarely and can be a little old.

Key takeaways

  1. Cache-aside: the app checks the cache, loads on a miss, and deletes on update. Simple, memory-efficient, and the default choice for reads.
  2. Read-through: the cache loads data for you. Same idea as cache-aside, with the logic in one place.
  3. Write-through: write the database and the cache together. Fresh data, slower writes.
  4. Write-back: write the cache now and the database later. Fastest writes, but you can lose data.
  5. Prefer deleting over updating the cached copy, and always keep a TTL as a safety net.
  6. Mix strategies per type of data, and don’t cache data that must be exact, like balances.

Next in the Performance & caching (deep) thread: a cache can’t keep everything forever. We’ll look at cache eviction and invalidation: what to throw out when memory is full, and how to remove data that’s no longer true.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.