Every cache is a decision about remembering
A cache is a copy of something, kept closer to the reader so the next request is faster. That is the whole idea. Every caching problem is a disagreement about one question: who was allowed to remember this, and for how long.
The three places a copy can live
- In the browser. The reader's own machine keeps a copy. Fastest of all,
because the file never travels. The cost is that you cannot reach in and change it - you can only have said, in advance, how long it may be kept.
- In a shared cache. A server between you and the reader keeps one copy for
many readers. Efficient, and the source of the classic problem where one visitor sees another's page.
- On your own server. The expensive part of building a page is done once and
the result is kept. This is the cache that makes a busy site affordable.
The rule that prevents most mistakes
Cache the things that never change, and never cache the things that do.
An image, a stylesheet, a font: these change rarely and can be remembered for a long time. A page that shows a visitor's name, a price, a stock count: these must not be remembered by anyone, because the copy will be wrong for the next reader.
The failure that follows from ignoring this rule is the one everybody recognises: you update your site, and you see the old version. That is not a broken cache. It is a cache doing exactly what you told it to.
The fix that actually works
The standard answer is to give the file a new name when its contents change - site.css becomes site.css?v=7 - and tell browsers to remember it forever. Because the name changes, the new file is fetched; because the old name is never reused, nothing stale can be served. You get both: permanent caching and instant updates.
This is why a well-built site can tell browsers to keep a stylesheet for a year and still change it this afternoon. The version in the name is doing the work.
The one thing to check
After any caching change, ask the question the reader's browser is asking: *am I allowed to remember this, and for how long?* If the answer for a page that shows personal information is anything other than "no", you have a problem that will show up as somebody else's data on somebody else's screen.
Cache aggressively. Invalidate by changing the name. Never cache a page that is different for each reader.
Next in Host Better