Why you need it

A cached copy is a snapshot. When the real data changes, the copy keeps answering with the old value, confidently and quickly. A wrong price or an old profile photo can cost money and trust, so every cache needs a plan for when its copies stop being true.

Think of it like this

A printed price list taped to a shop window. When prices change, someone must take it down. Either it gets replaced every morning whether or not anything changed, or someone replaces it the moment a price changes.

Where you’ll find it

What to know first

Stale. A copy that no longer matches the real data.

TTL. Time to live: how long a copy may be used before it is thrown away.

Invalidate. Mark a copy as no longer good, usually by deleting it, so the next ask fetches fresh data.

How it works

  1. TTL: copies expire by themselves. Give every copy a timer, say 5 minutes. When it runs out, the copy is dropped and the next ask fetches fresh data. Simple and safe, but the copy can be wrong for up to 5 minutes.
  2. Invalidate on change. When the data changes, delete the copy right away. The next ask misses and fetches the new value. Fresh within milliseconds. Both ways are in the animation.
  3. Delete, do not update. Deleting the copy is safer than writing the new value into it, because two updates arriving in the wrong order can leave the older value in the cache.
  4. Use both. Invalidation is fast but can be missed: a bug, a crash, a change made straight in the database. A TTL as well puts a limit on how long any mistake can last.
  5. Pick the TTL by how much staleness hurts. A logo can be cached for a year. A news headline for a minute. A bank balance probably not at all.

An example

Shoes cost $50, cached with a 10-minute TTL. At 9:00 the price changes to $40.

With TTL only: shoppers see $50 until the copy expires, up to 9:10, then pay $40 at checkout. Confusing.

With invalidation: the price update also deletes the copy. The next visitor at 9:00:01 misses, reads $40 and caches it.

Keep the TTL anyway: if the delete ever fails, the wrong price lives at most 10 minutes.

Further reading

  • HTTP caching, MDN. How TTLs and freshness work across the whole web. Start with this one.
  • Cache made consistent, Facebook Engineering. Real-world ways a cache goes stale, and how Facebook catches them.
  • Two Hard Things, Martin Fowler. The famous joke about why this is hard. One minute to read.