Module 4 · Caching and performanceLesson 39 of 886 minBeginner
Content delivery networks (CDNs)
A CDN keeps copies of your files on servers all over the world, so every user downloads from somewhere close.
Compare "No CDN" with the first and the second request through a CDN. Watch the load time.
Data can't travel faster than light, and light in fibre crossing the Pacific and back takes around 150 to 200 ms. Each round trip pays that. A page with many files feels slow for a faraway user no matter how fast your servers are.
A CDN (content delivery network) solves this by running edge servers in hundreds of cities. Users are routed to the nearest one.
How it works
- A user in Sydney requests
photo.jpg. DNS sends them to the Sydney edge. - Miss: the edge doesn't have it, so it fetches it from your origin server and keeps a copy.
- Hit: the next Sydney user gets it straight from the edge, in a few milliseconds.
How long the edge keeps it is controlled by your Cache-Control headers.
What to put on a CDN
- Static files: images, video, JavaScript, CSS, fonts. Almost always.
- Whole pages that are the same for everyone (blog posts, docs, marketing pages).
- API responses that are public and change slowly, with short TTLs.
- Video streaming: CDNs are built for it.
Other benefits
- Offloads your origin: most requests never reach your servers.
- Absorbs spikes and DDoS attacks with huge spare capacity.
- Terminates TLS near the user, saving round trips on connection setup.
- Edge computing: many CDNs can run small bits of code at the edge (redirects, auth checks, A/B tests).
Invalidation, again
When you change a file, edges may keep the old one until its TTL ends. Options:
- Purge the file through the CDN's API.
- Better: use versioned file names (
logo.v2.pngor a content hash). New name, new file, no purge needed, and the old one can be cached for a year.
Cloudflare, Fastly, Akamai and CloudFront are common CDNs.