AlgoViz

CDN architecture and design

medium 32 min

How a CDN is built: edge locations, a shield in front of the origin, routing that finds a good edge, cache keys, and the choice between pulling content on demand and pushing it in advance.

See it run

How content gets in, how users get there, and what stands in front of the origin.

Operations

Pull

A user in Tokyo asks for a 2.5 MB picture with max-age=86400.

Step 1 of 6

The user asks

User in TokyoCDN DNSTokyo edgeemptyOriginUS east

The browser needs the address of the CDN name.

Step 1: The user asks

def handle(path):    copy = cache.get(path)    if copy and copy.fresh():        return copy    copy = fetch(origin, path)    cache[path] = copy    return copy
First request
Slow
Storage
What is asked for
Good for
long tail

Nothing to upload. The headers are the interface.

In the real world

The same cdn architecture and design doing real jobs. Pick one and step through it.

The same article from four links.

Step 1 of 3

Whole query in the key

requestkeyresult
/news?utm=a/news?utm=amiss
/news?utm=b/news?utm=bmiss
/news?utm=c/news?utm=cmiss
/news?utm=d/news?utm=dmiss

0% hits

Four links, four keys, four misses.

Step 1: Whole query in the key

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Cookies in the cache key

    major

    Every visitor gets a separate copy, so nothing is shared.

    Wrong
    key = (path, request.headers["Cookie"])
    Right
    key = (path, normalized_language)
  • A header that is not in the key changes the page

    critical

    One request can plant a wrong page for everybody.

    Wrong
    link = "https://" + request.headers["X-Forwarded-Host"] + path
    Right
    link = SITE_URL + path
  • Pushing everything everywhere

    major

    Storage and transfer for files nobody reads.

    Wrong
    for p in all_pops: push(all_files, p)
    Right
    for p in pops_with_demand: push(planned_files, p)
  • Origin sized for a perfect CDN

    critical

    A purge or a shield failure multiplies the load.

    Wrong
    capacity = 600      # per second, only with every cache warm
    Right
    capacity = 3000     # shield bypassed; beyond that, shed load

Interview tips

  • How to explain it

    • Farm, depot, corner fridge.
    • Origin, shield, edge.
    • A road sign is the routing.
  • Memory trick: CACHE

    • Content copied, Anycast or GeoDNS.
    • Cache-Control sets the TTL.
    • Hit is fast, Edge is the hero.
  • Decide

    • Pull or push?
    • Which parts in the key?
    • Where is the shield?
  • Check

    • What if a PoP goes?
    • What if the shield goes?
    • Can anybody reach the origin?