Design a Content Delivery Network (CDN)
hard 45 minBuild the service that other websites use to answer their visitors from nearby.
See it run
A hit, a miss, a purge, a key, a route, a film and a flood, one step at a time.
Operations
Cache hit
The visitor is answered by the PoP nearby.
Step 1 of 7
Ask for the name
query
cdn.example.com
The browser needs an address for cdn.example.com.
Step 1: Ask for the name
def serve(req): rules.check(req) k = cache_key(req) e = ram.get(k) or ssd.get(k) if e and e.age() < e.ttl and not purged(e): return 200, e.body, {"Age": e.age()} return miss(req, k)- Time
- about 15 ms
- Load
- origin: none
- Share of requests
- 90% assumed
A first visit also pays for DNS and the TLS handshake. Returning visitors reuse both.
In the real world
The same content delivery network doing real jobs. Pick one and step through it.
Tokyo loses power.
Step 1 of 4
Before
Visitors go to Tokyo.
Step 1: Before
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Keep personal pages under a shared key
criticalThe next visitor gets someone else's account.
WrongCache-Control: public, max-age=600RightCache-Control: private, no-storeStore a miss that a purge overtook
criticalThe old answer arrives after the purge and lives for its complete TTL.
Wrongstore(k, res)Rightif log_position_at_start >= purged_at(tags): store(k, res)Drop every query parameter
majorVersions and sizes disappear, and people get the wrong file.
Wrongkey = host + pathRightkey = host + path + kept_params + encodingReport success after most places
majorThe missing place still serves the old copy.
Wrongif acks > 150: return 200Rightreturn 202, status_urlLeave the origin open
criticalAn attacker who knows its address goes around all filters.
Wrongorigin: allow allRightorigin: client certificate of the CDN only
Interview tips
Lead with numbers
- 50M a second is 40 Tb/s.
- Network binds, not CPU.
- 2% reaches origins.
Follow one request
- Name, route, TLS, rules, key.
- RAM, SSD, owner, shield, origin.
- Say what is joined where.
Make purge honest
- An ordered log.
- Replay before serving.
- 202 and a status.
Separate the planes
- Serve with local settings.
- Roll rules out in stages.
- Keep an emergency path.