Cache-aside, read-through, write-through, write-behind and refresh-ahead
Compare the mechanics, trade-offs, consistency limits and failure modes of five cache access patterns, and implement cache-aside and refresh-ahead safely.
Contentsand lesson path
On this page
- Why it matters
- Read path: cache-aside and read-through
- Write path and refresh: write-through, write-behind and refresh-ahead
- Check your understanding
- Apply it
- Review prompt
Lessons of Caching Strategies
- Cache layers, from HTTP caching to the database Concept · 20 min
- Cache-aside, read-through, write-through, write-behind and refresh-ahead Concept · 25 min
- Invalidation, TTLs, HTTP revalidation and the staleness budget Concept · 20 min
- Hit-ratio math and sizing a cache tier Worked example · 25 min
- Surviving stampedes and hot keys Lab · 30 min
- Caching check Knowledge check · 8 questions
What you will learn
- Choose cache placement (HTTP client and CDN, reverse proxy, application, database) and a pattern (cache-aside, read-through, write-through, write-behind, refresh-ahead) for a read/write profile.
01. Why it matters
A cache only helps if the way your code reads and writes through it fits the workload. The same Redis cluster can halve database load for one endpoint and serve stale prices, lose writes or overload the database for another, depending on the pattern around it.
Each pattern answers three questions differently: who loads data on a miss, when a write reaches the database, and what happens when the cache is slow or down. Get these wrong and the failures are quiet until they are expensive: a read path that dies with the cache cluster, counters that lose an hour of updates in a restart, or a hot key that sends thousands of identical queries to the database at once.
This lesson compares cache-aside, read-through, write-through, write-behind and refresh-ahead on those questions, then shows a safe implementation of the two you will write most often yourself.
02. Read path: cache-aside and read-through
A caching design decides how the application, the cache and the authoritative database interact. The two main patterns for reads are cache-aside and read-through.
Cache-aside (lazy loading). In cache-aside, the application code runs every cache and database operation itself. The cache (such as Redis or Memcached) knows nothing about the database.
- Read flow: the application asks the cache first. On a hit it decodes and returns the cached value. On a miss it queries the database, writes the result into the cache with a time-to-live (TTL), and returns it.
- Strengths: only data that is actually read takes up cache memory. A cache outage need not take the service down: if the application catches cache errors and falls back to the database, it keeps working, more slowly, as long as the database can take the extra load.
- Weaknesses: the first request for a key pays for a miss, a database query and a cache write, which raises tail latency for cold keys. Data can also go stale when the database changes and nothing deletes or updates the cached copy.
Read-through caching. In read-through caching, the application reads only from the cache, and the cache layer is configured with a loader that knows how to fetch from the database.
- Read flow: the application calls
cache.get(key). On a miss, the cache layer runs the loader, stores the result and returns it. - Strengths: application code stays free of caching boilerplate, and every service that uses the cache loads data the same way.
- Weaknesses: the cache layer must understand your data source, through a library or a plugin. If the cache layer is unavailable, reads fail unless you build a separate fallback path to the database.
03. Write path and refresh: write-through, write-behind and refresh-ahead
Read patterns decide how data gets into the cache. Write patterns decide how changes reach the cache and the database, trading write latency against consistency.
Write-through caching. With write-through, the application sends every write to the caching layer, which writes it synchronously to the database and updates the cache entry before confirming success.
- Strengths: a read straight after a write usually finds the new value in the cache, and cache and database stay close together.
- Weaknesses: each write waits for both the cache and the database commit. Data that is written but never read again still fills memory and can push hot keys out. If the cache write succeeds and the database write fails (or the reverse), you need a rule for which one wins.
Write-behind (write-back) caching. With write-behind, the application writes to the cache, which confirms at once. The cache layer queues or batches the changes and writes them to the database later, on a schedule or when a batch fills.
- Strengths: write throughput is very high. High-frequency updates such as view counters, click events or game positions can be combined in memory and written in bulk, which can cut database writes by a large factor when many updates hit the same keys.
- Failure modes: if a cache node loses power or is killed before it flushes, the unflushed changes are gone. Write-behind therefore suits counters, telemetry and other data where losing a bounded window of updates is an accepted trade-off.
Refresh-ahead caching. Refresh-ahead targets the latency spikes that hot keys cause when they expire. Instead of waiting for a miss, the system reloads an entry in the background shortly before its TTL runs out, as long as the key is still being read.
- Strengths: readers of a hot key keep getting cached responses, so the periodic tail-latency spike of a synchronous rebuild largely disappears.
- Considerations: without coordination, every reader that notices the short TTL starts its own refresh, and a hot key then sends a burst of identical queries to the database. Refresh only keys that are still in demand, and let one caller do it.
The example below implements cache-aside with delete-on-write, and refresh-ahead guarded by a short lock. Note two choices:
- Values are stored as JSON. Never decode cache contents with
eval()orpickle: anyone who can write to the cache (an exposed Redis, a compromised neighbouring service, a value built from user input) could then run code in every API worker.json.loadsonly ever produces data. - One refresh per key. On one Redis primary,
SET refresh-lock:<key> 1 NX EX 30succeeds for exactly one caller until the lock expires, so only that caller schedules the refresh. The task is kept in a set until it finishes, because the event loop holds only a weak reference to tasks and an unreferenced task can be garbage-collected before it completes.
import asyncio
import json
import time
import redis.asyncio as aioredis
# A short timeout: a slow cache must not hold every request hostage
redis = aioredis.from_url("redis://localhost:6379/0", socket_timeout=0.5)
TTL = 300 # seconds
REFRESH_WINDOW = 30 # refresh when fewer seconds than this remain
_background: set[asyncio.Task] = set() # keep task references alive
db_calls = 0
async def fetch_user_profile_db(user_id: str) -> dict:
global db_calls
db_calls += 1
await asyncio.sleep(0.04) # stands in for a PostgreSQL query
return {"user_id": user_id, "tier": "gold", "updated_at": time.time()}
# Pattern 1: cache-aside with delete-on-write
async def get_user_profile_cache_aside(user_id: str) -> dict:
cache_key = f"profile:{user_id}"
cached = await redis.get(cache_key)
if cached is not None:
return json.loads(cached) # data only: never eval() cache contents
profile = await fetch_user_profile_db(user_id)
await redis.set(cache_key, json.dumps(profile), ex=TTL)
return profile
async def update_user_profile(user_id: str, new_tier: str) -> None:
# 1. Commit to the database first (UPDATE users SET tier = ... in real code)
# 2. Then delete the cached copy so the next read reloads it
await redis.delete(f"profile:{user_id}")
# Pattern 5: refresh-ahead with a lock so one caller refreshes a hot key
async def get_with_refresh_ahead(user_id: str) -> dict:
cache_key = f"profile:{user_id}"
cached = await redis.get(cache_key)
if cached is None:
return await get_user_profile_cache_aside(user_id)
ttl = await redis.ttl(cache_key)
if 0 < ttl < REFRESH_WINDOW:
# SET NX succeeds for exactly one caller until the lock expires
if await redis.set(f"refresh-lock:{cache_key}", 1, nx=True, ex=REFRESH_WINDOW):
task = asyncio.create_task(refresh_key(user_id, cache_key))
_background.add(task)
task.add_done_callback(_background.discard)
return json.loads(cached)
async def refresh_key(user_id: str, cache_key: str) -> None:
fresh = await fetch_user_profile_db(user_id)
await redis.set(cache_key, json.dumps(fresh), ex=TTL)To see the difference, the script below replaces Redis with a small in-memory fake, stores a key with 20 seconds left, and sends 1,000 concurrent reads, first through a refresh-ahead version without the lock and then through get_with_refresh_ahead. It also shows that json.loads rejects a payload that eval() would have executed. It needs only pip install "redis==8.1.0", not a running Redis server.
import asyncio
import json
import time
import profile_cache as pc
class FakeRedis:
"""In-memory stand-in for the few Redis commands used (no server needed)."""
def __init__(self):
self.data = {} # key -> (value, expires_at)
async def get(self, key):
value, expires = self.data.get(key, (None, 0))
return value if expires > time.monotonic() else None
async def set(self, key, value, ex, nx=False):
if nx and await self.get(key) is not None:
return None
self.data[key] = (str(value).encode(), time.monotonic() + ex)
return True
async def ttl(self, key):
return int(self.data[key][1] - time.monotonic()) if key in self.data else -2
async def delete(self, key):
self.data.pop(key, None)
async def naive_refresh_ahead(user_id):
# The pattern without a lock: every caller in the window starts a refresh
cache_key = f"profile:{user_id}"
cached = await pc.redis.get(cache_key)
if 0 < await pc.redis.ttl(cache_key) < pc.REFRESH_WINDOW:
asyncio.create_task(pc.refresh_key(user_id, cache_key))
return json.loads(cached)
async def burst(reader):
pc.redis, pc.db_calls = FakeRedis(), 0
await pc.redis.set("profile:42", json.dumps({"tier": "gold"}), ex=20)
await asyncio.gather(*(reader("42") for _ in range(1000)))
await asyncio.sleep(0.1) # let background refreshes finish
return pc.db_calls
async def main():
without_lock = await burst(naive_refresh_ahead)
print("1000 reads at TTL 20 s, no lock: DB queries =", without_lock)
with_lock = await burst(pc.get_with_refresh_ahead)
print("1000 reads at TTL 20 s, with lock: DB queries =", with_lock)
poisoned = b'__import__("os").getpid()'
try:
json.loads(poisoned)
except json.JSONDecodeError as exc:
print("json.loads refuses code in the cache:", exc.msg)
asyncio.run(main())$ python simulate.py
1000 reads at TTL 20 s, no lock: DB queries = 1000
1000 reads at TTL 20 s, with lock: DB queries = 1
json.loads refuses code in the cache: Expecting value04. Check your understanding
05. Apply it
When you add caching to a backend service, start from these rules:
- Default to cache-aside for general web APIs. Catch cache errors and fall back to the database, and check that the database can take the extra load while the cache is down.
- Invalidate on write rather than updating the cached value. After the database commit, delete the key (
DEL user:123) instead of setting a new value. This avoids two writers racing their SETs and leaving the older value in the cache, but it does not close every race: a slow reader can still read the old row before the commit and store it after the delete. Keep a TTL as the upper bound on staleness, or use versioned keys or values, covered in the invalidation lesson. - Use write-behind only where losing a few seconds of updates is acceptable, such as counters, page views or game positions.
- Use refresh-ahead for hot, expensive keys such as catalogue menus or feature-flag sets, always with a per-key lock or request coalescing.
- Store data, not code. Serialise with JSON (or a schema-based format such as MessagePack with plain types), never with
repr/evalorpicklefor values others could write.
In the next lesson, you will look at invalidation strategies, TTLs, HTTP revalidation and how to state a staleness budget.
06. Review prompt
Without looking back, compare the five patterns: cache-aside, read-through, write-through, write-behind and refresh-ahead. Explain why write-behind reaches high write throughput and what it can lose on a crash, why cache-aside beats write-through when most written records are never read, why delete-on-write still needs a TTL, and why refresh-ahead needs a lock on hot keys.
References
- Microsoft Azure Architecture Center: Cache-Aside Pattern
- AWS: Database Caching Strategies Using Redis
- Redis documentation: SET (NX and EX options)
- Python documentation: asyncio.create_task (keep a reference to tasks)
- Python documentation: eval() runs arbitrary code
- Scaling Memcache at Facebook (NSDI 2013): leases against stale sets
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.