Skip to main content
← CONCEPTS / DATABASES & STORAGE
An end-to-end domain learning journey

Distributed &
Application Caching.

Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Start the journey7 sections· Last modified Nov 29, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

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.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Rate Limiting Algorithms, Token Buckets & Redis Lua
Rate limiting enforces caps on request or resource consumption per caller, tenant, or endpoint over time to protect downstream capacity, ensure fair multi-tenant sharing, and blunt abuse.
Distributed Locking & Redlock Algorithm
Distributed locking coordinates mutually exclusive access to a shared resource across independent processes that share no memory, using a network-accessible lease store such as Redis, etcd, or ZooKeeper.
Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

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

Cache-Aside Read/Write Path

App -> L1/Redis Cache -> Singleflight Guard -> PostgreSQL

API ServiceChecks L1 -> RedisRedis (L2)TTL + random jitterSingleflightCoalesces hot missesPostgreSQLAuthoritative truthChecks L1 -> RedisTTL + random jitterCoalesces hot misses

Keeping PostgreSQL as the clear source of truth with TTL jitter and singleflight prevents both staleness and meltdowns.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

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:

  1. 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).
  2. 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.
  3. Cache Penetration: Attackers query nonexistent IDs (product:-999), bypassing the cache every time. Fix: Bloom filters or short-TTL negative caching (NULL sentinel).
Invalidation & Stampede

Cache-Aside Miss Coalescing & Post-Commit Invalidation

Reader 1..NSingleflightRedisPostgres1. GET product:42 -> MISS2. Coalesce 5,000 misses to 13. 1x SELECT * WHERE id=424. SETEX product:42 (300s+jitter)5. Fan out result to all 5,000

Singleflight collapses thousands of concurrent misses for the same expired hot key into a single database query.

Engineering Decision Framework
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.
Decision Exercise · Make the Call

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.

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

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.

ChoiceWhat it buysWhat 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-ThroughCache 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.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

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.

Lifecycle & Failure Recovery

How TTL Jitter, Singleflight, and Eviction are managed

admitsucceedbudget exceededInitializedProcessingInvariant MetDegraded Fallback
# 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
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

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.

Design Trade-Off

Alternatives: In-Process L1 vs. Distributed Redis vs. CDN Edge

Before · Unbounded Coupling
  • No backpressure on spikes
  • Implicit shared state
  • Cascading tail latency
After · Bounded & Observable
  • Explicit capacity budgets
  • Isolated failure domains
  • Predictable p99 latency
ChoiceWhat it buysWhat 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 Cache5-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.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

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.

CDC-Driven Freshness

Postgres Commit -> Debezium CDC -> Redis DEL + L1 Pub/Sub Purge

Postgres CommitAuthoritative pg_walDebezium RelayReads committed LSNRedis L2 DELInvalidates stale keyL1 Pub/Sub PurgeEvicts pod-local RAM

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.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

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.

Component Topology

Problems solved by Caching & System Design Deep Dives

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 4
Score: 0/4

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?

Recommended Learning Flow