In high-throughput distributed applications, memory caching (Redis / Memcached) is the primary defense mechanism protecting relational databases from workload saturation. However, improper caching patterns introduce stale data reads, cache pollution, and race conditions during database updates.
Choosing the correct caching pattern depends on your workload’s read/write ratio and data consistency tolerance.
1. Comparative Breakdown of Primary Caching Patterns
PATTERN 1: CACHE-ASIDE (LAZY LOADING)
[App] ──1. Read Cache──► [Redis] (Miss)
│
└──2. Read DB ───────► [PostgreSQL]
│
└──3. Populate Cache ─► [Redis]
PATTERN 2: WRITE-THROUGH
[App] ──1. Write ──────► [Cache Layer] ──2. Sync Write ──► [PostgreSQL]
PATTERN 3: WRITE-BEHIND (WRITE-BACK)
[App] ──1. Fast Write ──► [Cache Layer] ──2. Async Queue ──► [PostgreSQL]
2. Deep Dive: Architectural Trade-Offs
| Metric | Cache-Aside (Lazy Loading) | Write-Through | Write-Behind (Write-Back) |
| Read Latency | Sub-ms on Hit; High on Miss | Always Sub-millisecond | Always Sub-millisecond |
| Write Latency | Standard DB write latency | Higher (Slower synchronous write to both) | Extremely Low (Instant cache response) |
| Data Consistency | Eventual (Requires key invalidation) | Strong / Near-Immediate | Risk of data loss if Redis crashes before flush |
| Best Used For | Read-heavy web applications, user profiles | Financial ledgers, critical user settings | High-throughput logging, live view counters |
3. Production Code: Cache-Aside with Safe Cache Invalidation
When updating data in a Cache-Aside strategy, always delete (invalidate) the cache key instead of updating it in place. Updating a cache key directly introduces race conditions when two concurrent writes finish in a different order than they started.
TypeScript
import Redis from "ioredis";
import { db } from "./db";
const redis = new Redis(process.env.REDIS_URL!);
export class UserProfileService {
private static getCacheKey(userId: string): string {
return `user:profile:v1:${userId}`;
}
/**
* Cache-Aside Read Flow
*/
static async getUserProfile(userId: string) {
const key = this.getCacheKey(userId);
// 1. Attempt Cache Fetch
const cachedData = await redis.get(key);
if (cachedData) {
return JSON.parse(cachedData);
}
// 2. Database Fallback on Cache Miss
const query = "SELECT id, email, full_name, bio FROM users WHERE id = $1";
const { rows } = await db.query(query, [userId]);
const user = rows[0];
if (!user) return null;
// 3. Populate Cache with a Jittered TTL (Prevents Cache Stampede)
const baseTTL = 3600; // 1 hour
const jitter = Math.floor(Math.random() * 300); // 0-300s variance
await redis.set(key, JSON.stringify(user), "EX", baseTTL + jitter);
return user;
}
/**
* Safe Write Invalidation Flow
*/
static async updateUserBio(userId: string, newBio: string) {
const key = this.getCacheKey(userId);
// 1. Update Core Database First
await db.query("UPDATE users SET bio = $1, updated_at = NOW() WHERE id = $2", [newBio, userId]);
// 2. INVALIDATE (DELETE) Cache Key
// Do NOT call redis.set() here to avoid write race conditions
await redis.del(key);
}
}


