A content delivery network (CDN) is a set of servers spread around the world, called edges, that keep copies of your files close to your users. A user in Mumbai gets your JavaScript from a server in Mumbai instead of from your one origin server in Virginia.
That sounds like a simple speed trick, and it is mostly a caching problem with all of caching’s traps: copies that are out of date, copies that belong to someone else, and caches that quietly store nothing at all until a traffic spike finds out. This page shows each one happening.
In the labs after the walkthrough, each row is a region: its users, their nearest edge and a line to the origin. Rows are placed by distance, so a longer line is a longer round trip. Each chip is one request. It is white on its way out and coloured on its way back by who answered: the edge, the shield or the origin. The small boxes in an edge are the copies it holds, each with a bar showing the time it has left. Network time is slowed six times so you can see it.
00 The life of one request
Before the live labs, follow a single request for a JavaScript file from a user in Sydney to a server in Virginia and back. Step through at your own pace, or press Play all.
Step 1 of 10
Meet the pieces
A CDN puts servers between your users and your own server. Edges sit in many cities, close to users, and keep copies of your files. A shield is one more cache, next to your server. The origin is your server: it has the real files.
01 Distance is latency
Light in fibre covers about 200 km per millisecond, and real cables do not run in straight lines. A round trip from Sydney to Virginia takes about 200 ms before the server does any work. No amount of server tuning removes that; only moving the answer closer does.
A CDN does that. The user talks to an edge a few milliseconds away. If the edge has a copy, the answer never crosses the ocean.
- On its way
- Edge hit
- From the origin
- Click a chip to follow it
- Average response
- –
- Origin requests
- 0
For users far from your servers, the network, not your code, sets the floor on response time. A CDN lowers that floor by answering nearby.
02 Hits, misses and separate caches
An edge that has a fresh copy answers at once: a hit. One that doesn’t forwards the request to the origin, waits, stores the answer and passes it on: a miss. The miss is as slow as having no CDN.
Every edge keeps its own cache. A copy in London does nothing for a user in Sydney, so the first request in every region misses. If a second request arrives while the first is still fetching, the edge makes it wait for that fetch instead of sending another (more in section 08).
- On its way
- Edge hit
- From the origin
- Click a chip to follow it
- Edge hit ratio
- –
- Edge hits
- 0
- Origin requests
- 0
- Copies at edges
- 0
The hit ratio, the share of requests the edge answers itself, is the number to watch. It is lowest right after a deploy or purge, and for files few people ask for.
03 TTL: how long a copy lives
The origin tells caches how long a response stays fresh with a header: Cache-Control: public, max-age=60 means any cache may keep it for 60 seconds. That time is the TTL. Until it runs out the edge answers from its copy without asking the origin anything, even if the origin has changed the file since.
- A long TTL means few origin requests and a high hit ratio, but users can see old content for that long after you change it.
- A short TTL keeps content fresh, at the cost of more misses and more origin load.
- On its way
- Edge hit
- From the origin
- Click a chip to follow it
- Origin requests
- 0
- Old version served
- 0
- Edge hit ratio
- –
Pick the TTL from how long stale content is acceptable, file by file: long for images and fonts, short for news and prices.
04 Public, private and no-store
A CDN cannot see what a response means. It only reads headers. If a page is personal, the headers must say so:
publiclets shared caches, such as a CDN, store it and give it to anyone.privateallows only the user’s own browser to keep it. A CDN must pass it through.no-storemeans no cache anywhere keeps it.
Mark a personal page public and the edge will store the first visitor’s page and hand it to everyone after them. This has happened to real companies, usually through one wrong rule.
- On its way
- Edge hit
- From the origin
- Click a chip to follow it
- Wrong person’s page
- 0
- Edge hits
- 0
- Origin requests
- 0
Default to private for anything that depends on who is asking. Cache public pages, and fetch the personal parts separately.
05 The cache key
An edge finds a copy by its cache key, usually the host, the path and the query string. Two requests share a copy only if their keys match. That makes the key a trade-off in both directions:
- Too much in the key splits one page into many copies. Ad links add
?utm_source=…with endless values, and each one becomes its own miss. - Too little in the key merges responses that differ, as in section 04.
- Adding the session cookie keeps pages apart per user, but then each user warms their own copy and the cache helps little.
- On its way
- Edge hit
- From the origin
- Click a chip to follow it
- Edge hit ratio
- –
- Copies at edges
- 0
- Origin requests
- 0
Put in the key exactly what changes the response, nothing more. Strip tracking parameters, and keep personal data out of cached pages instead of keying on it.
06 Origin shield: one request, not one per edge
With hundreds of edges, a file nobody has asked for lately costs one origin request per edge. An origin shield (also called tiered caching) adds one more cache next to the origin. Edges that miss ask the shield; only the shield asks the origin.
A miss at the edge that hits the shield still crosses the ocean, so it is no faster for that user. The win is for the origin, which now sees one request per file per TTL.
- On its way
- Edge hit
- From the shield
- From the origin
- Click a chip to follow it
- Origin requests
- 0
- Shield hits
- 0
- Edge hit ratio
- –
A shield matters most when you have many edges, an origin that is expensive to call, or files that are each asked for rarely.
07 Purging and versioned file names
Static files such as scripts and styles want very long TTLs, often a year. But then a deploy changes nothing for users until the copies expire. There are two ways out:
- Purge: tell the CDN to drop its copies. It takes a moment to reach every edge, and afterwards every region misses at once.
- Versioned names: give each build its own file name, such as
app.3f9c.js, and link to it from HTML with a short TTL. A new build is a new name, which no cache has seen, so no old copy can be served for it. Old copies sit there unused until they expire.
- On its way
- Edge hit
- From the origin
- Click a chip to follow it
- Old version served
- 0
- Origin requests
- 0
- Edge hit ratio
- –
Version the file names of static assets and cache them for a year. Keep purges for mistakes, and for content whose URL cannot change.
08 A viral spike, and wrong cache rules
The origin below can handle about 100 requests a second: four workers and a short queue. Past that it answers 503. A viral link brings twelve times the normal traffic. With a working cache, the origin still sees about one request per region every five seconds, whatever the traffic.
The cache only works if the rules let it. Three common mistakes make every request a miss, and you usually find out during the spike:
no-storeorprivateon pages that are the same for everyone, often a framework default.- A
Set-Cookieon every response. Many CDNs will not store a response that sets a cookie. - Tracking parameters in the cache key, so every ad click is a new key.
There is one more trap: when a popular copy expires mid-spike, dozens of requests miss at the same moment. Collapsing makes them wait for one fetch. Without it, each one goes to the origin.
- On its way
- Edge hit
- From the origin
- 503 error
- Click a chip to follow it
- Origin load
- 0/s
- Peak origin load
- 0/s
- Errors (503)
- 0
- Edge hit ratio
- –
Check the hit ratio of your busiest pages before launch day. A CDN that caches nothing still looks fine until the traffic arrives.
09 stale-while-revalidate
With a plain TTL, the first user after each expiry pays for a full trip to the origin. Cache-Control: max-age=60, stale-while-revalidate=600 changes that: for ten minutes after the TTL, the edge answers at once with its stale copy and fetches a fresh one in the background. The next user gets the fresh copy.
Users then never wait on the origin for a popular file, at the cost of one more request seeing content one TTL older than it could have. A related directive, stale-if-error, serves the stale copy when the origin is failing.
- On its way
- Edge hit
- From the origin
- Stale, refreshing
- Background refresh
- Click a chip to follow it
- Waited on origin
- 0
- Served stale
- 0
- Average response
- –
For content that is fine a little stale, stale-while-revalidate removes the slow request from the user’s path entirely.
10 Dynamic pages and code at the edge
Personal pages cannot be cached whole. Most CDNs now run your code on the edge servers (Cloudflare Workers, Fastly Compute, CloudFront Functions and Lambda@Edge, Akamai EdgeWorkers), so a page can be built a few milliseconds from the user. It is tempting to move everything there.
But code needs its data. If the edge function reads a database that lives in Virginia, each query crosses the ocean. A page that needs three queries in a row is three round trips, slower than building it at the origin next to the database. Edge code pays off when its data is at the edge too: cached, replicated, or carried in the request, such as a signed cookie.
- On its way
- Edge hit
- From the origin
- Built at the edge
- Click a chip to follow it
- Average response
- –
- Origin requests
- 0
Move code to the edge only with the data it reads. Common uses are redirects, auth checks on signed tokens, A/B routing and stitching cached fragments together.
11 Choosing a CDN
The ideas above are the same everywhere. The products differ in network size, how fast purges reach every edge, how you configure them and what code they can run. A rough map:
| CDN | Code at the edge | Purge | Shield / tiers | Known for |
|---|---|---|---|---|
| Cloudflare | Workers (JavaScript, Wasm) | By URL; by tag, prefix or host on some plans | Tiered Cache | Large network, free plan, security bundled in |
| Fastly | Compute (Wasm); VCL for cache rules | Very fast, by URL or surrogate key | Shielding, pick a shield location | Programmable caching, quick purges |
| Amazon CloudFront | CloudFront Functions, Lambda@Edge | Invalidations by path, with wildcards | Regional edge caches, Origin Shield | Close fit with S3 and the rest of AWS |
| Akamai | EdgeWorkers | Fast Purge, by URL or cache tag | Tiered distribution | One of the oldest and largest networks, enterprise focus |
Check the current docs before you choose: features, limits and prices change often and differ by plan.
12 Check yourself
You put a CDN in front of your site with a one-hour TTL. A user in Sydney is the first visitor from Australia today. How fast is their request?
The account page shows the signed-in user’s name. Someone marks it Cache-Control: public, max-age=300. What happens?
Your app ships app.js with a one-year TTL. You fix a bug and deploy. What is the cleanest way to get the fix to users?
Your hit ratio on product pages is 20% even though the TTL is an hour. Every ad link adds ?utm_source=… with a different value. Why?
A post goes viral and traffic jumps 20 times. The origin falls over even though there is a CDN. The responses set a session cookie on every request. What is the likely cause?