System DesignIntermediate15 min

Caching: where, what and when to invalidate

Cut latency and load by keeping hot data close, and understand the invalidation bill you accepted.

See it on the map

A cache is a bet that the same data will be asked for again before it changes. Layers stack: browser, CDN, application memory, a shared cache such as Redis, then the database's own buffer pool. Put the cache as close to the user as the data's freshness rules allow.

Cache-aside is the common pattern: read the cache, on a miss load from the source and store it. Write-through updates both on write. Write-back buffers writes and is fastest and riskiest. Pick by how much staleness and loss you can tolerate.

Invalidation is the hard part. Time-to-live is simple and bounded. Explicit invalidation on write is fresher but easy to get wrong. Watch for a stampede, where a popular key expires and thousands of requests hit the database at once. Request coalescing and jittered expiry both help.

Key points

  • Measure hit rate. A cache with a low hit rate is only extra latency.
  • Always set a TTL, even when you also invalidate explicitly.
  • Guard against stampedes with coalescing or early, jittered refresh.
  • Never cache per-user data under a shared key.

Trade-offs

ChoiceYou gainYou pay
Cache-asideSimple, app controls what is cachedFirst request is slow, stale reads possible
Write-throughCache stays freshSlower writes, caches data that may never be read
Write-backVery fast writesData loss if the cache node dies before flush

Answer these out loud

  1. 1A product page is read 10,000 times per second and its price changes twice a day. Design the caching layers and the invalidation.
  2. 2What goes wrong if two services cache the same entity with different TTLs?

Build it

Wrap a slow function in a cache-aside helper with TTL and request coalescing, then load-test the stampede with and without coalescing.

Use this from an agent

Any MCP client, including Grok, can read this lesson. See how to connect.

REST
curl https://engineeros-delta.vercel.app/api/v1/topics/caching

This unlocks