Caching

Lesson 3 of 14 · 28 min

x
21%

Caching Strategies: Five Core Patterns

How your application reads and writes through the cache defines its behavior. There are five fundamental patterns, each with different trade-offs between consistency, complexity, and write performance. Cache-aside (lazy loading) is the most common. The application checks the cache first; on a miss, it loads from the database and populates the cache. The app owns the logic. Read-through pushes that responsibility to the cache layer — on a miss, the cache itself fetches from the database. Write-through writes to both cache and database synchronously, keeping them consistent but slowing every write. Write-behind (write-back) writes to the cache immediately and flushes to the database asynchronously — fast writes, but you risk data loss if the cache crashes before flushing. Write-around skips the cache on writes entirely, writing only to the database; the cache is populated on the next read.

Before
Cache-aside — app manages the flow
async function getUser(id) {
  let user = await redis.get(`user:${id}`);
  if (user) return JSON.parse(user);       // hit

  user = await db.users.findById(id);      // miss
  await redis.setex(`user:${id}`, 300, JSON.stringify(user));
  return user;
}

async function updateUser(id, data) {
  await db.users.update(id, data);
  await redis.del(`user:${id}`);          // invalidate
}
After
Write-through — cache and DB updated together
async function updateUser(id, data) {
  const user = await db.users.update(id, data);
  await redis.setex(`user:${id}`, 300, JSON.stringify(user));
  return user;
  // Cache always consistent with DB after write
  // But every write pays the cache cost
}

Key Takeaway

Cache-aside for most apps; write-through when consistency matters more than write speed; write-behind only when you can tolerate async persistence risk.

PreviousNext Lesson