Learn Labs
Application Patterns

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:

appget_product(1)GET cache:product:1hit: return0.1 msmiss: PostgresSELECT … 200 msSET … EX 300±10%then return
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 product
docker compose -f compose_prod.yaml run --rm labs python cache_aside.py

1. hit vs miss
miss:   200.5 ms
hit:      0.1 ms

Cache-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

StrategyOn writeProsCons
Invalidate (cache-aside)Update DB, then DEL the cache keySimple; next read refillsOne miss after each write
Write-throughUpdate DB, then SET the new value in cacheCache always warmCaches data nobody reads; ordering races
Write-behindWrite to cache; flush to DB asynchronouslyFastest writesData loss if Redis fails before the flush
Read-throughA cache layer (not the app) loads on missCleaner app codeNeeds 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.

Invalidation strategies

  1. TTL only: accept staleness up to the TTL. Simplest; right for lots of data.
  2. Delete on write: as above. Requires every code path that writes the data to know the cache key.
  3. 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.
  4. 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 calls
50 requestskey just expired50 DB callsno protection50 requestskey just expiredSET lock NX PX1 winner1 DB call49 wait, then hit

Three 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 cache

Early 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.

Lab

  1. Run cache_aside.py and read the output.
  2. 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).
  3. Add negative caching: when slow_db_get_product returns nothing, cache a sentinel value for 30 seconds.
  4. 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.

On this page