To design a content delivery network (CDN) is to place copies of content in many cities so that users are served from a nearby cache and the origin is asked for as little as possible. A good answer explains how users reach the nearest site, how the caches are organised in tiers, how a new version replaces an old one, what makes two requests count as the same object, and what happens when the origin goes down.
This lesson designs the CDN for ScholarPath, a scholarship portal that serves a results page, scripts, images, scanned documents and recorded lectures to students all over India from one origin in Hyderabad. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: a shield tier between edges and origin, replacing old versions, the cache key, large files, an origin outage, and choosing a server inside a site. All capacities and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.
Key takeaways
20 edge servers alone left 80.68 of every 100 requests going to the origin. One shield cache in front of the origin cut that to 14.38 per 100, which is 322,728 origin requests down to 57,544.
Waiting for a 1 hour lifetime left 91.85% of requests on the old version after 10 minutes. Purging took 104 seconds to reach 99% when 2 of 20 edges missed it. Versioned file names took 59 seconds and had no failure mode.
With the cache key as sent, the hit rate was 5.2%. After ignoring the cookie and a campaign tag, sorting query parameters and grouping Accept-Encoding values it was 94.4%, and 94,706 stored copies became 5,595.
Fetching whole 200 MB lecture files on a miss moved 900.7 GB, of which 300.0 GB was never watched. 4 MB chunks moved 600.7 GB but needed 153,792 origin fetches. Fetching 2 chunks ahead moved 609.7 GB with 52,824 fetches.
During a 120 second origin outage, strict expiry answered 18.8% of requests. Serving stale pages on error answered 99.9%. Limiting retries cut asks to the dead origin from 194,737 to 37,117.
Inside a site, choosing the server by object name raised the hit rate from 35.1% to 73.5% but put 275.3% of an even share on one server. Letting the 20 hottest objects go to any server kept 72.3% and brought the busiest server to 104.5%.
1. Clarifying Requirements
Functional requirements
Serve static content (pages, scripts, images, documents, videos) from sites near the user.
Fetch content from the origin on a miss and keep a copy.
Replace an old version of content with a new one on request.
Let the origin control caching with standard HTTP headers.
Non-functional requirements
Low latency for users everywhere, which means a hit at a nearby site.
The origin must survive results day: it cannot see more than a small share of the traffic.
Users still get pages when the origin is down.
Changes reach users quickly and predictably.
Say what you leave out: personalised pages (they must not be cached for others), dynamic APIs that cannot be cached, and web application firewall rules.
2. Back-of-the-Envelope Estimation
Traffic: 60,000 requests per second at the peak, with an average response of 400 KB. That is 24 GB per second, or 192 Gbit per second.
Origin: we assume the origin has a 2 Gbit per second link. It can serve at most about 1% of the bytes, so at least 99% must come from caches.
Sites: 20 sites in different cities share the load, about 9.6 Gbit per second each if traffic is even. Real traffic follows the population, so big cities need more.
A CDN is a cache whose job is to keep the origin small.
3. Core APIs
Users need no special API: they fetch ordinary URLs, and the CDN answers. The origin and the operators use control interfaces.
Origin response headers (the main control):
Cache-Controlwithmax-age,stale-while-revalidateandstale-if-error;Vary;ETagorLast-Modifiedfor revalidation.POST /v1/purgewith a list of URLs or a tag, for example{"urls": ["/results/2026.html"]}. The reply is202with a purge id.GET /v1/purge/{id}returns how many sites have confirmed the purge.PUT /v1/rules/{path}sets caching rules for a path pattern, the cache key (which parameters and headers count) and the origin to use.
4. High-Level Design
A request first has to reach a nearby site. DNS can answer with the address of the nearest site (see DNS Load Balancing), or the same address can be announced from every site so the network delivers the request to the closest one (see Anycast Routing). Inside the site, a load balancer hands the request to one of its cache servers.
Reach a nearby site first; then choose a server.
A cache server that misses does not go straight to the origin. It asks a shield, a cache tier that sits in front of the origin, and only the shield asks the origin. If several requests for the same object arrive while the fetch is running, they wait for that one fetch (the same request collapsing described in Design API Gateway).
Hit at the edge, miss to the shield, then the origin once.
Three tiers keep the origin small.
5. The Shield Tier
An edge in a small city sees a thin slice of the traffic. Most of the long tail of objects is requested only a few times there, so the edge keeps missing. Without a shield, each of those misses is a request to the origin. A shield pools the misses from many edges, so an object that is rare at each edge may be common at the shield.
The first program has 50,000 objects (a few very popular, a long tail), 20 edge servers that keep 2,000 objects each, and 400,000 requests, each arriving at a random city. It compares edges alone, 4 regional shields (5 edges each, 10,000 objects each), and one shield for all edges (20,000 objects).
Output
50000 objects, 20 edge servers with room for 2000 each, 400000 requests (a few objects are far more popular).
setup edge hits shield hits origin requests origin requests
(of edge misses) per 100 requests in total
edge only 19.3% - 80.68 322728
4 regional shields 19.3% 52.0% 38.66 154671
1 global shield 19.3% 82.1% 14.38 57544
The edge hit rate was 19.3% in all three cases, because the edges are the same. The long tail does not fit in 2,000 objects.
With edges alone, 80.68 of every 100 requests went to the origin (322,728 in total).
4 regional shields caught 52.0% of the edge misses. The origin saw 38.66 per 100 (154,671).
One shield caught 82.1% and the origin saw 14.38 per 100 (57,544), a drop of 82% from edges alone. It has the largest cache and sees all misses, so it holds the most useful objects.
The shield turns many thin streams of misses into one.
The cost: every edge miss takes one more hop, and one shield is one more thing that can fail or become a bottleneck (real CDNs use several shield sites and let an edge choose the nearest). The shield sizes here are assumptions: the 4 regional shields hold 40,000 objects in total and the single shield only 20,000. The single shield wins because it sees every miss, so an object is fetched from the origin once for all 20 edges, not because it is bigger.
6. Replacing Old Content
When you release a new version of a script, every edge may still hold the old one. There are three ways to get users onto the new version.
Wait for the lifetime to run out. Simple, and slow.
Purge. Tell the CDN to delete a URL. Fast when it works, but the purge has to reach every site, and it can fail for one of them.
Versioned file names. The new script has a new name (for example
app.7f3a9c.js), and the page that refers to it has a short lifetime. Nothing has to be deleted, because the old file is never asked for again.
The second program releases new versions of 200 files at second 0. Every one of 20 edge servers holds an old copy of each, with a random time left of up to 1 hour. It sends 2,000 requests per second for 10 minutes. A purge reaches each edge 1 to 30 seconds after it is sent, and (a stress assumption) one edge in 5 misses it and is retried 60 to 119 seconds later. With versioned names, an edge switches when its copy of the page (cached 60 seconds) expires.
Output
New version of 200 files released at second 0; 20 edge servers; 2000 requests a second for 600 s.
how the old version is removed requests that 99% of requests origin fetches origin fetches in edges that
got the old one are new after the busiest second missed the purge
wait for the 1 hour lifetime 91.85% not in 10 min 676 5 -
purge by URL 3.80% 104 s 4000 270 2
versioned file names 5.58% 59 s 4000 257 -
Waiting: 91.85% of requests in the 10 minutes still got the old version, and the share on the old version never fell below 1% within those 10 minutes.
Purge: 3.80% got the old version and 99% were new after 104 seconds. 2 of the 20 edges missed the purge, which is what stretched the time. When no edge missed it (an earlier run with a lower failure rate), 99% were new after 28 seconds.
Versioned names: 5.58% got the old version and 99% were new after 59 seconds, which is the page's lifetime. There was nothing to miss.
Both purge and versioned names caused 4,000 origin fetches (20 sites times 200 files), with 270 and 257 in the busiest second.
Purge is faster when it works; versioned names cannot fail to arrive.
Use versioned names for anything referenced from a page (scripts, styles, images) and a long lifetime with them. Keep purge for content that must keep its address, and check that it was confirmed everywhere. Do not rely on it as the only mechanism.
7. The Cache Key
A cache serves a request from a stored object only if the request has the same cache key. By default the key is the full URL, plus any header named in Vary. Many requests for the same page differ only in things that do not change the content: a campaign tag in the query string, the order of parameters, a cookie, or the exact wording of the Accept-Encoding header.
The third program makes 100,000 requests for 2,000 pages. 60% carry a campaign tag (40 different tags), 30% list the query parameters in the reverse order, each carries one of 6 different Accept-Encoding values, and 70% carry a session cookie (5,000 sessions). The edge keeps everything it fetches, so a hit means the same key was seen before. Each row removes one more useless difference from the key.
Output
100000 requests for 2000 pages. Each row removes one more useless difference from the cache key.
cache key hit rate copies stored origin fetches
URL + headers + cookie as sent 5.2% 94706 94706
ignore the cookie 31.4% 68532 68532
also ignore the campaign tag 82.0% 17904 17904
also sort the query parameters 89.6% 10354 10354
also group Accept-Encoding 94.4% 5595 5595
With the key as sent the hit rate was 5.2% and 94,706 copies were stored. Nearly every request had its own key.
Ignoring the cookie gave 31.4%. Ignoring the campaign tag as well gave 82.0%.
Sorting the query parameters gave 89.6%. Grouping the 6 encodings into 3 (Brotli, gzip, none) gave 94.4%, with 5,595 copies stored.
Fewer useless differences, more hits.
Normalising the key is safe only for content that is the same for everyone. Never drop a cookie from the key for a page that changes with the logged-in user: keep personal content out of the shared cache (section 11). Check the grouping too: a tracking parameter that is ignored for caching must still reach the origin if analytics needs it.
8. Large Files
A 200 MB lecture is different from a 50 KB page. Many viewers stop after a minute, and a viewer can seek to any point. Fetching the whole file on the first miss wastes origin bandwidth, and making the first viewer wait for the whole file is worse. HTTP range requests allow a cache to fetch and store pieces.
The fourth program has 300 videos of 200 MB (50 chunks of 4 MB), 20 edge servers and 20,000 views. 40% of viewers stop within the first 1 to 5 chunks, 40% watch 6 to 30 and 20% watch all 50. It compares fetching the whole file on a miss, fetching 4 MB chunks as viewers reach them, and fetching chunks plus the next 2 ahead.
Output
20000 views of 300 lecture videos (200 MB each, 50 chunks of 4 MB) at 20 edge servers.
how the edge fills origin data never watched chunk hit fetches from
but fetched rate the origin
whole file on a miss 900.7 GB 300.0 GB 98.7% 4612
4 MB chunks on demand 600.7 GB 0.0 GB 58.2% 153792
chunks + fetch 2 ahead 609.7 GB 8.9 GB 85.6% 52824
Whole file on a miss: 900.7 GB moved from the origin, of which 300.0 GB was never watched. The chunk hit rate was 98.7%, because one miss filled the whole file. This flatters the policy: it hides the wait for the first byte, which the program does not measure.
Chunks on demand: 600.7 GB with no waste, but only 58.2% chunk hits and 153,792 separate origin fetches. Each viewer stalls at every chunk boundary that is not yet cached.
Chunks plus 2 ahead: 609.7 GB (8.9 GB never watched), 85.6% chunk hits and 52,824 fetches. It costs a little extra data and removes most of the stalls.
Chunks save bytes; reading ahead saves stalls.
The right chunk size and read-ahead depend on the content: video players already request in segments, and a larger chunk means fewer requests and more waste. Measure how far viewers actually watch before choosing.
9. When the Origin Is Down
A CDN can keep a site up while its origin is down, but only if it is allowed to serve content that is past its lifetime. The HTTP header stale-if-error says how long an expired copy may be used when the origin fails. A second risk is the edge itself: while the origin is failing, every request for an expired page asks it again, which keeps a struggling origin busy.
The fifth program has one edge, 3,000 pages (a few much more popular), 2,000 requests per second for 300 seconds, and pages that stay fresh for 60 seconds. The origin is down from second 100 to 220 and we count those 120 seconds. It compares no stale content, serving pages up to 10 minutes old when the origin fails, and the same with at most one ask to the origin per page every 5 seconds.
Output
1 edge, 3000 pages, 2000 requests a second for 300 s. Pages stay fresh 60 s. The origin is down from second 100 to 220.
Only the 120 s of the outage are counted below.
setup requests errors asks to the oldest page
answered down origin served
no stale content 18.8% 194737 194737 -
stale-if-error 10 min 99.9% 43 194737 213 s
stale-if-error + 1 attempt per 5 s 99.9% 43 37117 213 s
With no stale content only 18.8% of requests were answered, the pages that were still fresh. 194,737 requests were errors, and each asked the origin.
With stale-if-error 99.9% were answered. The 43 errors were pages never fetched before the outage. The oldest page served was 213 seconds old.
The edge still made 194,737 asks to the dead origin. Limiting it to one ask per page every 5 seconds cut that to 37,117, with the same 99.9%.
Stale content keeps users served; fewer retries help the origin recover.
Only serve stale content for pages where a slightly old version is harmful less than an error. A results page from 3 minutes ago is fine. A page showing a live seat count might not be. Also warm the cache for important pages before an event, because an object that was never cached cannot be served from the cache.
10. Choosing a Server Inside a Site
A site has several cache servers. The load balancer can send each request to any of them, or it can choose the server from the object name so that each object lives on one server. The first copies the popular objects onto every server and wastes memory. The second stores each object once and can overload the server that owns a very popular object.
The sixth program has one site with 8 servers that keep 500 objects each (4,000 in all), 20,000 objects and 200,000 requests. 25% of all requests ask for one object (the page announcing the toppers). It compares a random server, the server chosen by a hash of the object name, and the hash with an exception: the 20 most popular objects may be served by any server.
Output
One site with 8 servers (room for 500 objects each, 4000 in all), 20000 objects, 200000 requests.
how a server is picked hit rate different busiest server, requests to the
objects held % of an even share next tier per 100
random server 35.1% 2868 100.9% 64.87
server chosen by object name 73.5% 4000 275.3% 26.49
by name, hottest 20 on any server 72.3% 3899 104.5% 27.64
Random server: a 35.1% hit rate. The servers held only 2,868 different objects between them, because the same popular objects were stored on all 8. 64.87 per 100 requests went to the next tier.
By object name: a 73.5% hit rate and 4,000 different objects. But the server that owned the viral object received 275.3% of an even share of the load.
By name, with the 20 hottest on any server: 72.3% and 3,899 different objects, and the busiest server was at 104.5% of an even share.
Store each object once, but spread the hottest.
An earlier run without the viral object showed no benefit from the exception, so the rule matters when traffic is concentrated. Use the hash for the long tail, and a load or popularity signal to spread the few objects that are hot.
11. What to Cache, and for How Long
The origin controls caching through headers. A file whose name includes a version can be cached for a year and marked immutable. A page that changes gets a short lifetime, with stale-while-revalidate (serve the old copy while one request refreshes it) and stale-if-error. Anything personal, such as an account page or a response that depends on a cookie, must be marked private or no-store so the CDN never shares it. See RFC 9111 (HTTP Caching) and RFC 5861 for the exact rules.
The origin decides what is safe to share.
12. Choosing the Design
Start from how the content changes.
| Content | Strategy | Watch for |
|---|---|---|
| Scripts, styles, images referenced by a page | Versioned names, long lifetime | The page that names them must be fresh |
| Pages that change sometimes | Short lifetime, serve stale while refreshing, purge as a backstop | Confirm the purge everywhere |
| Large files and video | Chunks with read-ahead | Chunk size from real watch patterns |
| Long tail across many sites | Shield tier | The shield is a bottleneck if it is a single site |
| Personal or per-user responses | Do not cache at the edge | A cookie in the key is not enough protection |
13. Trade-offs to Mention
A shield raises the hit rate for the long tail, adds a hop for misses and one more tier to run.
Long lifetimes save origin load and delay changes; versioned names give both.
A normalised cache key raises hits and risks serving the wrong variant if a header that matters is ignored.
Chunking saves bytes and adds requests; read-ahead trades a little extra data for fewer stalls.
Serving stale content keeps users served and shows older data.
Hashing objects to servers saves memory and creates hot servers.
14. Common Mistakes
Caching personalised pages in a shared cache.
Relying on purge alone to publish a change.
Leaving tracking parameters and cookies in the cache key.
Giving everything the same short lifetime, so the origin sees every request.
No stale-if-error, so an origin outage becomes a full outage.
Fetching a whole large file for a viewer who watches the first minute.
Letting every edge retry a dead origin on every request.
15. Interview Questions
How does a user reach the nearest site? DNS that answers by location, or anycast, with health checks to shift traffic when a site fails.
Why add a shield? It collects the misses of many edges so the origin sees each object about once.
How do you ship a new version of a script? Give it a new name and publish the page that links to it with a short lifetime. Purge is the fallback.
Why is the hit rate low even with a big cache? The cache key may include things that vary without changing the content: cookies, tracking parameters, header text.
How do you serve large videos? Range requests and chunking, with a little read-ahead.
What happens when the origin dies? Serve stale on error, and limit how often the edge asks the origin.
Summary
A CDN is sized by the share of bytes that must not reach the origin.
Route users to a nearby site, then choose a server by object name, spreading the hottest objects.
Put a shield between the edges and the origin.
Use versioned names; keep purge for what cannot be renamed.
Normalise the cache key for public content only.
Cache large files in chunks with a little read-ahead.
Serve stale on error and cap retries to a failing origin.
Conclusion
A CDN looks like a cache, and most of its design is about the corners: the long tail, the cache key, how a new version replaces an old one, big files and a failing origin. The design above handles each with a mechanism and a measured result. In an interview, say how much traffic the origin can take, then show how each choice keeps it under that limit.
Previous topic: Design Distributed Cache. Next topic: Design Object Storage like S3.
References and further reading
RFC 9111, HTTP Caching; RFC 5861, HTTP Cache-Control Extensions for Stale Content; RFC 8246, HTTP Immutable Responses; RFC 9110, HTTP Semantics (range requests).
Nygren, Sitaraman and Sun, The Akamai Network: A Platform for High-Performance Internet Applications (2010).
DNS Load Balancing, Anycast Routing, Design Distributed Cache and Design API Gateway on this site.