FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Redis Cache-Aside & Thundering Herd Defense

Cache-Aside pattern, TTL eviction, Redis distributed locking, and thundering herd stampede protection.

Freshness: current•15 min read•Data Engineering and Databases

Key Learning Outcomes

  • ✓Implement Cache-Aside pattern with explicit TTL invalidation
  • ✓Protect database backends from thundering herd spikes
Full Technical Reference Document

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.

HTTP Request Route
Check Redis Cache Key
Cache HIT -> Return In-Memory Payload
Cache MISS -> Lock & Query PostgreSQL
Write Result to Redis with TTL
Conceptual teaching model synthesized from:redis-docs,postgresql-docs,sre-book

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.

HazardRoot CauseProduction Defense PatternTrade-Off / Caveat
Cache Stampede (Thundering Herd)Hot key TTL expires; N workers query DB concurrentlyDistributed Singleflight Lock (SET lock_key token NX EX 5) + jittered TTLFollowers poll briefly (25–50 ms) or read stale backup key
Stale Overwrite RaceSlow reader writes old DB snapshot over newer writer commitDelete 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 filterProtects PostgreSQL from repetitive index misses on 404 lookups
Synchronized Expiry WavesBatch job seeds 50k keys at identical EX=3600TTL 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.

python
import asyncio
import json
import random
import uuid
import redis.asyncio as aioredis
​
redis_client = aioredis.from_url("redis://redis-cluster:6379/0", decode_responses=True)
​
UNLOCK_LUA = """
if redis.call("GET", KEYS[1]) == ARGV[1] then
return redis.call("DEL", KEYS[1])
end
return 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 token
owner_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 PostgreSQL
await 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 IDs
await redis_client.set(cache_key, "__NULL__", ex=30)
return None
ttl_with_jitter = 300 + random.randint(0, 45)
await redis_client.set(cache_key, json.dumps(profile), ex=ttl_with_jitter)
return profile
finally:
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), atomic SET NX EX locks, 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

  1. Updating Cache Instead of Deleting on Write (UPDATE DB -> SET Cache): Concurrent updates arriving out-of-order (Write A hits DB first, Write B hits DB second, Write B writes Redis first, Write A overwrites Redis last) leave permanent stale data until TTL expiration. Always DEL cache keys after the database COMMIT, or key entries monotonically by monotonic version/timestamp.
  2. Unsafe Raw DEL lock_key Lock Release: If worker A stalls 6 seconds past a 5-second lock TTL, worker B legitimately acquires the lock—and then worker A wakes up and calls DEL lock_key, releasing B's live lock! Always validate ownership atomically via a Lua script (GET == ARGV[1] -> DEL).
  3. Un-Jittered Mass Cache Warmups / Synchronized Expirations: Seeding 100,000 product keys at midnight with exact EX=3600 triggers synchronized stampedes at 01:00 every hour. Add 10%–20% random jitter to every TTL.
  4. Hard-Failing Requests When Redis Unreachable: Letting uncaught redis.exceptions.ConnectionError bubble up as HTTP 500 turns 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.
Reflect before revealing the guide

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 DEL beats SET on database mutations.
  • Defend PostgreSQL against Thundering Herd stampedes using singleflight SET NX EX locks, 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).

Prerequisites & Related Concepts (2)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-201Production LLM Engineer

Design an observable full-stack LLM product from capability validation through interfaces retrieval evaluation security and operations.

37 concepts~35h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next