Skip to content

How a CDN serves from nearby

Working knowledgeUnder the hood

Your server is in one city, and your users are everywhere. A CDN keeps copies of your files in cities near them. Here is how a request reaches a nearby copy, how the copy is found, and what happens when it is not there.

01 Distance is the slow part

Light in optical fibre covers roughly 200 km per millisecond. Sydney and Frankfurt are about 16,500 km apart, so one round trip between them can never take less than about 165 ms, and real routes are longer than a straight line. A new HTTPS connection needs a TCP handshake, a TLS handshake and then the request itself: about three round trips before the first byte arrives, which is half a second gone on distance alone.

A content delivery network runs many edge servers in data centres around the world. Each edge keeps a cache of your files. A user in Sydney talks to the Sydney edge, a few milliseconds away, and only the edge ever talks to your origin server, and only when it has to.

02 How a user reaches the nearest edge

You point a name such as cdn.shop.com at the CDN. From then on, the CDN decides which edge answers. There are two common ways:

Two ways to steer a user to a nearby edge
MethodHow it worksCatch
DNS steeringThe CDN’s DNS server returns the IP of an edge close to whoever asked, judged by the resolver’s address.It sees the resolver, not the user. A user on a far-away public resolver can be sent to the wrong city.
AnycastEvery edge announces the same IP address. Internet routing (BGP) carries each packet to the nearest announcement, in network terms.Nearest by routing is not always nearest by distance, and a route change can move a user mid-connection.

Many CDNs mix both. Either way, the browser just connects to an IP address and has no idea a choice was made.

03 The cache key decides what counts as the same

An edge stores each response under a cache key built from the request. By default this is typically the host, the path and the query string. Two requests share a cached copy only if their keys match exactly, so the key decides your hit rate.

Three requests for one photo, and the keys they make (default settings)
RequestCache keyResult
/img/cat.jpgshop.com/img/cat.jpgmiss, then cached
/img/cat.jpg?utm_source=mailshop.com/img/cat.jpg?utm_source=maila different key: another miss, another copy
/img/cat.jpg, Accept-Encoding: brshop.com/img/cat.jpg + brwith Vary: Accept-Encoding, one copy per encoding

A response header Vary: Accept-Encoding tells caches that the body depends on that request header, so a Brotli copy is never sent to a client that cannot read it. CDN settings let you drop query parameters that do not change the response (such as tracking tags), sort them, or add a header or cookie to the key when the response really depends on it.

04 A miss, a hit and a revalidation

Follow one photo through the Sydney edge. Watch the origin column: it is touched on the first request and on the check an hour later, and never in between.

A miss, a hit, and a revalidation at one edge
Step 1 of 12
Origin fetches 0
Requests (example times)
Ana (Sydney)Bo (Sydney)Edge (Sydney)Origin (EU)Nothing sent yet
Sydney edge cache
Empty
  • just sent or stored
  • cache hit
  • stale copy

The site’s photos are served through a CDN. The Sydney edge has nothing cached yet, and the origin server is in Frankfurt, about 16,500 km away.

10:00 time
HitOne short round tripUser to edge and back. The origin does nothing.
RevalidationPlus a checkA round trip to the origin, but a 304 carries no body.
MissPlus a full fetchThe whole file crosses the long link once, then the edge has it.

05 Your origin sets the rules with headers

The edge does not guess how long a file stays good. Your origin says so in the Cache-Control response header, and the CDN follows it unless you override it in the CDN’s settings.

Common Cache-Control directives
DirectiveMeaning
max-age=3600Fresh for 3,600 seconds, for any cache, including the browser.
s-maxage=600Overrides max-age for shared caches such as a CDN only.
publicAny cache may store it, even for a request that carried credentials.
privateOnly the user’s own browser may store it. The CDN must not.
no-cacheMay be stored, but must be revalidated with the origin before every use.
no-storeNever store it anywhere.
immutableThis URL will never change, so do not even revalidate while fresh.
stale-while-revalidate=60For 60 seconds after expiry, serve the stale copy at once and revalidate in the background.

You can see a CDN’s decision in the response headers. Here is a real request to cdnjs, which runs on Cloudflare. Header names vary by CDN: Cloudflare uses cf-cache-status, CloudFront and Fastly use X-Cache.

Shell
curl -sI https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js \
| grep -iE '^(http|cf-cache-status|age|cache-control|vary|cf-ray)'
Text
HTTP/2 200
cf-cache-status: HIT
age: 3395736
cache-control: no-transform, public, s-maxage=30672000, max-age=30672000, immutable
vary: Accept-Encoding
cf-ray: a53f9a8eafd476d5-LHR

HIT means the edge answered by itself, and age says its copy is about 39 days old, which is fine because the library at this URL never changes. The end of cf-ray names the edge that answered, here LHR (London), because the request was made from the UK.

06 Change the URL, not the file

Long cache times and updates pull against each other. If app.js is cached for a year and you ship a fix, edges and browsers keep the old file. CDNs offer a purge to delete copies, but it has to reach every edge, and it cannot reach browsers. The usual answer is to put a hash of the content in the file name, so a new version is a new URL and a new cache key.

Fixed name
<script src="/app.js"></script>
Cache-Control: max-age=31536000
→ old app.js for up to a year
Hashed name
<script src="/app.3f9a1c.js"></script>
Cache-Control: max-age=31536000, immutable
→ a new build is a new URL

The HTML page that names those files is cached briefly or revalidated each time, so it can point to the new names as soon as you deploy. Build tools such as Vite and webpack add the hashes for you.

07 When it bites

A CDN caches whatever the rules allow, including pages meant for one person. If a signed-in page goes out as public or with a long s-maxage, the next visitor gets someone else’s account page. Mark personal responses private or no-store, and check what your CDN does with responses that set cookies.

?utm_source=…Query noise splits the cacheEvery new tracking tag makes a new key, so popular files miss again and again. Drop parameters that do not change the response from the key.
Cookie in the cache keyOne copy per visitorIf the key includes a session cookie, every user has their own key and the hit rate falls to almost nothing.
max-age expires at 12:00A crowd misses at onceWhen a hot file expires, thousands of requests can miss together and all hit the origin. Most CDNs collapse them into one origin fetch; stale-while-revalidate helps too.
300 edges, 1 originEach edge has its own cacheA file cached in Sydney is still a miss in São Paulo. Rarely requested files miss almost everywhere. An origin shield, one extra cache layer in front of the origin, turns many edge misses into one origin fetch.
purge /app.jsPurging is not instant everywhereA purge takes time to reach every edge and does nothing for copies already in browsers. Prefer new URLs for new content.

08 Check yourself

Question

A marketing email links to /img/cat.jpg?utm_source=mail. The photo is already cached at every edge under /img/cat.jpg. With default settings, what happens to the first click in each city?

Question

A cached copy is past its max-age, and the origin answers the edge’s check with 304 Not Modified. What crossed the long link to the origin?

Question

You deploy a fix to /app.js, which is served with max-age=31536000. What is the most reliable way to get users onto the new code?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?