Belajar
← All lessons

How a CDN works

Ask for the same file twice

You, Jakarta
Edge, Singapore
Origin, Virginia

edge.js

// runs on every edge serverasync function handle(request) {  const cached = await cache.match(request);  if (cached) return cached;   const res = await fetch(ORIGIN + request.path);  await cache.put(request, res.clone());  return res;}

origin.js

app.get("/logo.png", (req, res) => {  res.set("Cache-Control", "public, max-age=3600");  res.sendFile("logo.png");});

The nearest edge answers so the trip is short

You are inJakartaBerlinSeoulCape Town

routing.js

// every edge answers on the same IP (anycast),// so the network routes you to the closest oneconst edge = edges.reduce((a, b) =>  km(you, a) < km(you, b) ? a : b); // light in fiber does about 200 km per msconst rtt = (place) => 5 + km(you, place) / 70;const viaEdge = rtt(edge);const direct = rtt(origin); // a new HTTPS page load takes about 4 round tripsconst pageLoad = 4 * viaEdge;

max-age sets how long a copy lives and how stale it can get

Cache-Control: max-age1 min10 min1 hour
Minutes since the edge cached v10 min

A short max-age keeps copies fresh, but sends more trips to the origin

origin.js

res.set("Cache-Control", `public, max-age=${MAX_AGE}`);

edge.js

const age = (Date.now() - copy.fetchedAt) / 1000;if (age < copy.maxAge) return copy.body; copy = await fetchFromOrigin(request);return copy.body;

Purge drops the old copy so the next visit gets the new one

Visitor
Edge
Origin

deploy.js

// deploy.js, run by the site ownerawait writeFile("public/banner.txt", text); await fetch("https://api.cdn.test/purge", {  method: "POST",  body: JSON.stringify({ files: ["/banner.txt"] }),});

edge.js

// a normal requestconst cached = await cache.match(request);if (cached) return cached;const res = await fetch(ORIGIN + request.path);await cache.put(request, res.clone()); // a purge requestawait cache.delete("/banner.txt");

Topics

Next: How gzip compression works

Open lesson