Caching
Cache-aside, write strategies, invalidation, and stampede protection
Caching is the most common reason teams adopt Redis, and the easiest to get subtly wrong. A cache trades freshness for speed and database load. Every design decision below is about controlling that trade.
Cache-aside (lazy loading)
The application owns the logic. Redis knows nothing about the database:
def get_product(pid: str) -> dict:
key = f"cache:product:{pid}"
cached = r.get(key)
if cached is not None:
return json.loads(cached)
product = slow_db_get_product(pid) # ~200ms
r.set(key, json.dumps(product), ex=ttl_with_jitter())
return productdocker compose -f compose_prod.yaml run --rm labs python cache_aside.py
1. hit vs miss
miss: 200.5 ms
hit: 0.1 msCache-aside is the default for good reasons: only data that's actually read gets cached, and if Redis is down the app can fall back to the database (slower, but working).
Write strategies
| Strategy | On write | Pros | Cons |
|---|---|---|---|
| Invalidate (cache-aside) | Update DB, then DEL the cache key | Simple; next read refills | One miss after each write |
| Write-through | Update DB, then SET the new value in cache | Cache always warm | Caches data nobody reads; ordering races |
| Write-behind | Write to cache; flush to DB asynchronously | Fastest writes | Data loss if Redis fails before the flush |
| Read-through | A cache layer (not the app) loads on miss | Cleaner app code | Needs a library or proxy |
Prefer delete over update. After changing a row, DEL the key
rather than SETting the new value. Two concurrent writers that each
SET can leave the older value in the cache if their writes to
Redis arrive in the opposite order from their writes to the database. A
DEL can't be reordered into staleness the same way.
Even "update DB, then delete cache" has a race: a reader misses, reads the old row from the DB, the writer updates the DB and deletes the key, then the reader writes the old value into the cache. It's rare, and the TTL bounds how long it lasts. That's one more reason every cache key needs a TTL: it's the backstop for every invalidation bug.
Invalidation strategies
- TTL only: accept staleness up to the TTL. Simplest; right for lots of data.
- Delete on write: as above. Requires every code path that writes the data to know the cache key.
- Change data capture: a process reads the database's change log (Postgres logical replication, Debezium → Kafka) and deletes cache keys. Catches writes that bypass the application.
- Versioned keys: include a version in the key (
cache:v7:product:1). Bumping the version invalidates everything at once; the old keys age out by TTL.
Cache stampede
When a hot key expires, every request that misses at that moment goes to the database at once. With 1,000 requests a second on one key and a 200 ms query, that's 200 concurrent identical queries:
2. cache stampede on an expired hot key
no protection: 50 concurrent requests -> 50 database calls
with rebuild lock: 50 concurrent requests -> 1 database callsThree defences, from simplest:
TTL jitter stops many different keys expiring together.
A rebuild lock lets only one caller recompute a missing key while the others wait briefly and re-check:
if r.set(lock_key, "1", nx=True, px=5000): # only one caller wins
try:
product = slow_db_get_product(pid)
r.set(key, json.dumps(product), ex=ttl_with_jitter())
return product
finally:
r.delete(lock_key)
time.sleep(0.02) # others wait, then retry the cacheEarly recomputation refreshes a key before it expires: store the value with a soft expiry time inside it, and when a reader sees it's past the soft time, one reader refreshes in the background while everyone keeps getting the slightly stale value. "Probabilistic early expiration" (XFetch) makes the refresh more likely as expiry approaches.
Other failure modes
Cache penetration: requests for keys that don't exist anywhere
(product:99999999) always miss and always hit the DB, which is a cheap
attack. Cache the "not found" result too (a short TTL), or check a
Bloom filter first.
Cold start: after a flush or failover to an empty replica, every request misses at once. Warm critical keys before taking traffic, or ramp traffic gradually.
Redis down: decide in advance whether the app falls back to the database (and whether the database can take the full load) or fails fast. Use short client timeouts (tens of milliseconds) so a slow Redis doesn't make every request slow.
Measure the cache. The two numbers that matter are the hit ratio
(keyspace_hits / (hits + misses), on the Redis Overview dashboard)
and the database load it removes. A cache with a 30% hit ratio is
mostly overhead. Usually the fix is a better key choice or longer TTLs,
not more memory.
Lab
- Run
cache_aside.pyand read the output. - Edit it to remove the jitter, then write 1,000 keys with the same TTL
and watch them expire together in
INFO stats(expired_keys). - Add negative caching: when
slow_db_get_productreturns nothing, cache a sentinel value for 30 seconds. - Stretch: put a cache in front of a real table in the Postgres module, measure hit ratio on the Grafana dashboard, then update a row and verify the cached value is invalidated.