CDN & Edge Caching — Performance

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…

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

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

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

⚠️ Cache labels stuck on the wrong thing

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.

What you will learn