Caching strategies

Topic 2 of 9 in Week 4: Caching, queues and content delivery10 min readIntermediateFree course

Overview

Adding a cache raises two questions: how does data get into the cache, and how do writes reach the database? The answers are a handful of standard strategies. Each one makes a different trade-off between freshness, write speed, complexity and the risk of losing data.

Three common patterns

Three ways to use a cache. Cache-aside (lazy): the app first gets the value from the cache (1); on a miss it reads the database (2), then sets the value in the cache (3); simple, but stale until expiry. Write-through: the app writes to the cache (1), which writes to the database (2) in the same operation; the cache stays fresh but writes are slower. Write-behind: the app writes to the cache (1) and the cache writes to the database later (2); writes are fast but data can be lost.

Cache-aside (lazy loading)

The application manages the cache explicitly:

Text
read(key):
  value = cache.get(key)
  if value is missing:
      value = db.query(key)
      cache.set(key, value, ttl = 10 minutes)
  return value
  • Pros: simple; only data that’s actually read gets cached; if the cache is down, the app still works (slower) by reading the database.
  • Cons: the first read of each key is slow (a miss); data can be stale until it expires or is invalidated.

This is the default choice in most designs.

Read-through

Like cache-aside, but the cache library or service loads the missing data itself, so application code just calls cache.get(key). Same trade-offs, cleaner code. Common in caching libraries and some managed caches.

Write-through

Every write goes to the cache and the database as one operation, so the cache always holds the latest value.

  • Pros: reads after writes are fresh; no stale window for written keys.
  • Cons: writes are slower (two systems); the cache fills with data that may never be read; you still need a strategy for keys that were never written through.

Write-behind (write-back)

Writes go only to the cache; the cache flushes them to the database later, often in batches.

  • Pros: very fast writes; batching collapses many updates into one (great for counters and metrics).
  • Cons: if the cache node dies before flushing, those writes are lost; the database is temporarily behind, which matters for anything else reading it.

Use it for data where losing a few seconds is acceptable: view counts, likes, analytics.

Write-around

Writes go straight to the database and skip the cache; entries are cached only when read. Useful for bulk writes that would otherwise flush useful data out of the cache.

Updating cached data correctly

When data changes, you have two options for the cached copy:

  • Update it (cache.set(key, newValue))
  • Delete it (cache.delete(key)), and let the next read reload it.

Deleting is usually safer. Consider two concurrent writers that update the database and then the cache: if their cache updates arrive in the opposite order to their database writes, the cache ends up holding the older value indefinitely. With deletion, the worst case is an extra cache miss.

The usual order is update the database first, then delete the cache entry. A small race remains (a reader can load the old value just before the write commits and store it after the delete), so also keep a TTL as a safety net. Some systems delete twice, once immediately and once a moment later (“delayed double delete”), or drive invalidation from the database’s change stream so no update is missed.

Choosing a strategy

Need Strategy
General read-heavy data Cache-aside + TTL + delete on update
Fresh reads right after writes Write-through, or read your own writes from the database
Extremely high write rates, loss tolerable Write-behind
Bulk writes of rarely read data Write-around

In an interview

Say the pattern by name and the invalidation rule: “Cache-aside in Redis with a 5-minute TTL; on profile update we write the database and delete the key.” If the interviewer asks about consistency, explain the delete-versus-update race and the TTL safety net.

Recap

Cache-aside and read-through fill the cache on demand; write-through keeps it fresh by writing both at once; write-behind makes writes fast by flushing later at some risk; write-around keeps bulk writes out of the cache. On updates, write the database and delete the cached entry, and keep TTLs as a backstop for the races that remain.

Exercise

Pick a strategy

Choose a caching strategy for each case and explain the trade-off: (a) product detail pages that are read 1,000 times for every update; (b) a 'likes' counter on posts that receives thousands of increments per second on viral posts; (c) user profile settings that must show the new value immediately after the user saves them; (d) a nightly import that writes 50 million rows, most of which nobody will read soon.

Text
(a)
(b)
(c)
(d)

Summary

  • Cache-aside: the application reads the cache, loads from the database on a miss and fills the cache; the most common pattern.
  • Read-through: the cache itself loads missing data from the database.
  • Write-through: writes update the cache and the database together, keeping the cache fresh at the cost of slower writes.
  • Write-behind: writes go to the cache and reach the database later in batches; fast, but data can be lost.
  • On updates, prefer deleting the cache entry over overwriting it, to avoid races that leave stale data.