Skip to main content
11

Caching strategies and invalidation

MediumCachingRedisPerformance

What caching strategies do you know, and how do you handle cache invalidation?

TL;DR

The most common pattern is cache-aside: the app reads from the cache, and on a miss it reads the database and stores the result with a TTL. Writes go to the database, then delete (not update) the cache key. Alternatives: write-through (write to cache and database together, so the cache is always fresh), write-behind (write to cache, flush to the database later; fast but risky), and read-through (the cache itself loads from the database). Invalidation is the hard part: combine TTLs as a safety net with explicit deletes or events on writes, and decide how much staleness each piece of data can tolerate.

Key points

  • Cache layers: browser and CDN (HTTP headers), application memory, a distributed cache (Redis), and database buffers.
  • Delete on write rather than set, to avoid races where an older value overwrites a newer one.
  • Cache stampede: a hot key expires and thousands of requests hit the database at once. Fix with a lock or single-flight on rebuild, TTL jitter, or refreshing early in the background.
  • Cache penetration: repeated lookups for keys that don't exist. Cache the "not found" briefly.
  • Eviction: LRU is the usual default; set a memory limit.
  • Measure the hit rate. A cache with a low hit rate adds latency and complexity for nothing.

Example

ts
async function getUser(id: string) {
  const cached = await redis.get(`user:${id}`)
  if (cached) return JSON.parse(cached)

  const user = await db.user.findUnique({ where: { id } })
  await redis.set(`user:${id}`, JSON.stringify(user), 'EX', 300 + Math.floor(Math.random() * 60))
  return user
}

async function updateUser(id: string, data: UserUpdate) {
  await db.user.update({ where: { id }, data })
  await redis.del(`user:${id}`)
}

Common follow-ups

  • What shouldn't you cache? Highly personalized data with low reuse, or data that must be strongly consistent (balances) unless you have a solid invalidation path.
  • Local vs distributed cache? In-process memory is fastest but each instance has its own copy; Redis is shared across instances.

What interviewers look for

Tip

Name cache-aside with TTL and delete-on-write, then show you know the failure modes: stampede, staleness and hit rate.

  • Red flag: caching everything forever with no invalidation plan.

Was this helpful?

Related questions