Skip to Content
Mengty Learns
Architecture

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.

explanationintermediateTested with redis 8.12.0 (docs)Updated Nov 26, 2026

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

TL;DR

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

PatternRead pathWrite pathTrade-off
Cache-aside (lazy)App checks cache → miss → reads DB → fills cacheApp writes DB, then deletes/updates cache keySimple and resilient; first read after expiry is a miss
Write-throughApp reads cacheApp writes cache + DB synchronouslyCache stays warm and consistent, but every write pays double latency
Write-behind (write-back)App reads cacheApp writes cache, flushes to DB asynchronouslyFastest 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 configure maxmemory-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

Overview of Cache-Aside Lifecycle: Miss → DB → Fill → Hit. 6 steps.
Overview6 steps in this flow

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 ms at 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

When to use
  • 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.
When to avoid
  • 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

Pros
  • Sub-millisecond read latency and huge reduction in primary DB CPU/connection load.
  • Cache-aside naturally tolerates cold starts and Redis restarts.
Cons
  • 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