Skip to content
Caching

Lesson 3 of 14 · 28 min

x
3/14

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

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
1async function getUser(id) {2  let user = await redis.get(`user:${id}`);3  if (user) return JSON.parse(user);       // hit4 5  user = await db.users.findById(id);      // miss6  await redis.setex(`user:${id}`, 300, JSON.stringify(user));7  return user;8}9 10async function updateUser(id, data) {11  await db.users.update(id, data);12  await redis.del(`user:${id}`);          // invalidate13}
After
Write-through — cache and DB updated together
1async function updateUser(id, data) {2  const user = await db.users.update(id, data);3  await redis.setex(`user:${id}`, 300, JSON.stringify(user));4  return user;5  // Cache always consistent with DB after write6  // But every write pays the cache cost7}

Check your understanding

  • Cache-aside vs write-through?Show answer

    Answer

    Cache-aside: app loads DB on miss. Write-through: writes update cache and DB together for fresher reads at write cost.
  • What is the risk of write-behind?Show answer

    Answer

    Fast writes to cache with async DB flush — data loss if the cache dies before flush.
  • When is write-around sensible?Show answer

    Answer

    Write-heavy paths where caching the write is pointless and you prefer populate-on-read.
Previous

Progress is saved in this browser.

Next Lesson