Mental model
Cache-Aside (Lazy Loading) places a sub-millisecond in-memory store (Redis) directly beside PostgreSQL under explicit application control: reads check Redis first, fall back to PostgreSQL on a cache miss, populate Redis with a bounded TTL, and writes mutate PostgreSQL followed by cache key deletion (not read-through blind mutation). While cache-aside eliminates unnecessary caching of cold keys and keeps storage failures non-fatal, naive expiry allows a sudden Thundering Herd (Cache Stampede) when a hot key expires under 2,000 req/s and every worker simultaneously fires identical expensive SQL joins at PostgreSQL.
Theory
Operating Redis cleanly in production means solving three distinct concurrency hazards beyond simple GET/SET: cache stampedes, stale race overwrites during invalidation, and cache penetration on nonexistent IDs.
| Hazard | Root Cause | Production Defense Pattern | Trade-Off / Caveat |
|---|---|---|---|
| Cache Stampede (Thundering Herd) | Hot key TTL expires; N workers query DB concurrently | Distributed Singleflight Lock (SET lock_key token NX EX 5) + jittered TTL | Followers poll briefly (25–50 ms) or read stale backup key |
| Stale Overwrite Race | Slow reader writes old DB snapshot over newer writer commit | Delete key after DB COMMIT + short TTL or versioned key suffix (:v42) | Delayed second delete or Lua CAS prevents rare concurrent reader races |
| Cache Penetration (Missing Keys) | Malicious or buggy traffic floods nonexistent IDs (user:-999) | Negative Caching (store __NULL__ sentinel with 30 s TTL) or Bloom filter | Protects PostgreSQL from repetitive index misses on 404 lookups |
| Synchronized Expiry Waves | Batch job seeds 50k keys at identical EX=3600 | TTL Jitter (base_ttl + random.randint(0, int(base_ttl * 0.15))) | Spreads DB cache refreshes smoothly over minutes instead of cliff spikes |
Distributed Locks, Lua Safe Unlocking, and Stale-While-Revalidate
On cache miss for expensive payloads, only one worker holding an atomic SET lock:{key} {owner_token} NX EX 5 should hit PostgreSQL. Crucially, unlock via a Lua compare-and-delete script comparing the caller's unique owner_token before running DEL; calling raw DEL lock:{key} blindly risks deleting another worker's newly acquired lock if GC pauses or slow SQL caused your first lock's 5-second lease to expire early! For ultra-sensitive hot keys (homepage catalogs, feature flags), pair short fresh metadata (logical_expire_at) with a longer physical Redis TTL (2x) so readers serve slightly stale cached data immediately while a background task refreshes asynchronously (Stale-While-Revalidate), achieving zero tail-latency spikes on expiry.
pythonimport asyncioimport jsonimport randomimport uuidimport redis.asyncio as aioredisredis_client = aioredis.from_url("redis://redis-cluster:6379/0", decode_responses=True)UNLOCK_LUA = """if redis.call("GET", KEYS[1]) == ARGV[1] thenreturn redis.call("DEL", KEYS[1])endreturn 0"""async def get_user_profile_cached(user_id: int, fetch_from_pg) -> dict | None:cache_key = f"profile:v1:{user_id}"lock_key = f"lock:{cache_key}"# 1. Fast path: Redis Cache HIT (including negative sentinel)cached = await redis_client.get(cache_key)if cached is not None:return None if cached == "__NULL__" else json.loads(cached)# 2. Miss: Attempt singleflight distributed lock with unique owner tokenowner_token = str(uuid.uuid4())acquired = await redis_client.set(lock_key, owner_token, nx=True, ex=5)if not acquired:# Follower backoff + retry read so only 1 worker hits PostgreSQLawait asyncio.sleep(0.04)retry = await redis_client.get(cache_key)if retry is not None:return None if retry == "__NULL__" else json.loads(retry)return await fetch_from_pg(user_id)try:profile = await fetch_from_pg(user_id)if profile is None:# Negative cache prevents DB penetration on invalid IDsawait redis_client.set(cache_key, "__NULL__", ex=30)return Nonettl_with_jitter = 300 + random.randint(0, 45)await redis_client.set(cache_key, json.dumps(profile), ex=ttl_with_jitter)return profilefinally:await redis_client.eval(UNLOCK_LUA, 1, lock_key, owner_token)
Also wrap Redis network operations (redis_client.get/set) in strict timeouts (socket_timeout=0.5, circuit breaker fallback) so a degraded Redis instance degrades gracefully to PostgreSQL or stale local L1 cache rather than crashing API routes with 500 Internal Server Error.
Alternatives and trade-offs
- Redis Cache-Aside (External Shared Cache): Shared hit rate across 50+ stateless FastAPI containers, centralized invalidation (
DEL), atomicSET NX EXlocks, and survival across pod restarts; adds one network hop (~0.3–0.8 ms) and JSON/MsgPack serialization CPU. - Two-Tier L1 In-Process (
TTLCache/LRU) + L2 Redis: Eliminates network hops completely for immutable or ultra-hot configuration keys (0.005 ms), at the cost of cross-pod staleness (5–30 s) until short local L1 TTLs expire or Pub/Sub invalidation propagates. - PostgreSQL Unindexed Read Optimization / Materialized Views: Zero distributed consistency split when read query latency is already sub-millisecond on Primary/Replica shared buffers—never add Redis complexity unless PostgreSQL read profiles or compute transformations justify the cache tier.
Failure modes and misconceptions
- Updating Cache Instead of Deleting on Write (
UPDATE DB -> SET Cache): Concurrent updates arriving out-of-order (Write Ahits DB first,Write Bhits DB second,Write Bwrites Redis first,Write Aoverwrites Redis last) leave permanent stale data until TTL expiration. AlwaysDELcache keys after the databaseCOMMIT, or key entries monotonically by monotonic version/timestamp. - Unsafe Raw
DEL lock_keyLock Release: If worker A stalls6 secondspast a5-secondlock TTL, worker B legitimately acquires the lock—and then worker A wakes up and callsDEL lock_key, releasing B's live lock! Always validate ownership atomically via a Lua script (GET == ARGV[1] -> DEL). - Un-Jittered Mass Cache Warmups / Synchronized Expirations: Seeding
100,000product keys at midnight with exactEX=3600triggers synchronized stampedes at01:00every hour. Add10%–20%random jitter to every TTL. - Hard-Failing Requests When Redis Unreachable: Letting uncaught
redis.exceptions.ConnectionErrorbubble up as HTTP500turns a cache outage into total downtime. Wrap non-lock Redis lookups with short timeouts and fall back cleanly (with rate protection) when Redis is temporarily degraded.
Decision scenario
Your AI workspace dashboard loads expensive multi-table permission + usage aggregates (~180 ms in PostgreSQL) for 3,000 req/s while user roles update infrequently via admin settings. Implement Redis Cache-Aside with 300 s + random(0..45 s) jittered TTLs, guard cold-cache bursts with an atomic SET lock:{key} {uuid} NX EX 5 singleflight lock unlocked exclusively via Lua GET/DEL, negatively cache missing entity IDs (__NULL__, 30 s), invalidate keys strictly after admin database transactions commit, and wrap Redis calls in a 250 ms socket timeout + circuit breaker so Redis hiccups never crash endpoints.
Learning outcomes
- Trace standard Cache-Aside read/write flows and explain why
DELbeatsSETon database mutations. - Defend PostgreSQL against Thundering Herd stampedes using singleflight
SET NX EXlocks, TTL jitter, and Stale-While-Revalidate. - Eliminate unsafe lock releases using atomic Lua compare-and-delete ownership tokens.
- Mitigate cache penetration on invalid IDs via bounded negative caching and graceful Redis degradation.
Trade-offs
Redis Cache-Aside drops database read pressure by 80%–99% and shields downstream queries during traffic spikes, yet introduces eventual-consistency invalidation windows, serialization overhead, and extra distributed infrastructure to monitor (evicted_keys, hit ratio, lock contention).