Caching Strategies

Difficulty: Intermediate

Question

Explain Cache-Aside vs. Write-Through caching. When would you choose each, and where do Read-Through and Write-Behind fit?

Answer

In cache-aside (lazy loading) the application reads from the cache first, and on a miss it reads the database, then writes the result into the cache with a TTL. In write-through, every write goes to the cache and the database as part of the same operation, so the cache is always populated and fresh for keys that were written. Cache-aside is the most common pattern with Redis because it is simple and the app keeps working if Redis goes down; write-through trades slower writes for fewer stale reads.

How cache-aside works step by step

  1. App calls GET product:101.
  2. Hit: return the cached value.
  3. Miss: query the database, then SET product:101 <json> EX 300, then return.
  4. On update: write the database, then delete the cache key (DEL product:101) so the next read reloads it.

Deleting on write is preferred over updating the cache, because two concurrent writers updating the cache in different orders can leave it permanently stale. Only data that is actually read ends up in cache, which keeps memory usage proportional to the hot set.

How write-through and write-behind work

  • Write-through: the write path updates the database and the cache together (often via a caching layer or library that owns both). Reads after writes are always hits, but every write pays two latencies and you cache data that may never be read.
  • Write-behind (write-back): the app writes only to the cache, and changes are flushed to the database asynchronously in batches. Writes are very fast and the database sees less load, but if the cache node dies before flushing, data is lost. Use it for things like view counters, not for payments.
  • Read-through: like cache-aside, but the cache layer itself loads from the database on a miss. Redis does not do this natively; a library, a proxy, or a client-side abstraction provides it.

Comparing the patterns

PatternWrite latencyStale read riskSurvives cache outageGood for
Cache-asideLow (DB only)Short window after writeYes, falls back to DBMost read-heavy APIs
Write-throughHigher (DB + cache)Very lowDepends on implementationData read right after it is written
Write-behindLowest (cache only)LowNo, risk of data lossCounters, analytics, likes
Read-throughSame as cache-asideSame as cache-asideDepends on layerTeams that want caching hidden from business code

Gotchas interviewers probe

  • Race on cache-aside: reader A misses and reads old data from the DB, writer B updates the DB and deletes the key, then A writes the old value into the cache. Short TTLs bound the damage; some teams use a delayed second delete or version numbers.
  • Order of operations: update the DB first, then invalidate. Invalidating first lets a concurrent reader repopulate stale data before the DB write lands.
  • Thundering herd: a hot key expiring causes many simultaneous misses. Use a per-key lock or request coalescing.
  • Always set a TTL as a safety net, even with explicit invalidation.

In real systems

A product catalogue at Flipkart scale is a classic cache-aside case: reads massively outnumber writes and a few seconds of staleness is fine. Wallet balances or UPI transaction status should not be served from a write-behind cache; the database stays the source of truth and the cache, if any, is invalidated on every change. Change data capture (Debezium reading the DB log and deleting Redis keys) is a popular way to make invalidation reliable without touching every write path.

Cache-aside read on a miss. The application owns the logic: check Redis, fall back to the database, then populate the cache.
  1. App → Redis: GET product:101
  2. Redis → App: nil (cache miss)
  3. App → Database: SELECT product 101
  4. Database → App: Row data
  5. App → Redis: SET product:101 EX 300

Code examples

Cache-aside with invalidation in Node.js (node-redis v4+)

import { createClient } from 'redis';
const redis = await createClient().connect();

export async function getProduct(id) {
  const key = `product:${id}`;
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);          // hit

  const product = await db.products.findById(id); // miss: go to DB
  if (product) {
    // TTL is a safety net even though we invalidate on write
    await redis.set(key, JSON.stringify(product), { EX: 300 });
  }
  return product;
}

export async function updatePrice(id, pricePaise) {
  await db.products.update(id, { pricePaise }); // 1. source of truth first
  await redis.del(`product:${id}`);             // 2. then invalidate
}

Reads populate the cache lazily and writes delete the key instead of updating it, which avoids two writers leaving the cache in the wrong order.

Key points

  • Cache-aside: app reads cache, loads DB on miss, writes cache; most common with Redis.
  • Write-through: write DB and cache together; fresh reads, slower writes.
  • Write-behind: write cache only, flush later; fastest but can lose data.
  • On update, write the DB first and then delete the cache key rather than overwriting it.
  • Always set a TTL so any invalidation bug heals itself.

Common follow-up questions

  • What race condition can occur with cache-aside, and how would you mitigate it?
  • Why delete the cache key on update instead of setting the new value?
  • How would you handle a hot key expiring under heavy traffic?
  • Would you use write-behind for an order service? Why not?

Interview tips

  • Draw the read and write paths separately; most candidates only describe reads.
  • Mention the update-DB-then-invalidate ordering and the stale-write race; it shows real production experience.
  • Tie the choice to consistency needs: product pages tolerate staleness, balances do not.

Concepts covered

Cache-Aside, Write-Through, Write-Behind, Read-Through, Cache Invalidation

More Redis & Caching questions