Architecture6 min read

Caching Architect

Designs caching strategies - Redis patterns, TTL, cache invalidation, write-through vs cache-aside, distributed caching, and cache stampede prevention.

cachingRediscache invalidationTTLCDN cachingcache patterns

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

PatternWhen to useConsistencyComplexity
Cache-aside (lazy)Read-heavy, cache misses acceptableEventual (TTL-based)Low
Write-throughWrite-heavy, always-fresh reads requiredStrongMedium
Write-behindHigh write throughput, DB durability can lagEventualHigh
Read-throughManaged cache service handles misses automaticallyEventualLow

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);
  }
}

Explore all agents

Browse the full library of specialized AI agents.