Caching patterns
Cache-aside vs write-through, TTLs, invalidation, stampede protection (locks, jittered expiry, single-flight). "How do you invalidate?" follows every cache answer.
The mental model
A cache is a notepad on your desk. The real record lives in a filing cabinet across the room (the database), but you scribble the things you look up constantly onto a pad within arm's reach. Reaching for the pad is a thousand times faster than walking to the cabinet — as long as what you wrote down is still correct. The entire discipline of caching is that last clause: keeping the notepad true enough, and knowing what to do when the cabinet changes and your pad does not.
Two questions define every caching decision, and famously the second is the hard one. What do you put in the cache (and how do you handle a miss)? And how do you keep it from lying — invalidation. Phil Karlton's line that "there are only two hard things in computer science: cache invalidation and naming things" is a joke because it is true: putting data in a cache is trivial, and every cache bug is a variant of the cache disagreeing with the source of truth.
Why this exists — what breaks without it. Every read hitting the database means the database is your throughput ceiling and your latency floor. A product page that runs six queries at 15 ms each is 90 ms before rendering; at 10,000 requests a second those queries alone would flatten a single primary. A cache turns the repeated reads into a memory lookup — 0.5 ms, and load the database never sees. But a cache done carelessly is worse than no cache: it serves one user another user's data, shows a price that changed an hour ago, or — the failure that takes systems down — lets a thousand requests all miss at the same instant and stampede the database that the cache existed to protect. "How do you invalidate?" follows every cache answer in an interview, and the honest answer involves TTLs, write-path invalidation, and stampede protection, not "we just cache it".
- 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