Caching & CDNs
Serve content faster by storing copies closer to users and skipping needless downloads
The fastest request is the one you never make. Caching stores copies of responses so they can be reused instead of re-fetched, and CDNs push those copies physically closer to users. Together they're the backbone of a fast web.
Why Cache?
Re-downloading an unchanged logo on every page view wastes bandwidth, time, and server capacity. A cache keeps a local copy and reuses it:
first visit: browser ──▶ server (downloads logo.png, 40KB)
next visits: browser ──▶ cache (0 bytes over the network — instant)
Caches live at many layers: the browser, a CDN, a reverse proxy, the server. The same principles govern them all.
Cache-Control: The Master Switch
The server tells caches what to do via the Cache-Control response header:
Cache-Control: max-age=3600 cache for 1 hour
Cache-Control: no-store never cache (sensitive data)
Cache-Control: no-cache cache, but revalidate before using
Cache-Control: public, max-age=31536000, immutable cache for a year, never revalidate
max-age— seconds the response stays "fresh" and reusable without asking.no-store— don't cache at all (use for private/sensitive responses).no-cache— you may store it, but must revalidate with the server before reuse.immutable— promise it will never change, so don't even revalidate.
Build tools name files with a content hash — app.9f2a1b.js —
and serve them with a one-year immutable cache. When the file
changes, the hash changes, so the URL changes, so browsers fetch the new
one. You get aggressive caching AND instant updates.
Freshness vs Validation
Two questions a cache asks:
- Is it still fresh? If within
max-age, use the cached copy immediately — no network at all. - If stale, has it actually changed? Instead of re-downloading, the browser validates with an ETag — a fingerprint of the content:
Response: ETag: "abc123"
Later: browser sends If-None-Match: "abc123"
server replies 304 Not Modified → reuse cache, no body re-sent
or 200 OK + new body → content changed
A 304 Not Modified means "your copy is still good" — a tiny response instead of the full file. (Recall 304 from the status-codes lesson.)
Content Delivery Networks
A CDN is a network of servers spread around the world that cache your content at edge locations near users. A visitor in Tokyo hits a Tokyo edge server instead of your origin in Virginia:
without CDN: Tokyo user ─────────── 150ms ───────────▶ origin (Virginia)
with CDN: Tokyo user ── 10ms ──▶ Tokyo edge (cached copy)
CDNs cut latency (shorter physical distance), offload traffic from your origin, and absorb spikes. Static assets — images, CSS, JS, fonts — are the classic thing to serve from a CDN.
Data can't travel faster than light, so distance is a hard floor on speed. A CDN's whole job is shrinking that distance by keeping a copy near the user — which no amount of server optimization can replace.