Your shop's origin is in America. A visitor in Singapore who opens the page waits about 345 ms, and most of that time goes on data crossing the ocean. If a copy were already on a server in Singapore, the answer would arrive in about 15 ms.
A CDN (Content Delivery Network) is a network of servers in many cities that keeps copies of your site's files close to visitors. Picture a shop whose central warehouse is in America, but which has a convenience store in Singapore. If the item is already on the store's shelf, you take it home right away. If not, the store orders it from the central warehouse, you wait a long time, and the store keeps one copy for the next shopper. The label on the item says how long it may stay on the shelf.
Terms first
- Origin: your real server, where the app and the database live.
- Edge (or PoP, Point of Presence): a CDN server in a city near the visitor, Singapore for example.
- HIT: the edge already has a copy and answers straight away. MISS: it doesn't, so it asks the origin.
- TTFB (Time to First Byte): the time from sending the request until the first byte of the answer arrives.
- Check it in the DevTools Network tab: the header
x-cache: HIT(on Cloudflare it's calledcf-cache-status) andage: 120, the copy's age in seconds.
One request, four places
The Lab on this page sends requests from Singapore to an origin in the United States. The numbers are sensible estimates: about 15 ms round trip to the Singapore edge, about 230 ms round trip from the edge to the origin, about 40 ms for the app on the origin, and about 60 ms for the database query. A static file needs only about 5 ms on the origin, with no database.
What happens, file app.3f9a1c.js |
Browser cache | Singapore edge | Origin | Total, about |
|---|---|---|---|---|
| You, first request | MISS | MISS | asked | 15 + 230 + 5 = 250 ms |
| Another visitor in Singapore | MISS (their own browser) | HIT | not asked | 15 ms |
| You again, the next day | HIT | not asked | not asked | 0 ms |
An HTML page that misses costs even more: 15 + 230 + 40 + 60 = 345 ms. A browser cache belongs to one person; the edge cache is shared by every visitor in that city. That's the win of a CDN: one MISS, thousands of HITs.
Cache-Control: who may keep it, and for how long
The origin labels each response with the Cache-Control header. The CDN and the browser follow it.
Cache-Control: public, max-age=31536000, immutable
Cache-Control: public, max-age=60, s-maxage=86400
Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=600
Cache-Control: no-cache
Cache-Control: private, no-store
public: any cache may keep it, the CDN included.private: only that visitor's browser.max-age=60: fresh for 60 seconds, for every cache, the browser included.31536000seconds is one year.s-maxage=86400: only for shared caches (CDNs and proxies), where it replacesmax-age. The second line means the browser keeps it 1 minute and the CDN keeps it 1 day.no-cache: it may be stored, but must be checked with the origin every time before use.no-store: don't store it at all.immutable: the content will never change, so the browser doesn't recheck it even on reload.stale-while-revalidate=600: once it's no longer fresh, the old copy may still be used for up to 600 more seconds while a new one is fetched in the background.
stale-while-revalidate at the edge
With the third line (s-maxage=60, stale-while-revalidate=600) on the page /, this is what happens in the Lab:
| Time | Status at the edge | Total, about |
|---|---|---|
| Minute 0 | MISS, stored | 345 ms |
| +1 minute (age 60 seconds) | STALE: the old copy is sent, the edge fetches a new one in the background | 15 ms |
| +1 hour | MISS, past 60 + 600 seconds | 345 ms |
A visitor who arrives during STALE doesn't wait for the origin at all.
This table needs a CDN that stores HTML. By default, Cloudflare doesn't store HTML or JSON, whatever the Cache-Control says, because it decides by file extension. Without an extra rule, the origin answers every request for / and the edge reports cf-cache-status: DYNAMIC. Create a Cache Rule for that page with the "Eligible for cache" option, and your Cache-Control is then used. Other CDNs have their own default rules, so check their documentation.
Purge, cache keys and hashed file names
A cache key is the "name" a CDN uses to decide two requests are the same file: usually the full URL including the query string, so /app.js?v=2 differs from /app.js. Headers named in Vary (such as Accept-Encoding) count too.
A purge deletes copies at the edge before their time is up: by URL, or by tag. A response can carry a label like Cache-Tag: product-123 (Cloudflare) or Surrogate-Key: product-123 (Fastly). When product 123 changes, purge just that tag: every page that includes it is removed, and the rest of the cache stays intact.
But a purge only cleans the CDN, not visitors' browsers. Say app.js has no hash in its name and is sent with max-age=31536000, immutable, then you change it and purge the CDN. Yesterday's visitor keeps using the old app.js from their browser cache, for up to a year. The fix is hashed file names: app.3f9a1c.js. The content changes, the hash changes, the URL is new, so no cache has a copy of it. Since the content behind an old URL is guaranteed never to change, max-age=31536000, immutable is safe. The HTML that lists those file names gets a short cache or no-cache.
Edge functions: code that runs at the edge
Modern CDNs can run your JavaScript right at the edge, with no round trip to the origin: Cloudflare Workers, Netlify Edge Functions, Vercel. Good for redirects by country, A/B tests, or a simple login check.
// Cloudflare Worker
export default {
async fetch(request) {
const url = new URL(request.url);
const country = request.cf?.country; // filled in by Cloudflare, e.g. "DE"
const isPage = request.headers.get('accept')?.includes('text/html'); // a page, not JS, CSS or an image
const alreadyOnDe = url.pathname === '/de' || url.pathname.startsWith('/de/');
if (country === 'DE' && isPage && !alreadyOnDe) return Response.redirect('https://myshop.com/de', 302);
return fetch(request); // everything else goes through the cache and origin as usual
},
};
The alreadyOnDe check prevents a redirect loop: without it, /de itself is redirected to /de again, without end. The isPage check keeps JS, CSS and image files from being redirected too.
The exercise version: parseCacheControl and the hit ratio
The cache hit ratio is the percentage of requests answered from the cache: cacheHits / totalRequests × 100. For static files, aim above 90%.
| Call | Result |
|---|---|
parseCacheControl('public, max-age=31536000, immutable') |
{ maxAge: 31536000, isPublic: true, noStore: false, immutable: true } |
parseCacheControl('no-store') |
{ maxAge: 0, isPublic: false, noStore: true, immutable: false } |
parseCacheControl('no-cache') |
{ maxAge: 0, isPublic: false, noStore: false, immutable: false } |
calculateCacheHitRatio(1000, 920) |
92 |
calculateCacheHitRatio(3, 1) |
33.33 |
calculateCacheHitRatio(0, 0) |
0 |
- Split the header on commas, then
trim(), because there's a space after each comma:'public, max-age=3600'.split(',')gives'public'and' max-age=3600'. maxAgemust be a number:Number('3600'), not the string'3600'. Withoutmax-age, it's0.- Rounding to 2 decimals while staying a number:
Math.round((hits / total) * 10000) / 100.toFixed(2)gives the string'33.33', which is not the number33.33.
⚠️ Cache labels stuck on the wrong thing
- Thinking
no-cachemeans "don't store". That'sno-store.no-cacheis still stored, just checked first every time. - A long
max-ageon a file without a hash. A purge doesn't reach browsers, so visitors are stuck on the old version. - Personal data marked
public. The CDN may send one person's cart to someone else. Per-user data getsprivateorno-store. - A random query string in the URL like
?t=1712345. The cache key is different every time, so it always misses. - In the exercise: the key order must be
maxAge,isPublic,noStore,immutable, and the hit ratio comes back as a number,0whentotalRequestsis 0.
TL;DR: A CDN keeps copies at an edge near visitors: a HIT from the Singapore edge takes about 15 ms, a MISS to an origin in America about 250 to 345 ms. Cache-Control says who may store a response and for how long: max-age for every cache, s-maxage for CDNs only, no-cache store but check first, no-store never store, immutable never changes, stale-while-revalidate send the old copy while fetching a new one. The cache key is usually the full URL. A purge cleans the CDN (by URL, or by tag through Cache-Tag/Surrogate-Key) but not browsers, so assets get hashed file names plus max-age=31536000, immutable. Edge functions run code at the edge. Hit ratio = hits / total × 100, aim above 90%.
⚡ A copy near the visitor
Meaning: A CDN keeps copies of your files at the edge, a server in a city near the visitor. A HIT from the Singapore edge takes about 15 ms, a MISS to an origin in America about 250 to 345 ms. One MISS, thousands of HITs, because the edge cache is shared by every visitor in that city.
⚡ Cache-Control says who and for how long
Write:
Cache-Control: public, max-age=60, s-maxage=86400
Guess first: in this header, what's the difference between max-age and s-maxage?
s-maxage is only for shared caches (CDNs and proxies), while max-age applies to every cache, the browser included. So the browser keeps it 1 minute, the CDN 1 day.
Meaning: no-cache is still stored but checked first every time, no-store is never stored. Personal data gets private or no-store.
⚡ A purge doesn't reach browsers
Meaning: A purge only cleans the CDN. That's why assets get hashed file names like app.3f9a1c.js plus max-age=31536000, immutable, and the HTML that lists those names gets a short cache or no-cache.