System Design · 02. Scaling · 9 min · Beginner
Content Delivery
Put copies of your files in cities near the users.
In short
Distance costs time: 600 ms to load from Sydney when the origin is in Virginia. A CDN keeps copies in edge servers near the users, so a hit costs 30 ms.
Static files are cached according to their headers, dynamic requests still go to the origin, and a purge or a new file name replaces old copies. The origin does far less work.
Key ideas
- You cannot make light faster, so move the data closer to the user. (step 2)
- The edge is a cache that lives near the user. The origin is still the source of truth. (step 3)
- Long max-age plus versioned file names gives the best of both: speed and instant updates. (step 7)
Good to know
- Users get faster pages, and the origin does a small part of the work. Both come from the same copies. (step 5)
- A CDN also soaks up traffic spikes and some attacks, because the edges answer most requests themselves. (step 6)
Watch out
- Faster servers do not help here. The time is spent on the road, not in the CPU. (step 1)
- Someone always pays for the first request. A CDN can warm popular files in advance. (step 4)
- Prefer versioned names so you rarely need to purge. Keep purge for emergencies. (step 8)
Key numbers
- Sydney user
- 30 / 230 ms
- Virginia user
- 30 / 35 ms
- Origin load
- 240/s
Terms
- Origin server
- The real server that holds your site; a CDN copies from it.
- Round trip time (RTT)
- The time for a message to reach a server and for the reply to come back.
- Speed of light limit
- Signals in fibre travel about 200,000 km a second, which sets a minimum delay over long distances.
- CDN (content delivery network)
- Many servers in many cities that keep copies of your files near your users.
- Edge server
- A CDN server in a city near users, which answers requests from its copies.
- Anycast
- One address announced from many places, so each user's traffic reaches the nearest one.
- Edge cache miss
- The edge has no copy, so it fetches the file from the origin and keeps it.
- Edge cache hit
- The edge already has a copy and answers right away.
- Static vs dynamic content
- Static files are the same for everyone and can be cached; dynamic responses differ per user.
- Cache-Control header
- A response header that says who may cache a response and for how long.
- Versioned file names
- Putting a hash in a file name so a changed file gets a new name and old copies never go stale.
- Purge
- Telling the CDN to delete a cached URL from all its edges at once.