Card 03/ 11

ConceptDifficulty: Beginner2 min

CDNs: Serving Files From Near the Reader

An image served from the next city arrives faster than one from another continent.

A CDN, or content delivery network, keeps copies of a site's static files at edge servers in many cities, so each reader downloads them from somewhere close. Static files are the ones that are the same for every reader: images, video, scripts and stylesheets. Serving them from nearby cuts the time each one takes, and takes their load off your own servers.

A reader in Amsterdam loading a page from a site hosted in California

Without a CDNevery file from the origin

Every image and script crosses the Atlantic. Each round trip takes about 150 ms (Colin Scott's 2020 latency figures), and a page that fetches its files in a few waves pays that several times over. The origin, the site's own server, sends every byte to every reader.

With a CDNfiles from an edge in the same city

The files come from an edge server in or near Amsterdam, a round trip of a few milliseconds on a typical connection. Only the first reader of a file there causes a fetch from California; every later reader gets the copy.

How it works. The site's DNS points its file addresses at the CDN. A reader's request reaches the nearest edge. If the edge holds a copy that has not expired, it answers at once, which is called a hit. If not, a miss, it fetches the file from the origin, keeps it, and answers. A header the origin sends, Cache-Control, tells the edge how long a copy may be kept.

What breaks without one. Distant readers wait longer for every page, and the origin carries the full weight of every file download, which for images and video is usually most of the bytes a site sends.

When it is not the answer. A CDN helps when many readers want the same file. A page built for one signed-in reader, or an API response that changes on every request, gains little, because each request misses. Products that play the part include Cloudflare and Amazon CloudFront.

So put static files behind a CDN whenever readers are spread far from your servers: distance is the one cost no faster code removes.