Caching strategies

CDN/HTTP caching, Redis for hot reads, Next.js data cache, and the invalidation bugs each one buys you. Name the staleness you accept.

About 28 min read3-question knowledge check

The mental model

Caching is the highest-leverage performance tool in web engineering and the most dangerous, for the same reason: a cache is a second copy of the truth, and two copies of anything eventually disagree. Every cache trades freshness for speed. So the real skill is not "add a cache" — it is naming exactly which staleness you are willing to accept, and where. An engineer who says "I'll cache it" without answering "for how long, and what happens when the underlying data changes?" is signing up for the second-hardest problem in computer science.

The mental model that organizes the whole topic: a cache is a layer that answers a request without doing the expensive work, and every layer forces two decisions — when does it expire (staleness) and how do you kill a stale entry early (invalidation). That is it. CDN, Redis, the browser cache, the Next.js data cache — they differ in where they sit and who they serve, but every one of them is the same two questions. The famous quip — "there are only two hard things in computer science: cache invalidation and naming things" — is a warning that the invalidation half is where the bugs live. A cache with a clean expiry story and no invalidation need (a build-time asset with a content hash) is easy. A cache of data that changes, with consumers who must see the change quickly, is where you lose a weekend.

The analogy: a cache is a whiteboard summary of a document that lives in a filing cabinet. Reading the whiteboard is instant; opening the cabinet is slow. The whiteboard is great — until someone edits the document and forgets to wipe the board, and now everyone reads the wrong number and acts on it. The discipline is deciding how long the board is allowed to be out of date (a stale-time), and building a reliable habit of wiping it the moment the document changes (invalidation). Most caching incidents are a whiteboard nobody wiped.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision