The Caching Architect designs caching strategies that reduce database load and improve response times. Caching is not a performance optimisation to add later - it is an architectural decision that affects data consistency, invalidation complexity, and failure modes. The hardest part is not the caching; it is invalidation.
Cache Strategy Selection
| Pattern | When to use | Consistency | Complexity |
|---|---|---|---|
| Cache-aside (lazy) | Read-heavy, cache misses acceptable | Eventual (TTL-based) | Low |
| Write-through | Write-heavy, always-fresh reads required | Strong | Medium |
| Write-behind | High write throughput, DB durability can lag | Eventual | High |
| Read-through | Managed cache service handles misses automatically | Eventual | Low |
Redis Patterns
import { createClient } from 'redis';
const redis = createClient({ url: process.env.REDIS_URL });
await redis.connect();
// Cache-aside pattern
async function getUser(userId: string): Promise<User> {
const key = `user:${userId}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
const user = await db.users.findById(userId);
if (!user) throw new Error('User not found');
await redis.setEx(key, 300, JSON.stringify(user)); // TTL: 5 minutes
return user;
}
// Invalidate on update
async function updateUser(userId: string, data: Partial<User>) {
const user = await db.users.update(userId, data);
await redis.del(`user:${userId}`); // Invalidate immediately
return user;
}
// Hash for structured data - more memory-efficient than JSON strings
await redis.hSet(`product:${id}`, {
name: product.name,
price: String(product.priceCents),
stock: String(product.stockCount),
});
await redis.expire(`product:${id}`, 600);
Cache Stampede Prevention
// Problem: cache expires → many requests hit DB simultaneously
// Solution: probabilistic early expiry + mutex lock
async function getCachedWithLock<T>(key: string, fetchFn: () => Promise<T>, ttl = 300): Promise<T> {
const cached = await redis.get(key);
if (cached) return JSON.parse(cached);
// Distributed lock - only one process rebuilds the cache
const lockKey = `lock:${key}`;
const acquired = await redis.set(lockKey, '1', { NX: true, EX: 10 }); // 10s lock
if (!acquired) {
// Another process is rebuilding - wait and retry
await new Promise(r => setTimeout(r, 100));
return getCachedWithLock(key, fetchFn, ttl);
}
try {
const data = await fetchFn();
await redis.setEx(key, ttl, JSON.stringify(data));
return data;
} finally {
await redis.del(lockKey);
}
}