How a CDN serves files from a server near you

· 2 min read

#how-it-works#web

A CDN (content delivery network) is a group of servers in many places, each keeping copies of your files. The idea to keep: most requests are answered by a copy close to the visitor, and the original server is asked only when the copy is missing.

The short version

Distance adds delay, so a copy that sits near the visitor is faster than a trip to the original server, called the origin. If the nearby server holds a fresh copy, it answers at once. If it does not, it asks the origin, keeps the reply and uses it for the visitors who come next.

How a CDN answers a request The browser asks a nearby CDN server. If the server has a fresh copy it answers the browser at once. If it has none, it asks the origin server, the origin replies, and the CDN server keeps the copy and answers. Browser Nearby CDN server Origin server 1 ask 2 miss 3 reply hit: fresh copy, answer at once
Simplified: a hit is answered by the nearby server, a miss goes to the origin first.

Step by step

  1. The browser asks for a file.
  2. The request is routed to a nearby CDN server; how that works depends on the CDN.
  3. A fresh copy there is a hit, and it is sent back without asking the origin.
  4. No copy, or a stale one, is a miss: the server asks the origin.
  5. The reply is stored and passed on, and later requests reuse it.
  6. A changed file shows up when the copy's Cache-Control time ends or the owner purges it.
Hit Miss
Fresh copy nearby yes no
Origin asked no yes

Why it matters

Less distance and less work for the origin make pages load faster. The costs are a third party your site depends on, extra DNS lookups and connections, and a copy that can be out of date until it expires or is purged. Caching basics are in How a cache makes things faster.

Sources