Most caching advice tells you how to store something in Redis and stops there. The hard part was never the store. It is the key you chose and the moment you have to throw it away.
Cache-aside — also called lazy-loading — is the pattern I reach for first on a read-heavy endpoint, because it fails safe. The application, not Redis, owns the data. On a read you look in the cache; on a miss you fetch from the database, populate the cache, and return. If Redis is down or empty, every request simply falls through to the database and the endpoint keeps working, slower. Nothing serves stale data because Redis lied to you. That property is worth more than any clever write-through scheme when you are the one carrying the pager.
This is a recipe on FastAPI 0.115 and redis-py, Redis 7, Python 3.12. It covers the three decisions that actually determine whether the cache helps or quietly corrupts a response: key design, TTLs, and invalidation. Then the two cases everyone gets wrong.
Design the key before you write a line of cache code
A cache key is a contract. Get it wrong and you will serve one tenant’s data to another, or serve last month’s schema to this month’s deserialiser. A key that survives contact with production carries three things beyond the entity identifier:
- A version prefix. When the shape of what you cache changes — a new field, a different serialiser — you bump the version and every old key is orphaned instantly. No migration, no flush, no stale reads. The old keys expire on their own TTL and disappear.
- The tenant. In any multi-tenant system the tenant belongs in the key, always, even when the current query looks global. It is the difference between a bug and a data-protection incident.
- The namespace and identifier. Which entity, which one. Colons are the conventional separator and Redis tooling groups on them.
So v3:acme:invoice:8841, not invoice_8841. It reads well in redis-cli and it tells you at a glance what would break if you deleted it.
A reusable cache-aside decorator
The pattern is identical on every endpoint, so it belongs in one decorator you apply to the loader function rather than logic copied into each route. This version handles serialisation, a per-entity TTL with jitter, and negative caching for the miss.
import functools
import json
import random
import redis.asyncio as redis
CACHE_VERSION = "v3"
MISS = "\x00__miss__" # sentinel for a known-absent entity
# decode_responses=True gives us str in and out, so json handles the payload
r = redis.from_url(
"redis://localhost:6379/0",
encoding="utf-8",
decode_responses=True,
)
def _key(namespace: str, tenant: str, ident: str) -> str:
return f"{CACHE_VERSION}:{tenant}:{namespace}:{ident}"
def cache_aside(namespace: str, ttl: int):
"""Wrap an async loader(tenant, ident) -> dict | None."""
def decorator(loader):
@functools.wraps(loader)
async def wrapper(tenant: str, ident: str):
key = _key(namespace, tenant, ident)
cached = await r.get(key)
if cached is not None:
# a cached miss is still a cache hit
return None if cached == MISS else json.loads(cached)
value = await loader(tenant, ident)
if value is None:
# negative cache, short: stops penetration on absent ids
await r.set(key, MISS, ex=30)
return None
# jitter the TTL so a batch of keys does not expire in lockstep
expiry = ttl + random.randint(0, ttl // 10)
await r.set(key, json.dumps(value), ex=expiry)
return value
return wrapper
return decorator
Three things in there are load-bearing. The negative cache stops cache penetration: without it, requests for an identifier that does not exist miss the cache every time and hammer the database, which is a trivially cheap denial-of-service. The TTL jitter stops a thundering herd — if you warm a thousand keys in one loop with the same TTL, they all expire in the same second and a thousand requests stampede the database together. And the version prefix means a schema change is a one-line edit, not an incident.
Applied to a loader, it disappears into the route:
@cache_aside(namespace="invoice", ttl=300)
async def load_invoice(tenant: str, ident: str) -> dict | None:
row = await db.fetch_invoice(tenant, ident)
return row.model_dump() if row else None
@router.get("/invoices/{invoice_id}")
async def get_invoice(invoice_id: str, tenant: str = Depends(current_tenant)):
invoice = await load_invoice(tenant, invoice_id)
if invoice is None:
raise HTTPException(status_code=404)
return invoice
Invalidate by deleting, never by updating
The single most important rule of cache-aside invalidation: on a write, delete the key. Do not try to write the new value into the cache in the same breath as the database.
Updating the cache on write reintroduces every consistency problem you were trying to avoid. Two concurrent writers race, and whichever loses the race leaves a stale value behind that survives until the TTL. Delete the key instead and the next read is a clean miss that repopulates from the source of truth. Deletion is idempotent, order-independent, and safe under concurrency in a way that a write never is.
async def invalidate(namespace: str, tenant: str, ident: str) -> None:
await r.delete(_key(namespace, tenant, ident))
@router.put("/invoices/{invoice_id}")
async def update_invoice(invoice_id: str, body: InvoiceIn,
tenant: str = Depends(current_tenant)):
await db.update_invoice(tenant, invoice_id, body)
await invalidate("invoice", tenant, invoice_id) # delete after the commit
return {"status": "updated"}
Delete after the database commit, not before. If you delete first and the write then fails, a concurrent read can repopulate the cache with the old value and you are stale again.
The two cases that bite: bulk invalidation and list caches
Single-entity invalidation is easy. The two that catch people are wiping a whole tenant and caching lists.
Bulk invalidation. When a tenant changes something that touches many entities, you need to clear a swathe of keys. Do not use KEYS — it blocks the whole server while it scans the keyspace. Use scan_iter, which walks the keyspace in cursored batches without blocking, and unlink, which frees the memory on a background thread rather than inline:
async def invalidate_tenant(tenant: str) -> None:
pattern = f"{CACHE_VERSION}:{tenant}:*"
async for key in r.scan_iter(match=pattern, count=500):
await r.unlink(key)
That is fine for occasional administrative wipes. If you find yourself doing it on a hot path, the design is wrong — reach for a version segment in the key instead (v3:acme:9:invoice:8841, where 9 is a per-tenant counter you bump to orphan the lot in one command).
List caches. Caching GET /invoices?status=open&page=2 is where cache-aside gets genuinely hard, because a single write can invalidate an unknowable number of cached list pages. You cannot enumerate which filtered, paginated, sorted views a new invoice belongs to. Do not try. Two honest options: give list caches a deliberately short TTL — 15 to 60 seconds — and accept brief staleness, which is almost always acceptable for a list view; or, when it is not, cache lists under a namespace you version-bump on any write to that entity type, so every list key for the tenant is orphaned at once. Trying to selectively invalidate individual list pages is a trap that produces subtle, unreproducible staleness bugs. Cache the single entity precisely; cache the list loosely.
Where the cache sits in the stack
Cache-aside earns its place on genuinely read-heavy endpoints where the same entities are fetched far more often than they change. It is not free — it adds a second system to reason about, and every cached value is a small bet that your invalidation is correct. Put it where the read-to-write ratio justifies that bet, and nowhere else.
The same Redis you use here does double duty across an API stack — it is the store behind idempotency keys that make POST safe to retry and the broker behind Celery when you offload slow work off the request path. Keep the concerns in separate logical databases or key prefixes so a cache flush never touches your idempotency records or your task queue.
Get the key right and invalidation is a delete. Get the key wrong and no amount of clever invalidation will save you.
Free interactive tool
Website compliance checklist
What your site has to do, based on what it actually does
Answer as much or as little as you like — the list builds as you go. Nothing is stored against your name and no email is required.
Everything that applies
Ordered by what to do first: legal requirements you can close quickly, then larger pieces of work, then what is expected rather than required. Not exhaustive, and not a legal audit.
Dated PDF, yours to keep or circulate.
Most technology problems are not technology problems. They are control problems.
The systems exist. The investment has been made. The question is whether leadership can understand, direct, evidence, and sustain what those systems produce. Find out where control exists — and where it only appears to.