AlgoViz

Introduction to a CDN

easy 26 min

A content delivery network (CDN) is a set of servers in many places that keep copies of your content and answer users from nearby.

Video lesson · Chapter 1 of 5

A photograph crosses an ocean

0:00 / 3:11

What a CDN does, in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A content delivery network is a group of caching servers spread over many cities. Each one stands between the users near it and your own server, which is called the origin. If it holds a copy of what the user wants, it answers. If not, it fetches the content from the origin, answers, and usually keeps a copy.

Technically each of these servers is a reverse proxy with a cache. It speaks to the user as if it were your site, ends the encrypted connection, checks its cache, and talks to the origin only when it must.

Why it exists

Distance costs time. Light in glass fibre travels about 200,000 km each second, so a round trip between Sydney and Virginia, about 16,000 km apart, takes at least 160 ms. No faster server can change that. Only a closer one can.

Repetition costs money. If a million people load the same picture, the origin sends the same bytes a million times. With copies at the edge it sends them a few times, and the network takes the rest.

A single location is also fragile. Many locations can share a traffic spike, and one can be taken out of use while the others continue.

A short history

  1. September 1997

    RFC 2187 describes how web caches can cooperate with ICP, so that one cache asks its neighbours before it goes to the origin.

  2. February 2003

    RFC 3466 describes a model for connecting content delivery networks and defines shared words for them.

  3. December 2006

    RFC 4786 documents good practice for anycast services, where one address is announced from many places.

  4. November 2008

    Amazon opens CloudFront, a pay-as-you-go CDN.

  5. June 2012

    Netflix announces Open Connect, a delivery network of its own for its video.

  6. June 2022

    RFC 9111, the current HTTP caching standard, is published. The same month RFC 9213 gives CDNs a Cache-Control header of their own.

Words to know

Origin
Your own server or storage, where the content really lives.
Edge server
A CDN server near users that caches and answers.
PoP
Point of presence: a physical location with edge servers.
Cache hit
The edge has a usable copy and answers at once.
Cache miss
The edge has no usable copy and must ask the origin.
TTL
Time to live: how long a copy may be used.
Offload
The share of traffic that never reaches the origin.

How it works

Step through the idea, or press Play.

Step 1 of 3

Ask nearby. The user's request reaches a close edge server

Understand it

Start here

One print shop, kiosks everywhere

Imagine a comic that is printed in one city. Readers live everywhere. They could all write to the print shop and wait. Or kiosks could keep a few copies.

The comic and the kiosks
PRINT SHOP13 days1Far away: three days by van

A CDN is the chain of kiosks. A toy shop near your home instead of a factory far away works the same way.

The parts

Origin, edge, PoP

Two users, two edges, one origin

A user in Sydney sends a request to the Sydney edge server and a user in London to the London edge server. Both edge servers belong to the CDN, another company. Dashed arrows show that an edge asks our web server, the origin, only on a miss. The origin reads pictures from its file storage.
Users talk to the edge. Only misses reach what we run.

Words you need

  • Origin

    Your server or bucket. The source of truth.

  • Edge server

    A cache near users that speaks for your site.

  • PoP

    A location with edge servers in it.

  • TTL

    How long a copy may be used.

The problem

Life without a CDN

Five problems and what a CDN changes

ProblemWhy it happensWith a CDN
High latencyEach request travels to one placeA short trip to a close edge
Origin overloadAll traffic meets the same serversMost requests end at the edge
One point of failureIf the origin is down, everybody sees itCached content can still be served
Bandwidth costThe same bytes are sent again and againSent to the edge once per copy
Uneven experienceSpeed depends on the distanceMore similar everywhere
A CDN hides an origin outage only for content that is cached, and only as long as it may be served.

Without a CDN

Three long trips to one place.

How it works

A request, step by step

  1. 1

    The browser asks

    It wants a picture from a name such as cdn.example.com.

  2. 2

    The name becomes an address

    DNS or the network itself leads the browser to a nearby PoP.

  3. 3

    The edge receives it

    It finishes the TCP and TLS handshakes close to the user.

  4. 4

    The cache is checked

    The edge builds a cache key, usually from host, path and query, and looks it up.

  5. 5

    Serve or fetch

    On a hit it sends the copy. On a miss it asks the origin and keeps the answer if it may.

  6. 6

    The response

    The user gets the content with headers that tell the browser how long to keep it.

Miss, then hit

Many CDNs report the result in a header such as X-Cache, and the Age header says how old the copy is.

The numbers

Where the time goes

Take a user in Sydney and an origin in Virginia. Assume a 200 ms round trip to the origin, 10 ms to a Sydney edge, 20 ms for the name lookup and 30 ms of work at the origin. A new HTTPS connection with TLS 1.3 costs one round trip for TCP, one for TLS and one for the request.

A new connection, small file

Torigin=20+3⋅200+30=650 msThit=20+3⋅10+2=52 msT_{origin} = 20 + 3 \cdot 200 + 30 = 650\text{ ms} \qquad T_{hit} = 20 + 3 \cdot 10 + 2 = 52\text{ ms}
About 92% less. On a miss the edge reuses an open connection to the origin: 20 + 3 x 10 + 200 + 30 = 280 ms, still far below 650.

The same trip, added up

StepDirectEdge hit
Name lookup20 ms20 ms
TCP handshake220 ms30 ms
TLS handshake420 ms40 ms
Request and first byte650 ms52 ms
The distances are assumptions. The lesson is that every round trip gets shorter, also the handshakes.

Average and origin load

Tavg=h⋅Thit+(1−h)⋅Tmiss=0.95⋅52+0.05⋅280≈63 msRorigin=R (1−h)T_{avg} = h \cdot T_{hit} + (1-h) \cdot T_{miss} = 0.95 \cdot 52 + 0.05 \cdot 280 \approx 63\text{ ms} \qquad R_{origin} = R\,(1-h)
With 10,000 requests a second on average and a peak of 3x, a 95% hit ratio leaves the origin 30,000 x 0.05 = 1,500 a second.

Gains

What you get

  • Lower latency

    Fewer and shorter long trips.

  • Origin offload

    At a 90% hit ratio the origin sees one request in ten.

  • Scale

    A spike is spread over a large network.

  • Availability

    Another PoP can take over, and stale copies can be served.

  • Attack protection

    Floods meet the CDN's capacity first, if the origin cannot be reached around it.

  • Lower cost

    Less origin traffic and fewer servers. Compare it with the CDN bill.

Kinds of content

Static and dynamic

Static: cache it

  • Images, CSS, JavaScript
  • Fonts
  • Video and downloads
  • Same bytes for everybody

Dynamic: think first

  • API responses and HTML pages
  • Real-time data
  • Personal pages
  • Short lifetime, or no shared cache

Dynamic traffic can still gain. The edge ends the handshakes near the user, keeps warm connections to the origin and may run small programs (edge compute). But the answer itself comes from the origin.

May the CDN keep this?

Kinds of CDN

Pull and push

PullPush
Who startsThe first readerYou, before anybody asks
First requestSlow: a missFast, if the copy arrived
StorageOnly what is asked forEverything you upload
Work for youHeadersUploading and removing
Good forMany files, unknown demandFew large files, known demand
Most sites use pull and warm a few important files. The details are in CDN architecture and design.

Control

The headers that matter

Rules for three kinds of files

PathHeaderReason
/static/* with a hash in the namepublic, max-age=31536000, immutableThe name changes when the content does: 1 year
/images/*public, max-age=6048001 week
/api/* with personal datano-storeNo cache may keep it
no-store alone is enough. Adding no-cache and must-revalidate to it changes nothing for a cache that follows the standard.

CDNs differ in what they cache by default. Cloudflare goes by file extension and leaves HTML and JSON alone unless you add a rule. CloudFront uses 24 hours when no cache policy and no header say otherwise. Read more in Cache TTL and API caching.

Limits

When a CDN helps little

Do

  • Send Cache-Control on every response
  • Use names with a hash for static files
  • Compress text
  • Serve public files through the CDN
  • Watch the hit ratio

Avoid

  • Shared caching of personal pages
  • TTLs so short that they never hit
  • Changing a file without a plan for the copies
  • Caching secrets
  • Leaving the origin open to everybody

Do we need one?

If one office uses an internal tool next to its server, a CDN adds a hop and a bill.

Summary

The whole topic in one minute.

A CDN keeps copies of your content in many places and answers from the nearest one. A hit is a short trip. A miss costs the long trip once, and later readers use the copy.

It shortens latency, protects the origin, absorbs spikes and cuts bandwidth. It does not help with content that is different for every person and changes all the time, except by ending connections early and reusing warm ones.

Decide three things per kind of content: may a shared cache keep it, for how long, and how does it change.

  • A CDN is many caching reverse proxies near users.
  • Hit: short trip. Miss: long trip once.
  • Round trips, not bytes, dominate small files.
  • Origin load is requests times (1 - hit ratio).
  • Shared caches are for content that is the same for many people.

Sources