Caching in Plain English

Caching means remembering an answer so you do not have to compute or fetch it again. Done right, it is the cheapest speed-up that exists: the second request costs almost nothing. Done wrong, it shows one user another user’s data. This post is the plain-English version: where your app already caches, the one rule that keeps it safe, and when adding a cache actually pays.
The incident that explains the rule
On Christmas Day 2015, the Steam store was hit by a denial-of-service attack during its biggest sale of the year. To stay up, Valve’s caching partner deployed new caching rules. One configuration cached pages for logged-in users, and the store started serving people pages generated for other users. About 34,000 users saw a stranger’s account page: billing address, purchase history, parts of phone and card numbers. Valve shut the store down, purged every cache, and published exactly what happened (Valve’s statement, Dec 2015).
No one “hacked” Steam. A cache stored the wrong kind of page. The full incident postmortem has the whole story; this post stays on where your caches live and when to add one.
Your app already has four caches
You do not start from zero. Any app on a modern host already caches in several places:
- The browser keeps copies of pages, images and API responses, and reuses them when the rules allow.
- The CDN (Cloudflare, Vercel, Netlify, Fastly) keeps copies of your files on servers near your users.
- Your build tool fingerprints static assets. When Vite or Astro builds
app-a1b2c3.js, the hash in the name changes only when the content does, so the file can be cached for a year. (This site does exactly that for its own assets.) - Your database and framework remember prepared-statement plans and rendered fragments so repeated work costs less.
So the question is never “should I add caching”. It is “is the caching I already have correct”.
The one rule: never cache per-user data at a shared layer
Caches come in two kinds. A private cache belongs to one user (their browser). A shared cache sits between your server and everyone (the CDN). Public pages belong in both. Anything rendered for one specific user belongs in the private one only, and telling them apart is one HTTP header:
Cache-Control: public, max-age=3600 # safe to store anywhere, for an hourCache-Control: private, no-store # one user's data: never store it at allOne trap hides in the vocabulary: no-cache does not mean “store nothing”. It means the cache may store the response but must re-check with your server before every reuse. For per-user data you want no-store, which stores nothing anywhere.
That is the whole rule, and MDN’s Cache-Control reference covers every value. The Steam incident, in one sentence, was an account page served without this protection at a shared cache. AI tools get this wrong in a predictable way: they add caching to make an endpoint faster and do not ask whose data it returns. If a response contains a user’s name, email, orders or usage, it is private, no-store, no exceptions for speed.
When adding a cache pays
Add a cache for work that is expensive, repeated, and the same for many requests:
- Reads that vastly outnumber writes. Your pricing page or product catalog changes twice a month and is read ten thousand times a day. Cache it. Your landing page hero image is the same story, and it is the biggest lever on your Core Web Vitals.
- Expensive computations. A report that scans a million rows can be computed once and reused for an hour.
- AI API calls. If your app sends the same long system prompt or reference document with every request, prompt caching remembers the prefix on the provider’s side. Anthropic reports it makes calls over 2x faster and up to 90% cheaper for the cached part (Anthropic). Anthropic needs explicit cache breakpoints in the request; OpenAI caches matching prefixes automatically. For an AI feature with real users, that is the difference between a viable bill and a scary one.
One thing a cache cannot fix: work whose result differs per request, like an AI call on a user’s own data. Caching stores the wrong person’s answer there. That work should not wait in the request at all; it belongs in a background job.
When a cache is the wrong fix
A cache hides slow work; it does not remove it. If one database query takes eight seconds, caching its result means the first user still waits eight seconds, and everyone else gets an answer that may be hours old. Fix the query first: indexes, limits and joins come before caches. (Why your app gets slower with every new user walks through those fixes.)
Prove it with two runnable tests
Caching bugs live in headers nobody looks at, so pin them down. Save this as test_cache_headers.py in an empty folder and run python3 test_cache_headers.py. It starts a tiny version of your app (Python standard library only) and tests the two rules above:
import threadingimport unittestimport urllib.requestfrom http.server import BaseHTTPRequestHandler, HTTPServer
class App(BaseHTTPRequestHandler): def do_GET(self): if self.path == "/account": self.send_response(200) self.send_header("Content-Type", "application/json") # FIX 1 (after the first run): uncomment the next line # self.send_header("Cache-Control", "private, no-store") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) elif self.path == "/logo.png": body = b"fake-png-bytes" self.send_response(200) self.send_header("Content-Type", "image/png") # FIX 2 (after the first run): uncomment the next line # self.send_header("Cache-Control", "public, max-age=31536000, immutable") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
def log_message(self, *args): pass
def directives(cache_control): return {d.strip().lower() for d in cache_control.split(",")}
class CacheHeaderTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.server = HTTPServer(("127.0.0.1", 0), App) cls.port = cls.server.server_address[1] threading.Thread(target=cls.server.serve_forever, daemon=True).start()
@classmethod def tearDownClass(cls): cls.server.shutdown()
def get(self, path): return urllib.request.urlopen(f"http://127.0.0.1:{self.port}{path}")
def test_account_page_is_never_stored_by_a_shared_cache(self): cc = self.get("/account").headers.get("Cache-Control", "") d = directives(cc) safe = "no-store" in d or ("private" in d and "public" not in d and not any(x.startswith("s-maxage") for x in d)) self.assertTrue(safe, f"a shared cache may store the account page: {cc!r}")
def test_static_assets_load_from_cache_on_repeat_visits(self): cc = self.get("/logo.png").headers.get("Cache-Control", "") d = directives(cc) max_age = next((int(x.split("=", 1)[1]) for x in d if x.startswith("max-age=")), 0) self.assertGreaterEqual(max_age, 86400, f"a fingerprinted asset should cache at least a day, got: {cc!r}") self.assertIn("immutable", d, f"without immutable the browser re-checks every visit: {cc!r}")
if __name__ == "__main__": unittest.main()The first run fails twice, and this is the real output:
FAIL: test_account_page_is_never_stored_by_a_shared_cache (__main__.CacheHeaderTests)AssertionError: False is not true : a shared cache may store the account page: ''FAIL: test_static_assets_load_from_cache_on_repeat_visits (__main__.CacheHeaderTests)AssertionError: 0 not greater than or equal to 86400 : a fingerprinted asset should cache at least a day, got: ''
Ran 2 tests in 0.003sFAILED (failures=2)Uncomment the two marked lines (the fix in a real app is the same two headers, wherever your framework sets them) and run again:
Ran 2 tests in 0.004sOKNote what the tests assert: behaviors, not implementation details. The asset test parses the value instead of matching words, so public, max-age=0, must-revalidate (Cloudflare Pages’ default for HTML) fails it, and the account test passes on plain no-store, which forbids every cache from storing the response. “A shared cache never stores my account page” and “repeat visits load static files from cache” are things a user experiences. Write your tests at that level, so a later change that quietly breaks another behavior fails a test instead of shipping.
The hand check: read one header
Open your live site, open DevTools, go to the Network tab and reload. Click any request and look at the response headers. Cache-Control tells you the rule; on a CDN, a header like cf-cache-status or x-vercel-cache tells you whether the copy came from the cache (HIT) or your server (MISS). Check the page that shows the logged-in user’s data first, and do it logged in and logged out: a CDN rule usually starts caching on the logged-out version of a page. If that page is not private or no-store, you have Steam’s bug in miniature.
Headers are only half the story. Steam’s leak came from CDN rules, not origin headers: a “cache everything” rule with an edge TTL caches responses whatever your origin says, and origin-header tests stay green while the edge serves one user’s page to another. Save this as check_shared_cache.py, fill in your URL, two real test accounts, and a string only the first account’s page contains, and run it:
"""Run against YOUR live site: python3 check_shared_cache.py"""import urllib.request
URL = "https://your-app.example/account" # a page that shows the logged-in userCOOKIE_A = "session=token-for-user-a" # two real test accountsCOOKIE_B = "session=token-for-user-b"
CACHE_HEADERS = ("cf-cache-status", "x-vercel-cache", "x-cache")
def fetch(cookie): req = urllib.request.Request(URL, headers={"Cookie": cookie}) with urllib.request.urlopen(req) as res: return {k.lower(): v for k, v in res.headers.items()}, res.read().decode()
headers_a, body_a = fetch(COOKIE_A)headers_b, body_b = fetch(COOKIE_B)
status = next((f"{k}: {v}" for k, v in headers_b.items() if k in CACHE_HEADERS), None)if status is None: print("WARNING: no cache-status header found; find the one your CDN sends and add it to CACHE_HEADERS")else: assert "hit" not in status.lower(), f"a shared cache served a per-user page: {status}"assert USER_A_MARK not in body_b, "user B received user A's data: Steam's bug in miniature"assert body_a != body_b, "both accounts received the same page"print("shared-cache check passed:", status or "no cache header")Against a misconfigured CDN the first assertion trips (AssertionError: a shared cache served a per-user page: cf-cache-status: HIT). With no CDN in front it warns that no cache header was found, so you can add yours to the list; the body checks run either way.
The prompt to paste
Audit this app for caching. For every route and API endpoint, list: what data it returns, whether that data is per-user or public, the Cache-Control header it sends today, and the header it should send. Flag any per-user response that a shared cache could store, and any expensive public response that is not cached. Do not change code yet.
Do this before launch, next to the rest of the launch checklist. It takes twenty minutes and it is cheaper than apologizing to 34,000 users.
The Get AI Native ebook goes deeper on this. It is free, and the expected launch is around Christmas. Join the waitlist on the homepage.