Caching Strategies & Redis
Compare cache-aside, write-through, and write-behind caching, handle TTLs, stampedes, Redis RDB/AOF persistence, and degrade gracefully when the cache is down.
TL;DR
Cache-aside is the default pattern: read Redis first, fall back to the DB on a miss, and populate Redis with a TTL. Guard hot keys against stampedes, pick RDB/AOF only if your cached/session data needs durability, and always degrade instead of crashing if Redis is down.
Intent
Choose the right caching write/read strategy, prevent cache invalidation bugs and thundering herds, and understand Redis persistence and failure modes.
Problem
Every uncached API call that hits Postgres pays disk/network latency and connection-pool contention. Adding Redis blindly creates a second set of problems: stale data after updates, simultaneous DB spikes when a popular key expires (cache stampede), and total site outages if the app treats a Redis timeout as a fatal 500 error.
Solution
1. Three core caching patterns
| Pattern | Read path | Write path | Trade-off |
|---|---|---|---|
| Cache-aside (lazy) | App checks cache → miss → reads DB → fills cache | App writes DB, then deletes/updates cache key | Simple and resilient; first read after expiry is a miss |
| Write-through | App reads cache | App writes cache + DB synchronously | Cache stays warm and consistent, but every write pays double latency |
| Write-behind (write-back) | App reads cache | App writes cache, flushes to DB asynchronously | Fastest writes, but risk of data loss if cache crashes before flush |
2. TTLs, invalidation, and stampede protection
- Always set a TTL (
SET key val EX 60) and configuremaxmemory-policy(e.g.,allkeys-lru) so Redis never runs out of RAM. - Prefer deleting the cache key after a DB update rather than writing the new value from two concurrent requests (which can race and leave stale data).
- Prevent stampedes (dogpiles): Add random jitter to TTLs (
60s + rand(0..10s)), coalesce concurrent misses for the same key in-process (singleflight), or refresh hot keys asynchronously before expiry.
3. Redis persistence (RDB vs AOF) and failure handling
- Pure cache: You can disable disk persistence or use RDB snapshots—if Redis restarts empty, the DB repopulates it.
- Sessions / queues / rate limits: Enable AOF (
appendonly yes,appendfsync everysec) or RDB+AOF so restarts lose at most ~1 second of writes. - Degrade, don't fail: Wrap Redis calls in short timeouts (e.g., 50–100 ms) and circuit breakers. On error, fall back to the DB (with rate limiting if needed so the DB doesn't melt).
Real-world analogy
▶ Flow: watch it work
Cache-Aside Lifecycle: Miss → DB → Fill → Hit
Press Start or tap any step dot to trace the path.
▸All steps (6)
Code
Minimal cache-aside helper in TypeScript showing a short timeout, graceful degradation on Redis failure, and jittered TTL:
// Minimal cache-aside pattern with graceful degradation (not run)
interface CacheClient {
get(key: string): Promise<string | null>;
set(key: string, value: string, opts: { EX: number }): Promise<void>;
}
export async function getUserCached(
cache: CacheClient,
fetchFromDb: (id: string) => Promise<{ id: string; name: string } | null>,
id: string,
) {
const key = `user:${id}`;
try {
const hit = await cache.get(key);
if (hit) return JSON.parse(hit);
} catch {
// Cache down: degrade gracefully to the primary DB instead of throwing 500
}
const row = await fetchFromDb(id);
if (!row) return null;
const ttlSeconds = 60 + Math.floor(Math.random() * 10);
try {
await cache.set(key, JSON.stringify(row), { EX: ttlSeconds });
} catch {
// Best-effort cache fill; do not fail the user request
}
return row;
}When you DON'T need this
- Static sites or CDN-cacheable pages: This site pre-renders every page at build time and serves it from Cloudflare's edge cache—adding Redis would add cost and a failure mode for zero benefit.
- Fast enough primary DB: If your Postgres queries already take
< 10 msat your current traffic and you can scale with a read replica or better indexes, don't introduce cache invalidation complexity early. - Cost / complexity trade-off: Redis adds another stateful service to monitor, patch, and size in memory (RAM is much pricier per GB than disk). In return, you cut p99 read latency from milliseconds of DB work to sub-millisecond in-memory lookups.
When to use / when to avoid
- Repeated, expensive read queries or aggregations that tolerate seconds of staleness.
- Shared rate-limiting counters, distributed locks, or ephemeral session state across multiple app instances.
- Financial balances or inventory counts where stale reads cause double-spending.
- Caching an entire database in RAM before you have added basic SQL indexes.
How to implement
Start with cache-aside and a short TTL
Read Redis first, fall back to the DB on miss, and write back with EX plus small random jitter.
Set maxmemory and an eviction policy
Configure maxmemory-policy allkeys-lru (or volatile-ttl) so Redis evicts old keys instead of failing writes with OOM.
Test Redis failure in staging
Kill or block Redis and verify your app degrades cleanly (slower responses, zero 500 errors).
Pros / Cons
- Sub-millisecond read latency and huge reduction in primary DB CPU/connection load.
- Cache-aside naturally tolerates cold starts and Redis restarts.
- Cache invalidation bugs (stale reads) and stampedes on hot-key expiry.
- RAM-bound cost and another operational dependency to monitor.
Relations
Check yourself
Check Yourself
1. A popular homepage key expires at 12:00:00 and 500 concurrent requests immediately query Postgres at once. What is this failure mode called?
2. In a cache-aside architecture, what should happen if Redis times out during a GET?
Sources
Related Notes
Event Sourcing: Overview, Projections, and Traps
Store every state change as an append-only sequence of events, rebuild state with projections and snapshots, and recognize when Event Sourcing is a trap.
Queues & Asynchronous Work
Decouple slow work from HTTP requests with queues vs pub/sub, at-least-once delivery, idempotency keys, exponential backoff retries, and dead-letter queues.