Write-Through Caching with Redis and FastAPI

With plain cache-aside caching, an update to the database leaves the cached copy stale until it expires or is deleted. Write-through caching updates the cache as part of every write, so reads after an update return the new value straight from the cache instead of a stale copy or a database round trip.
This guide implements write-through caching for a FastAPI service with Redis, using the async Redis client so cache calls don't block the event loop. It also covers the consistency gaps that remain even with write-through, which most introductions skip. If you're new to caching in general, start with our cache-aside guide for Laravel. This post builds on that pattern.
When Caching Helps
Caching pays off when the same records are read far more often than they change, such as product pages, user profiles or configuration. Each cache hit saves a database query and a network round trip. Caching does little for data that's read once, or for queries that are rarely repeated with the same parameters.
Why Redis
Redis keeps data in memory, so typical reads and writes complete in well under a millisecond on a local network. It supports per-key expiry (TTL) and data structures beyond plain strings, and most languages have a mature client for it.
How Write-Through Works
The common patterns differ in what happens on a write:
- Cache-aside with invalidation: write to the database, then delete the cache key. The next read repopulates it.
- Write-through: write to the database, then write the new value to the cache.
- Write-back (write-behind): write to the cache only, and flush to the database later. Writes are fastest, but data can be lost if the cache fails before the flush.
What is Write-Through Caching?
In textbook write-through, the application writes to the cache and the cache layer writes to the database synchronously. Redis doesn't write to databases itself, so in practice the application does both: it commits to the database first (the source of truth), then writes the same value to Redis. The write counts as successful once the database commit succeeds.
Benefits:
- Fresh reads after writes: a read after an update returns the new value from the cache, without a miss.
- Warm cache for updated records: records that were just written are already cached. Reads still use cache-aside logic for keys that expired or were never written.
- Reduced Database Load: Once data is in the cache, subsequent reads for that data bypass the database entirely, reducing its workload.
Trade-offs:
- Increased Write Latency: Write operations take longer because they involve two steps (writing to cache and writing to DB).
- Not strongly consistent: the database commit and the Redis write are two separate operations. If the process crashes between them, or if two requests race (see below), the cache can hold an old value. Keep a TTL so any such error heals itself.
- Caches data that may never be read: every write fills the cache, even for records nobody reads.
When to Use Write-Through
Write-through fits when:
- Records are read often and updated regularly, and users expect to see their own updates immediately (profiles, settings, carts).
- All writes go through one service that can update the cache. If other systems write to the same tables directly, the cache won't see those changes, so invalidate via change events or rely on short TTLs.
Implementation: FastAPI and Redis
Let's walk through an example using Python with FastAPI and Redis to implement write-through caching for user profile data.
Our Goal: Create an API that can retrieve and update user profiles, ensuring that frequently accessed user data is served quickly from Redis while maintaining consistency with our underlying (simulated) database.
Step 1: Set up Redis and Python Environment
First, you'll need a running Redis instance. The easiest way is via Docker:
docker run --name my-redis -p 6379:6379 -d redis:7Next, install the required Python libraries:
pip install fastapi uvicorn "redis>=5" pydanticStep 2: Implement the API with Write-Through Logic
The read endpoint uses cache-aside, and the update endpoint uses write-through. The "database" is a dictionary with artificial delays so the difference is visible. Note the redis.asyncio import: calling the synchronous client inside an async def endpoint blocks the event loop and stalls every other request while it waits.
import asyncio
import json
import redis.asyncio as redis
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
CACHE_TTL_SECONDS = 300
app = FastAPI(title="User API with write-through caching")
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
# Stand-in for a real database
fake_db = {
"1": {"id": "1", "name": "Alice Smith", "email": "alice@example.com", "role": "admin"},
"2": {"id": "2", "name": "Bob Johnson", "email": "bob@example.com", "role": "user"},
}
async def fetch_user_from_db(user_id: str) -> dict | None:
print(f"DB read: user {user_id}")
await asyncio.sleep(0.1) # simulated query latency
user = fake_db.get(user_id)
return dict(user) if user else None
async def save_user_to_db(user_id: str, data: dict) -> None:
print(f"DB write: user {user_id}")
await asyncio.sleep(0.15) # simulated write latency
fake_db[user_id] = data
class User(BaseModel):
id: str
name: str
email: str
role: str
class UserUpdate(BaseModel):
name: str | None = None
email: str | None = None
role: str | None = None
def cache_key(user_id: str) -> str:
return f"user:v1:{user_id}" # version prefix lets you change the cached shape safely
@app.get("/users/{user_id}", response_model=User)
async def get_user(user_id: str):
cached = await r.get(cache_key(user_id))
if cached is not None:
return json.loads(cached)
user = await fetch_user_from_db(user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
await r.set(cache_key(user_id), json.dumps(user), ex=CACHE_TTL_SECONDS)
return user
@app.put("/users/{user_id}", response_model=User)
async def update_user(user_id: str, changes: UserUpdate):
user = await fetch_user_from_db(user_id) # always merge with the source of truth
if user is None:
raise HTTPException(status_code=404, detail="User not found")
user.update(changes.model_dump(exclude_unset=True))
await save_user_to_db(user_id, user) # 1. commit to the database
try:
# 2. write-through: cache the value we just committed
await r.set(cache_key(user_id), json.dumps(user), ex=CACHE_TTL_SECONDS)
except redis.RedisError:
# The database write succeeded, so don't fail the request.
# Try to remove the old value; the TTL bounds staleness if this fails too.
try:
await r.delete(cache_key(user_id))
except redis.RedisError:
pass
return userSave the code as main.py and run it with uvicorn main:app --reload.
Test Sequence:
First GET request (cache miss):
Bashcurl http://localhost:8000/users/1The console prints
DB read: user 1.Second GET request (cache hit):
Bashcurl http://localhost:8000/users/1No database read is logged, and the response returns without the simulated 100 ms delay.
PUT request (write-through):
Bashcurl -X PUT -H "Content-Type: application/json" -d '{"name": "Alicia Smith"}' http://localhost:8000/users/1The console shows the read used for merging and the database write. The cache now holds the new name.
GET request after PUT (cache hit with new data):
Bashcurl http://localhost:8000/users/1The response shows "Alicia Smith" with no database read.
The Races Write-Through Doesn't Fix
Two concurrent operations can still leave a stale value in the cache:
- Two updates: request A commits
name=X, request B commitsname=Y, then B writesYto Redis and A writesX. The database saysY, but the cache saysXuntil the TTL expires. - A slow read and an update: a read misses the cache and loads the old row, an update commits and caches the new value, and then the slow read finishes and overwrites the cache with the old row.
Ways to narrow or close these gaps:
- Delete instead of set on writes (cache-aside invalidation). This removes the first race, and the next read loads the committed value. You give up the warm cache after writes.
- Store a version number (or
updated_at) with each record and only overwrite the cached copy if the new version is higher. A small Lua script run withEVALcan do the compare-and-set atomically in Redis. - Keep TTLs short enough that the worst-case staleness is acceptable for the data.
💡 Tip: Cache the serialized API response shape, not ORM objects, and put a version prefix in the key (
user:v1:). When the shape changes, bump the prefix, and old entries simply expire instead of breaking deserialization.
Testing and Monitoring Your Cache
redis-cli INFO stats reports keyspace_hits and keyspace_misses, from which you can calculate the hit ratio, plus evicted_keys. INFO memory shows memory use against maxmemory. For a cache, set a maxmemory limit and an eviction policy such as allkeys-lru, so Redis evicts old entries instead of rejecting writes when it fills up. Compare API latency and database query rates before and after enabling the cache to confirm it's helping.
Summary
- Write-through keeps updated records fresh in the cache: commit to the database first, then cache the committed value.
- It isn't strongly consistent. Concurrent writes and slow reads can still cache stale data. Use TTLs, and versioned compare-and-set if staleness matters.
- Use the async Redis client in async frameworks so cache calls don't block the event loop.
- Don't fail a write because the cache is down: the database commit is what counts. Delete or let the TTL expire the stale entry.
- Watch hit ratio and evictions to confirm the cache earns its memory.
