If disk I/O or compaction stalls threaten tail latency, keep a clear source of truth. Decide how stale a cached value may be, how to refresh it, and what happens when the cache is empty or unavailable.
TL;DR30-second simplified summary▾
Core Mechanics: Caching stores the result of an expensive database query, computation, or RPC in fast memory (in-process L1 or distributed Redis/Memcached) so subsequent reads reuse it in sub-millisecond time.
Visual & Structural Flow: Depicts App -> L1/Redis Cache -> Singleflight Guard -> PostgreSQL (API Service -> Redis (L2) -> Singleflight -> PostgreSQL); Cache-Aside Miss Coalescing & Post-Commit Invalidation (Reader 1..N -> Singleflight -> Redis -> Postgres); Postgres Commit -> Debezium CDC -> Redis DEL + L1 Pub/Sub Purge (Postgres Commit -> Debezium Relay -> Redis L2 DEL -> L1 Pub/Sub Purge).
Trade-Offs & Production: Compare latency, consistency, and operational overhead across cache tiers. High-QPS read platforms pair a tiny L1 in-process cache (10–30s TTL) for ultra-hot keys with Redis Cluster (L2) and CDC/Debezium invalidation—so DB commits.
Failure Modes & Application: Explore cache avalanche, penetration, stampedes, L1/L2 sync, and dual-write invalidation races.
What is Caching.
Why this matters: The mechanism: understand how Caching works from first principles.
Caching stores the result of an expensive database query, computation, or RPC in fast memory (in-process L1 or distributed Redis/Memcached) so subsequent reads reuse it in sub-millisecond time.
Every cache design revolves around five core primitives: Cache Hit (served from cache), Cache Miss (computed/fetched from source of truth), TTL (expiry window bounding staleness), Invalidation (deleting/updating on write), and Eviction (LRU/LFU removal when RAM is full).
App -> L1/Redis Cache -> Singleflight Guard -> PostgreSQL
Keeping PostgreSQL as the clear source of truth with TTL jitter and singleflight prevents both staleness and meltdowns.
Why we need Stampede, Avalanche & Penetration Defenses.
Why this matters: The problem: see what breaks without Stampede, Avalanche & Penetration Defenses under real concurrency or scale.
A naive cache works fine in calm traffic and collapses on bad days due to three failure modes:
- Cache Avalanche: Thousands of keys loaded at deploy time share the exact same TTL (
300s) and expire simultaneously, sending a flood of misses to PostgreSQL. Fix: Add random TTL jitter (300s +/- 30s). - Hot-Key Stampede (Breakdown): One viral key (
product:42) expires while 5,000 RPS hit it—all 5,000 threads miss and hammer the DB at once. Fix: Request coalescing (singleflight) or probabilistic early refresh. - Cache Penetration: Attackers query nonexistent IDs (
product:-999), bypassing the cache every time. Fix: Bloom filters or short-TTL negative caching (NULLsentinel).
Cache-Aside Miss Coalescing & Post-Commit Invalidation
Singleflight collapses thousands of concurrent misses for the same expired hot key into a single database query.
- Problem
- How to implement Distributed & Application Caching without hitting unbounded tail latency, state divergence, or operational fragility.
- Naive Solution
- Use a single unpartitioned path with unbounded retries and synchronous global coordination.
- Why It Fails
- Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
- Alternatives
- Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
- Engineering Decision
- If disk I/O or compaction stalls threaten tail latency, keep a clear source of truth. Decide how stale a cached value may be, how to refresh it, and what happens when the cache is empty or unavailable.
- Trade-Offs
- Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
When Distributed & Application Caching experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?
Invalidate, Don't Blindly Overwrite
Updating DB + deleting cache is safer than dual-writing DB + cache, though a concurrent reader can still race unless versioned.
Bound Fallback Concurrency
Even with caching, put a semaphore/bulkhead in front of the DB fallback so a cold Redis restart cannot take down Postgres.
Where Caching Patterns fit.
Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Think of Where Caching Patterns fit as the intuition layer for Distributed & Application Caching: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.
Start with one shared Redis layer; add in-process L1 (Caffeine/Ristretto) or CDN layers only when latency or cost justifies extra invalidation complexity.
| Choice | What it buys | What it costs |
|---|---|---|
| Cache-Aside (Lazy Loading) | Only caches actually requested keys; resilient if Redis is flushed or restarts. | First read is slow (miss penalty); invalidation and refill can race under concurrent writes. |
| Write-Through | Cache stays warm on writes; consistent read-after-write through the cache tier. | Adds write latency and caches cold data that may never be read. |
| Write-Behind (Write-Back) | Absorbs extreme write spikes by batching dirty cache writes asynchronously to DB. | Data loss risk if cache node crashes before async flush; complex recovery. |
How TTL Jitter, Singleflight, and Eviction are managed.
Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.
Think of How TTL Jitter, Singleflight, and Eviction are managed as the intuition layer for Distributed & Application Caching: Operational control: configure bounds, failure handling, and safe production defaults.
Measure hit rate, eviction rate, p99 latency, cache error rate, and DB fallback QPS together—a 99% hit rate still crashes your DB if the remaining 1% is unthrottled during a hot-key stampede.
How TTL Jitter, Singleflight, and Eviction are managed
# Cache-aside with random TTL jitter, negative caching, and per-key coalescing (Python)
import random, threading
_inflight_locks: dict[str, threading.Lock] = {}
_registry_lock = threading.Lock()
def get_product_cached(redis, db, product_id: int, base_ttl: int = 300):
key = f"product:{product_id}"
cached = redis.get(key)
if cached is not None:
return None if cached == b"__NULL__" else cached
with _registry_lock:
key_lock = _inflight_locks.setdefault(key, threading.Lock())
with key_lock: # single-process stampede guard
cached = redis.get(key)
if cached is not None:
return None if cached == b"__NULL__" else cached
row = db.fetch_product(product_id)
jittered_ttl = base_ttl + random.randint(-30, 30) # avalanche guard
if row is None:
redis.setex(key, 60, b"__NULL__") # negative cache stops penetration
return None
redis.setex(key, jittered_ttl, row)
return row
Alternatives: In-Process L1 vs. Distributed Redis vs. CDN Edge.
Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Think of Alternatives: In-Process L1 vs. Distributed Redis vs. CDN Edge as the intuition layer for Distributed & Application Caching: The trade-off: compare competing approaches across latency, consistency, and operational cost.
Compare latency, consistency, and operational overhead across cache tiers.
Alternatives: In-Process L1 vs. Distributed Redis vs. CDN Edge
- No backpressure on spikes
- Implicit shared state
- Cascading tail latency
- Explicit capacity budgets
- Isolated failure domains
- Predictable p99 latency
| Choice | What it buys | What it costs |
|---|---|---|
| In-Process L1 (Caffeine / Guava) | Sub-microsecond RAM reads; zero network serialization; immune to Redis outages. | Per-pod memory limit; pods can drift out of sync until L1 TTL expires or pub/sub invalidates. |
| Distributed L2 (Redis / Memcached) | Shared view across all pods; large RAM capacity; atomic Lua/TTL primitives. | 0.5-2 ms network RTT; requires singleflight and big-key protection. |
| CDN Edge Cache | 5-20 ms global RTT; shields origin from 90%+ of public read traffic. | Only for public or surrogate-keyed HTTP responses; requires careful Vary/Cookie rules. |
Production example: Two-Tier L1+L2 Cache with CDC Invalidation.
Why this matters: Production architecture: see how the components compose end to end under real load.
Think of Production example: Two-Tier L1+L2 Cache with CDC Invalidation as the intuition layer for Distributed & Application Caching: Production architecture: see how the components compose end to end under real load.
High-QPS read platforms pair a tiny L1 in-process cache (10–30s TTL) for ultra-hot keys with Redis Cluster (L2) and CDC/Debezium invalidation—so DB commits asynchronously purge stale Redis keys and broadcast L1 evictions via Redis Pub/Sub.
Postgres Commit -> Debezium CDC -> Redis DEL + L1 Pub/Sub Purge
1.No App Dual-Write: Application code only writes to Postgres; CDC handles cache invalidation reliably.
2.Versioned Refill: Attach monotonic DB version/xmin so stale async refills never overwrite newer data.
3.Graceful Cold Start: Singleflight + DB concurrency bulkhead keep Postgres safe if L2 is empty.
CDC-driven invalidation eliminates dual-write races between the database and multi-tier caches.
Problems solved by Caching & System Design Deep Dives.
Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.
Think of Problems solved by Caching & System Design Deep Dives as the intuition layer for Distributed & Application Caching: Applied problems: connect these internals to concrete system design and debugging scenarios.
Explore cache avalanche, penetration, stampedes, L1/L2 sync, and dual-write invalidation races.
Problems solved by Caching & System Design Deep Dives
Practice: Make the trade-off yourself.
Every night at 00:00 UTC, 50,000 cached product keys expire at the exact same second and PostgreSQL CPU spikes to 100%. What is this failure mode and its fix?