TExcelTAD

CDNs

The speed of light is a hard limit: a user in Hanoi fetching a page from a server in Virginia waits at least ~200 ms for each round trip. A Content Delivery Network (CDN) fixes this by keeping copies of content in edge servers (Points of Presence, PoPs) in hundreds of cities. Users are served from a nearby PoP, and only cache misses travel to the origin server.

What a CDN does

  • Caches static content (images, CSS, JS, video segments) close to users.
  • Terminates TLS near the user, so the handshake round trips are short.
  • Absorbs traffic spikes and DDoS attacks across a huge global network.
  • Keeps warm, optimised connections to the origin for dynamic requests that can't be cached.

Major CDNs include Cloudflare, Akamai, Fastly, Amazon CloudFront and Google Cloud CDN.

Why proximity matters so much

A new HTTPS request needs several round trips (TCP handshake, TLS handshake, the request itself). Multiply by the RTT:

python · try it yourself
round_trips = 3          # TCP + TLS 1.3 + HTTP request
for where, rtt_ms in [("origin in Virginia, user in Hanoi", 230), ("origin in Singapore", 35),
                      ("CDN PoP in Hanoi", 4)]:
    print(f"{where:<35} RTT {rtt_ms:>3} ms -> first byte after ~{round_trips * rtt_ms:>3} ms")
origin in Virginia, user in Hanoi   RTT 230 ms -> first byte after ~690 ms
origin in Singapore                 RTT  35 ms -> first byte after ~105 ms
CDN PoP in Hanoi                    RTT   4 ms -> first byte after ~ 12 ms

Routing users to the nearest PoP

CDNs use two main techniques:

  1. DNS-based: the CDN's DNS server looks at where the query comes from (the resolver's IP, or the client subnet if the resolver sends it) and answers with the IP of a nearby PoP.
  2. Anycast: every PoP announces the same IP address with BGP; the Internet's routing naturally carries each user's packets to the "closest" PoP in network terms.
python · try it yourself
POPS = {"Hanoi": (21.0, 105.8), "Singapore": (1.35, 103.8), "Frankfurt": (50.1, 8.7),
        "Ashburn": (39.0, -77.5), "Sao Paulo": (-23.5, -46.6)}

def distance_km(a, b):
    import math
    lat1, lon1, lat2, lon2 = map(math.radians, (*a, *b))
    d = (math.sin((lat2 - lat1) / 2) ** 2 +
         math.cos(lat1) * math.cos(lat2) * math.sin((lon2 - lon1) / 2) ** 2)
    return 6371 * 2 * math.asin(math.sqrt(d))

users = {"Da Nang": (16.05, 108.2), "Berlin": (52.5, 13.4), "Toronto": (43.7, -79.4), "Lima": (-12.0, -77.0)}
for user, location in users.items():
    pop = min(POPS, key=lambda p: distance_km(location, POPS[p]))
    km = distance_km(location, POPS[pop])
    print(f"user in {user:<8} -> PoP {pop:<10} {km:>6.0f} km, min RTT ~{2 * km / 200:4.1f} ms")
user in Da Nang  -> PoP Hanoi         606 km, min RTT ~ 6.1 ms
user in Berlin   -> PoP Frankfurt     422 km, min RTT ~ 4.2 ms
user in Toronto  -> PoP Ashburn       546 km, min RTT ~ 5.5 ms
user in Lima     -> PoP Sao Paulo    3454 km, min RTT ~34.5 ms

Caching with HTTP headers

The origin tells the CDN (and browsers) what may be cached and for how long using HTTP headers:

Header Meaning
Cache-Control: public, max-age=86400 anyone may cache it for a day
Cache-Control: s-maxage=600 shared caches (CDNs) may keep it 10 minutes
Cache-Control: private, no-store never store in a shared cache (personal pages)
ETag: "v42" / If-None-Match revalidate: "has it changed?" → 304 Not Modified
Vary: Accept-Encoding keep separate copies per encoding (gzip/br)
python · try it yourself
class EdgeCache:
    def __init__(self):
        self.store = {}            # url -> (body, expires_at)
        self.hits = self.misses = 0

    def get(self, url, now, origin):
        entry = self.store.get(url)
        if entry and entry[1] > now:
            self.hits += 1
            return "HIT "
        self.misses += 1
        body, max_age = origin[url]
        if max_age > 0:
            self.store[url] = (body, now + max_age)
        return "MISS" if max_age > 0 else "PASS"

ORIGIN = {"/logo.png": (b"...", 86400), "/app.js": (b"...", 3600), "/cart": (b"...", 0)}
edge = EdgeCache()
requests = [(0, "/logo.png"), (1, "/app.js"), (2, "/logo.png"), (3, "/cart"), (5, "/app.js"),
            (6, "/cart"), (3700, "/app.js"), (3701, "/logo.png")]
for t, url in requests:
    print(f"t={t:>4}s GET {url:<10} {edge.get(url, t, ORIGIN)}")
print(f"hit ratio: {edge.hits}/{edge.hits + edge.misses} = {edge.hits / (edge.hits + edge.misses):.0%}")
t=   0s GET /logo.png  MISS
t=   1s GET /app.js    MISS
t=   2s GET /logo.png  HIT
t=   3s GET /cart      PASS
t=   5s GET /app.js    HIT
t=   6s GET /cart      PASS
t=3700s GET /app.js    MISS
t=3701s GET /logo.png  HIT
hit ratio: 3/8 = 38%

/cart is personal, so it's never cached (PASS: always forwarded to the origin). /app.js expired after an hour and was fetched again.

Tip: Use versioned file names for static assets (app.3f9c2b.js) with a long max-age, and short or no caching for the HTML that references them. Deploying a new version then changes the file name, so nobody gets a stale script, and you don't have to purge the CDN.

Checking whether a response came from the CDN

bash
curl -sI https://www.example.com/logo.png

Sample output:

text
HTTP/2 200
content-type: image/png
cache-control: public, max-age=86400
age: 5123
x-cache: HIT
via: 1.1 varnish

age says how many seconds the object has been in the cache. Headers like x-cache, cf-cache-status (Cloudflare) or x-amz-cf-pop (CloudFront) show whether it was a hit and which PoP answered.

Test yourself

What is the main reason a CDN makes websites faster?

  1. It compresses all images to text
  2. It serves content from servers close to users, cutting round-trip time
  3. It upgrades users' Internet plans
  4. It removes HTTPS

Which header tells a CDN it must never store a personal page?

  1. Cache-Control: public, max-age=3600
  2. Cache-Control: private, no-store
  3. ETag
  4. Vary: Accept-Encoding

With anycast, how does a user reach a nearby PoP?

  1. The browser pings all PoPs
  2. Every PoP announces the same IP, and BGP routing delivers packets to the closest one
  3. The user picks it from a list
  4. DNS always returns the origin's IP