InterviewDryRun
Lesson 29 · 23 min video · free

Design a CDN

A content delivery network keeps copies of many websites' files in hundreds of locations around the world, so every user gets them from a few milliseconds away. The interview tests whether you can route users to the right place, keep the hit ratio high, protect the origin from floods, and remove changed files everywhere in seconds. This lesson walks through the whole 45-minute answer.

What you will learn

  • Design for pull from the origin, with per-customer rules, fast purge and a hit ratio target of ninety-five percent or more.
  • Put regional shields between the edges and the origin, so a miss in three hundred places becomes one origin request.
  • Know both ways to route users: DNS routing gives control, anycast gives simplicity and absorbs attacks.
  • Choose cache keys carefully, collapse concurrent misses into one fetch, and serve stale copies when the origin fails.
  • Run purge through a durable log to every location, and use tags and version numbers for anything bigger than one URL.
  • Roll out configuration slowly, location by location, because a bad config is what takes a whole CDN down.

In this lesson

  1. The question
  2. Step 1: Clarify the requirements
  3. Step 2: Back-of-the-envelope estimates
  4. Step 3: The interface
  5. Step 4: High-level design
  6. Step 5: Sending users to the nearest location
  7. Step 6: Caching well at the edge
  8. Step 7: Removing content quickly
  9. Step 8: Scaling and failures
  10. Step 9: The parts people forget
  11. Step 10: The follow-up questions
  12. Recap
Practice this question with Max

The question

Welcome to lesson twenty-nine of the InterviewDryRun system design course. Today we are designing a content delivery network, usually called a CDN: a worldwide network of servers that keeps copies of a website's files close to the people who want them.

Almost every page you open is served this way. The images, the scripts, the fonts and the video segments come from a machine a few milliseconds away, not from the company's own servers on the other side of the world. That is the difference between a page that appears instantly and one that crawls in over two seconds.

Max asks

“Design a content delivery network that serves static files and video for many customer websites from servers around the world.”

That is how Max, our AI interviewer, asks it. Listen to the two words that matter: many customers, and around the world. We are not adding a cache in front of one website. We are building a shared platform, with hundreds of locations, that thousands of websites send their traffic through. That changes almost every decision.

Here is the plan. We will clarify the requirements, size the problem, and define how a customer uses the network. Then we will draw the high-level design, and spend most of our time on the three hard parts: sending each user to the right location, caching well at the edge, and removing content quickly when it changes. We will finish with failures, the parts people forget, and Max's follow-up questions.

Step 1: Clarify the requirements

Functional requirements
  1. 01
    Serve cached filesImages, scripts, fonts and downloads from the nearest location
  2. 02
    Stream videoSmall segments, and byte ranges of large files
  3. 03
    Pull from the originFetch on a miss, keep a copy for next time
  4. 04
    Purge on demandRemove a file everywhere within seconds
  5. 05
    Per-customer rulesCache times, custom domains and certificates

As always, start with questions, not boxes. The first one is: what are we serving? Static files, like images, scripts and style sheets, are the classic case. They are the same for every user and change rarely, which makes them easy to cache.

Then ask about video, because it is most of the bytes on the internet. Video is cut into small segments of a few seconds each, and players ask for them one after another. Large downloads are fetched in byte ranges, so a user can pause and resume. Both must work.

Next, how does content get into the network? There are two models. In push, the customer uploads files to us ahead of time. In pull, we fetch a file from the customer's own server, which we call the origin, the first time someone asks for it, and keep a copy. Pull is the common default, because the customer changes nothing about how they publish. We will design for pull.

Ask how quickly a change must show up. If a customer fixes a typo on an image, or a news site takes down a story, waiting a day for the cache to expire is not acceptable. So we need a purge: an instruction to remove a file from every location in the world, quickly.

And finally, because many customers share the platform, each one needs its own rules: how long to keep files, which paths never to cache, their own domain name, and their own TLS certificate so the padlock in the browser shows their name, not ours.

Non-functional requirements
  1. 01
    Low latencyFirst byte in tens of milliseconds for a cached file
  2. 02
    High hit ratioNinety-five percent or more served without the origin
  3. 03
    Always upA location failing must not take a website down
  4. 04
    Huge throughputHundreds of terabits a second at peak
  5. 05
    Protect the originAbsorb floods and sudden spikes for the customer

Now the qualities. The first is latency. The whole product is speed, so the first byte of a cached file should reach the user in a few tens of milliseconds, from a location a short network distance away.

The second is the hit ratio: the share of requests we answer from our own copy without going back to the origin. This is the number customers judge us by, because every miss is slower for the user and costs the customer bandwidth. A good target is ninety-five percent or higher for static files.

Availability matters in a particular way. Customers put us in front of their whole website, so if we go down, they go down. Any single location, or even a whole region, must be able to fail without users noticing more than a short pause.

And the last two are what make this a planet-scale problem. The total traffic is enormous, measured in terabits a second. And a big part of our job is protecting the origin, from a flood of attack traffic and from a sudden rush, like a product launch, where a million people ask for the same new file in the same second.

Step 2: Back-of-the-envelope estimates

Rough numbers
Peak requests50 M / sworldwide, across all customers
Average response100 KBimages small, video segments larger
Peak egress≈ 40 Tbit / s50 M × 100 KB × 8 bits
Locations≈ 300each a few hundred servers
Per server≈ 40 Gbit / snetwork card is the limit, not the CPU
Origin traffic≈ 5% of requestsat a 95% hit ratio

Let us size it. Assume a large network serving many customers: around fifty million requests a second at peak, worldwide. That is a big number, but it is spread over hundreds of locations, which is the whole point of the design.

Responses vary a lot. A small icon is a few kilobytes; a video segment is a few megabytes. Call the average a hundred kilobytes. Fifty million requests a second, times a hundred kilobytes, times eight bits, is about forty terabits a second leaving the network at peak.

Spread across about three hundred locations, that is well over a hundred gigabits a second each, and much more in the busiest cities. A single modern server with a fast network card can push around forty gigabits a second, so a big location needs dozens to hundreds of servers. Say out loud that the bottleneck is the network card and the disk, not the processor.

And the most useful number: with a ninety-five percent hit ratio, only one request in twenty goes back to an origin. Across fifty million a second that is still two and a half million origin fetches a second, spread over all our customers. Every point we add to the hit ratio removes half a million of those. That is why we will spend so long on caching.

Storage is the other side. A location cannot hold every file of every customer; the full set is many petabytes. But a small part of the content gets most of the requests, so a location with a few hundred terabytes of fast disk and a few terabytes of memory holds the popular files, and that is enough for a high hit ratio.

Step 3: The interface

Two interfaces
# Data plane: what browsers send
GET https://static.shop.example/img/hero.webp
  → 200, Cache-Control: max-age=86400, Age: 312

# Control plane: what customers call
PUT  /v1/sites/{site}/config   { origin, rules[], certificate }
POST /v1/sites/{site}/purge    { urls[] | tags[] | prefix }
  → 202 { purgeId }
GET  /v1/purges/{purgeId}      → { status, locationsDone }

A CDN has two interfaces, and naming both is a good sign. The first is the one users hit without knowing: an ordinary web request for a file. The customer points a name, like static dot shop dot example, at us, and every browser request for that name arrives at one of our edge servers.

The response carries the usual caching headers. Cache control tells the browser and our servers how long the file may be kept. And an Age header says how long our copy has been sitting in the cache, which is very handy when a customer asks why they are still seeing an old file.

The second interface is the control plane, which customers call to set up and manage their site. They give us the origin address, their caching rules, and their certificate. And they call purge, with a list of URLs, a tag, or a path prefix. Purge returns an id straight away, because reaching three hundred locations takes a few seconds, and the customer can poll it to see when every location has confirmed.

Step 4: High-level design

High-level design
where?requestmissmissconfigCLIENTUsersbrowsers, playersSERVICERoutingDNS or anycastEDGEEdge locationnearest, many serversCACHERegional shieldbig cache per regionSERVICECustomer origintheir own serversSTOREControl planeconfig, purges, certs

Now the picture. On the left, users all over the world. Their first step is not to fetch the file; it is to find out where to fetch it from. That is the routing layer, which we will look at in detail next.

Routing sends the user to an edge location: a building, usually inside an internet exchange or a large network provider, with many cache servers. This is where nearly every request ends. If the edge has the file, it answers straight away, and the origin never hears about it.

On a miss, the edge does not go straight to the origin. It asks a regional shield: a bigger cache, one or two per continent, that sits between all the edges in that region and the origin. Without it, three hundred edges could each miss on the same new file and send three hundred requests to the customer's server. With it, the origin sees one.

Only if the shield misses too does a request reach the customer's origin. The shield keeps the copy, the edge keeps a copy, and the next user in that region gets it from the edge. This layered design is called tiered caching, and it is one of the main ways a CDN pushes its hit ratio from the eighties into the high nineties.

Finally, the control plane. It stores every customer's configuration, certificates and purge requests, and pushes them out to every location. Notice that it is off the request path. Edges keep a full copy of the configuration they need in memory, so a slow or broken control plane stops changes from going out, but never stops files being served.

Inside each edge location there is one more layer worth a sentence. Traffic arrives at a load balancer, which spreads connections over the cache servers. Each server has memory for the hottest files and fast solid-state disks for the rest. And files are spread over the servers by consistent hashing on the URL, so each file lives on one or two servers in the location rather than being copied onto all of them.

Step 5: Sending users to the nearest location

Two ways to route users
  1. 01
    DNS routingThe name resolves to a different address per region
  2. 02
    AnycastEvery location announces the same address
  3. 03
    Health checksStop sending users to a location that is failing
  4. 04
    Load and costNearest is not always best; busy places shed traffic

The first hard problem: how does a user in Mumbai end up at the Mumbai location and not the one in Frankfurt? There are two standard answers, and interviewers like to hear both, with their trade-offs.

The first is DNS routing. When the browser looks up static dot shop dot example, our name servers answer with the address of a location close to the person asking. We judge closeness from the address of the user's DNS resolver, and from measurements of real latency between networks and our locations.

The weakness is that we only see the resolver, not the user. Someone in Mumbai using a public resolver run from Singapore might be sent to Singapore. There is an extension that passes part of the user's own address to us, which helps. DNS answers are also cached by resolvers, so changing where people go takes as long as the time to live on the answer, typically thirty to sixty seconds.

The second is anycast. Every location announces the same IP address to the internet, and the internet's own routing carries each user's packets to the nearest location in network terms. There is no lookup to get wrong, and if a location disappears, its announcement disappears too, and traffic flows to the next nearest within seconds. That makes anycast excellent at absorbing attacks, because a flood is spread over every location at once.

Its weakness is control. Internet routing picks the shortest path by its own rules, which is not always the fastest, and a route change in the middle of a long download can move a connection to a different location, which breaks it. In practice, large networks use anycast for DNS and for short requests, and many use DNS routing to steer long video sessions more precisely.

Whichever we use, routing must react to health. Every location reports its health and load to a central system. If a location's servers fail, or its links fill up, it withdraws its anycast route or the DNS stops handing out its address, and users go to the next best place.

And nearest is not always best. A location may be close but full during the evening peak, or the network link to it may cost more. So the routing decision mixes distance, measured latency, current load and cost. Saying that out loud shows you know this is a traffic management problem, not just a map lookup.

Step 6: Caching well at the edge

Getting a high hit ratio
  1. 01
    The cache keyHost and path; drop query strings that do not matter
  2. 02
    How long to keepThe origin's headers, or the customer's rules
  3. 03
    What to evictLeast recently used, with a guard for one-off files
  4. 04
    Collapse requestsOne fetch to the origin for many waiting users
  5. 05
    Serve staleKeep answering if the origin is slow or down

Now the heart of a CDN: what the edge does with a request. The first thing it computes is the cache key, the name under which a copy is stored. By default that is the host name and the path. Get the key wrong, and the hit ratio falls apart.

The classic trap is the query string. If a page links to an image with a tracking parameter on the end, every visitor gets a different URL, and every one is a miss. So customers can tell us which parameters change the content and which to ignore. The same goes for headers: if we vary the copy by language or device, each variation is a separate entry, so we keep that list short.

Next, how long to keep a copy. The origin says so with its cache control header: max age one day, or no store for something private. Customers can override it with rules, for example keep everything under slash static for a year. A common pattern is versioned file names, where the build puts a hash in each file name, so a file never changes, can be cached forever, and a new version simply has a new name.

The disk fills up, so we must evict. Least recently used is the usual starting point: throw out the file nobody has asked for in the longest time. But a CDN sees lots of one-hit wonders, files requested once and never again, and they push popular files out. A good refinement is to only write a file to disk on its second request in a short window, which keeps the disk for things that will be asked for again.

Now the thundering herd. A news story breaks, and a hundred thousand people request the same new image within the same second. All of them miss, because the edge does not have it yet. If each miss goes to the origin, we have just aimed a flood at our own customer.

The fix is request collapsing. The first miss for a key starts a fetch, and every other request for the same key waits on that one fetch instead of starting its own. When the file arrives, all of them are answered from it. Combined with the regional shield, a hundred thousand users turn into one request to the origin. Interviewers love this point, so make it clearly.

Finally, serve stale. When a copy has expired, we do not have to throw it away. We can keep serving it for a short while, refreshing it in the background. And if the origin is down or returning errors, we can keep serving the old copy until it comes back. Customers turn this on per site, and it means a broken origin often goes completely unnoticed by users.

For video, add one more detail. Players ask for byte ranges and small segments, so we cache segments as separate objects, and for very large files we cache them in fixed-size chunks, say two megabytes each. A request for any range is then served from the chunks we already have, and only the missing chunks are fetched from the shield.

Step 7: Removing content quickly

Purge fan-out
purgeappendfan outdoneCLIENTCustomerpurge callSERVICEPurge APIrecords the requestQUEUEPurge logordered, durableEDGEEvery locationapply and confirmSTOREStatus storewho has confirmed

A customer uploads a corrected price list, and they need the old one gone everywhere. This is purge, and it is a classic deep dive, because it is a small distributed systems problem hiding inside the CDN.

The purge API checks that the customer owns the site, gives the request an id, and writes it to a purge log: an ordered, durable stream that every location subscribes to. Writing to a log, rather than calling three hundred locations one by one, means a location that was offline for a minute simply catches up from where it left off.

Each location reads the log and applies the purge. For a single URL, it is a delete by cache key on the servers that own that key. Each location then reports back, and the status store tracks how many have confirmed. The customer's poll shows something like two hundred and ninety-eight of three hundred done. A good system gets every location within a few seconds.

Purging by URL does not scale to real needs, though. When a product's price changes, it appears in dozens of files. So we support tags: the origin labels each response with tags, like product one two three, and we keep an index from tag to cache keys in each location. Purging the tag removes every file that carries it.

And there is a clever shortcut for a prefix, or for purge everything. Instead of deleting millions of files, we bump a version number for the site, or for that path, and include it in the cache key. Every old entry instantly becomes unreachable, and the disk reclaims the space through normal eviction. Deleting becomes a single number changing.

Say one more thing: a purge must also clear the shield, and in the right order. If the edge clears first and then refetches from a shield that still has the old copy, the old file comes straight back. So the shields apply the purge first, or the edges ignore any copy older than the purge time. That kind of detail is what separates a strong answer.

Step 8: Scaling and failures

When things break
  1. 01
    A server failsIts keys move to neighbours and refill from the shield
  2. 02
    A location failsRouting sends users to the next nearest one
  3. 03
    The origin failsServe stale copies; errors are cached only briefly
  4. 04
    An attack arrivesAnycast spreads it; filter at the edge
  5. 05
    A bad config shipsRoll out slowly, location by location

Now, what breaks, and what we do about it. Start with a single cache server dying. Consistent hashing moves only its share of the keys to the other servers in the location, those keys miss once, and fill from the shield. Users see nothing.

If a whole location fails, for a power cut or a fibre cut, routing takes over. Anycast routes disappear, or DNS stops pointing there, and users move to the next nearest location. That location sees a sudden rush of misses for files it did not have, which is another reason the regional shield matters: it absorbs that rush instead of the origin.

If the customer's origin fails, serve stale keeps the site up for everything we have already cached. We also cache error responses, but only for a few seconds, so a broken origin is not hammered by every user, yet recovers quickly once it is fixed.

Attacks are part of the job. A flood of junk traffic aimed at one customer is spread across every location by anycast, so no single place is overwhelmed. Each edge filters obviously bad traffic early, in the network card or the kernel, before it costs much. And per-customer rate limits stop one site's attack from hurting its neighbours on the same servers.

And the failure that actually takes CDNs down: a bad configuration change. Because the config reaches every location, one mistake can break every site at once. So every change rolls out slowly: first to a single canary location, then a few percent, then everywhere, with automatic checks on error rates at each step and a fast way to roll back.

Step 9: The parts people forget

Often forgotten
  1. 01
    CertificatesThousands of customers, issued and renewed automatically
  2. 02
    Logs and billingEvery request counted, shipped in batches
  3. 03
    Dynamic contentCannot cache, but fast routes and kept-open connections help
  4. 04
    FairnessOne customer's spike must not evict everyone else

A few things that strong candidates mention and others forget. The first is TLS. Every request is encrypted, so each edge needs the customer's certificate and private key. With thousands of customers, we keep certificates in the control plane, issue and renew them automatically, and push them to the edges, ideally keeping the most sensitive keys in hardware.

Second, logs. Customers want to see their traffic, hit ratio and errors, and we bill by bytes delivered. That is tens of millions of log lines a second. Edges write them locally, compress them, and ship them in batches to a central analytics pipeline. Real-time dashboards use sampled data; billing uses the complete logs, a few minutes later.

Third, dynamic content, like a shopping cart, that cannot be cached at all. A CDN still helps. The edge ends the encrypted connection close to the user, which saves several slow round trips, and then sends the request to the origin over a connection that is already open and warm, along the fastest path through our own network.

And fairness. Many customers share the same servers and disks. If one customer suddenly gets huge traffic for files nobody will ask for twice, they could push everyone else's popular files out of the cache. Limits per customer on disk share, and the second-hit rule for writing to disk, keep one tenant from ruining the hit ratio for the others.

Step 10: The follow-up questions

Max asks

“A customer purges a file, but some users still see the old one for a minute. Why, and what would you do?”

There are three usual causes. The browser has its own copy, which we cannot purge, so long browser cache times should be used only with versioned file names. A location was slow to read the purge log, which the status store will show. Or the shield still had the old copy and an edge refetched it. The fixes are versioned names for anything long-lived, shields purging first, and edges refusing copies older than the purge time.

Max asks

“How would you serve a live sports stream to ten million viewers at once?”

Live video is cut into segments of a couple of seconds, and every viewer asks for the newest segment at almost the same instant. That is the thundering herd, every two seconds. Request collapsing at each edge and shield is essential, so each new segment is fetched from the origin once per region. Short cache times on the playlist, long ones on the segments, and spreading viewers over many servers per location do the rest.

Max asks

“Why not just put every customer's files in every location ahead of time?”

Because the total content is many petabytes, and most of it is rarely requested. Copying all of it everywhere would cost a fortune in disk and bandwidth, for files that might be read once a year in that city. Pulling on demand stores what each region actually uses. Pushing ahead of time does make sense for a small set of files we know will be hot, like a big game update on launch day, so we offer it as a feature, not the default.

Max asks

“How do you decide where to build the next location?”

From data. We look at where our traffic comes from, the latency users there see today, and how much we pay to carry it to the nearest existing location. A city with lots of users, high latency and expensive transit is the best candidate. Often the best site is inside a large local network provider, which is happy to host our servers because it saves them traffic too.

Recap

Your 45 minutes
  1. 01
    0 to 5: requirementsPull, static and video, rules, purge, hit ratio
  2. 02
    5 to 10: estimates40 Tbit/s, 300 locations, origin traffic at 5%
  3. 03
    10 to 20: design and routingEdge, shield, origin; DNS versus anycast
  4. 04
    20 to 35: caching and purgeKeys, eviction, collapsing, stale, tags, versions
  5. 05
    35 to 45: failure and extrasFailover, attacks, slow rollouts, certificates

Let us map it onto forty-five minutes. Five minutes of requirements, ending with pull from origin, static files and video, per-customer rules, fast purge, and a hit ratio target. Five minutes of estimates: about forty terabits a second, three hundred locations, and every point of hit ratio saving the origin a huge amount of traffic.

Then around ten minutes on the design: edges near users, regional shields, the origin behind them, and the control plane off the request path. Explain DNS routing and anycast, and when you would use each.

Fifteen minutes on caching and purge: the cache key and the query string trap, eviction with the second-hit rule, request collapsing for the thundering herd, serving stale, and purge through a log with tags and version numbers. And the last ten minutes on failure: servers, locations and origins failing, attacks spread by anycast, and slow, careful config rollouts. Say the trade-offs out loud at each step, and you have a strong answer.

Knowing the boxes is the easy part. Explaining request collapsing clearly, while someone asks you why a purged file is still showing up, is the part that takes practice. You can practice this exact question with Max, our AI interviewer, at interview dry run dot com. It is free to start, and you get a scored report with what to fix. The written lesson, with every diagram, is on the site too. See you in lesson thirty.

Now say it out loud

Watching an answer is not the same as giving one. Max asks this exact question, pushes back when an answer is vague and keeps time, then scores you per skill.

Practice with Max

Free: a 5-minute voice round and unlimited typed drills, with scored feedback. No card, and your camera is never recorded.