Summary#
A CDN is a global network of caching reverse proxies (edge servers) placed in many cities (PoPs, points of presence). Users are routed to a nearby edge via DNS or anycast; the edge serves cached content or fetches it once from your origin. CDNs cut latency (tens of ms instead of hundreds), offload most bandwidth from your servers, and absorb attacks. You control them with cache keys, TTLs (Cache-Control), invalidation and versioned URLs. They are essential for static assets and video, and increasingly used for APIs and dynamic sites.
Why It Exists#
Distance costs time. A user in Sydney fetching an image from a server in Virginia pays ~200 ms of round-trip time per request, before any bandwidth limits. A web page needing dozens of files becomes slow, and video becomes impossible without buffering.
Bandwidth also costs money and capacity. If a popular video is watched a million times, the origin should not send it a million times. A CDN serves it from caches near viewers, so the origin sends it a handful of times. This page builds on DNS, which is how many CDNs route users to the nearest edge.
How It Works#
Edge PoPs, origin and routing#
- Origin: your servers or object storage (such as Amazon S3) holding the real content.
- Edge PoPs: caches in many locations. Large CDNs have hundreds of PoPs worldwide.
- Routing to the edge: either DNS-based (your domain is a CNAME to the CDN, whose DNS returns a nearby edge IP) or anycast (the same IP is announced from every PoP and the network routes to the closest).
- Tiered caching / origin shield: a mid-tier cache in front of the origin, so a miss in 200 PoPs becomes a single origin fetch.
The cache hit ratio (share of requests served from cache) is the key metric. Well-tuned static content often reaches 90-99%.
Why distance matters, in numbers#
Light in optical fibre covers about 200 km per millisecond, so a round trip from Virginia to Mumbai (about 13,000 km each way along real cable paths) costs well over 130 ms before any processing, and measured round trips are typically 200-300 ms. A new HTTPS connection needs about two round trips (one for TCP, one for TLS 1.3) before the first request, plus one for the request itself. That is three round trips, roughly 750 ms, just to start receiving the first byte of an image from across the world.
From an edge server in the same city, with a 10-20 ms round trip, the same three round trips take 30-60 ms. Multiply that by the dozens of files a page needs, and the difference is between a page that feels instant and one that feels broken. A CDN helps in two ways at once: users get content from somewhere close, and your servers no longer have to answer the requests that the CDN serves.
How users reach the edge, in depth#
A CDN has to get each user to a good PoP. There are two main techniques.
DNS-based mapping. You point a host name at the CDN with a CNAME, for example static.example.com as a CNAME to example.cdnprovider.net. When a resolver asks the CDN's authoritative DNS for that name, the CDN picks a PoP based on where the resolver is (or the client's subnet, if the resolver passes it on through EDNS Client Subnet), how loaded each PoP is and how healthy the network paths are. It then returns IP addresses in that PoP with a short TTL, often 20-60 seconds. Akamai is the classic example: its mapping system constantly measures the internet and updates DNS answers. The weakness is that the CDN sees the resolver, not the user. A user in Chennai using a public resolver whose nearest site is in Singapore may be sent to a Singapore PoP.
Anycast. The CDN announces the same IP prefix from every PoP using BGP. Internet routers send each packet to the "nearest" announcement in routing terms, which is usually, but not always, the geographically closest PoP. Cloudflare is the classic example. Anycast needs no DNS tricks, reacts in seconds when a PoP is withdrawn, and naturally spreads a DDoS attack across every PoP, since each attacker's packets go to whichever PoP is nearest to them. The weaknesses: BGP picks paths by policy and hop count, not by latency, so some users land on a distant PoP, and a route change in the middle of a long TCP connection can move it to a different PoP that knows nothing about it. CDNs handle this with stable routing and by sharing connection state or forwarding packets between machines.
| DNS-based mapping | Anycast | |
|---|---|---|
| How a PoP is picked | CDN's DNS chooses per resolver or client subnet | Internet routing chooses per packet |
| Steering control | Fine-grained: load, health, cost, per customer | Coarse: announce or withdraw prefixes, adjust BGP |
| Failover speed | Bounded by DNS TTL and caching | Seconds, as routes are withdrawn |
| DDoS spreading | Attack goes to the PoPs DNS hands out | Spread across all PoPs automatically |
| Known weakness | Sees the resolver, not the user | Route changes can move long connections |
| Typical users | Akamai, CloudFront (DNS-based), many media CDNs | Cloudflare, Google, Fastly, many DNS providers |
Which URL points at the CDN? There are two common setups. You can serve only static content through a CDN host name (static.example.com or cdn.example.com) and rewrite asset URLs in your HTML to point there, which is the classic setup the primer describes. Or you can put your whole site behind the CDN (www.example.com itself resolves to the CDN), with rules deciding what is cached and what is passed through to the origin. The second is now common because it also gives every request edge TLS, DDoS protection and dynamic acceleration, and nothing needs rewriting.
Inside a PoP#
A PoP is a small data center, from a few racks to several hundred servers, connected to many local networks. A request arriving there typically goes through:
- Routers and an L4 load-balancing layer that spread connections across the PoP's servers (often with ECMP and consistent hashing, as described in Load Balancing).
- An edge proxy that terminates TCP and TLS (and QUIC for HTTP/3), applies WAF and rate-limit rules, runs any edge code, and computes the cache key.
- The cache layer. To avoid every server caching the same objects, many CDNs hash the cache key to choose which server inside the PoP owns that object, a direct use of consistent hashing. The server that received the request either has it in memory or SSD, or fetches it from the owner. Very hot objects are deliberately copied to several servers so that one owner does not become a hot spot.
- On a miss, a request goes to the next tier (a regional or shield cache) or to the origin, over long-lived, warm connections.
Memory and disk tiers. The hottest objects live in RAM (sub-millisecond reads); the warm working set lives on SSD (about 0.1 ms per read); everything else is a miss. A single cache server may hold tens of TB on SSD. The PoP's total capacity, compared with how many distinct objects users ask for, decides its hit ratio.
What to keep: eviction and admission. Caches evict with LRU or variants of it (LRU segmented into "seen once" and "seen again" areas, or frequency-aware policies). Just as important is admission: whether to store an object at all. Many objects on a CDN are requested only once. In "Algorithmic Nuggets in Content Delivery" (SIGCOMM Computer Communication Review, 2015), Bruce Maggs and Ramesh Sitaraman described how Akamai found that about three quarters of objects in a large sample were "one-hit wonders" requested only once, and how caching an object only on its second request (tracked with a Bloom filter) cut disk writes sharply and raised the hit ratio by leaving room for content that would be reused.
Request collapsing. If 500 users ask for the same uncached object within a few milliseconds (a new software release, a breaking-news photo), the PoP sends one request upstream and has the other 499 wait for it. Without this, a single popular miss would multiply into hundreds of origin requests.
Push vs pull CDN#
| Pull CDN | Push CDN | |
|---|---|---|
| How content arrives | Edge fetches from origin on first request, then caches | You upload content to the CDN ahead of time |
| Effort | Low: set headers and point DNS | You manage uploads and deletions |
| First request | Slower (miss goes to origin) | Fast everywhere |
| Storage | Only popular content occupies cache | You pay to store everything pushed |
| Fits | Most websites and APIs, long-tail content | Large files with known demand: game patches, software releases, scheduled video premieres |
Most CDN usage today is pull, often with pre-warming for known big launches.
Push vs pull in depth#
Push CDNs. You are responsible for putting content on the CDN. Whenever something changes, you upload it (directly or by syncing a storage bucket), point your URLs at the CDN, and decide when each object expires or is replaced. Content travels to the CDN only when it is new or changed, so transfer from your side is minimal, but the CDN stores everything you push, whether anyone requests it or not. Push suits sites with modest traffic or content that rarely changes, since each file is placed once instead of being fetched again and again as TTLs expire. It also suits large, predictable releases, where you want every PoP ready before the first user arrives.
Pull CDNs. You leave content on your origin and point URLs at the CDN. The first request for an object at a PoP is a miss: the PoP fetches it from the origin, stores it, and serves it, so that first user waits longer. Later requests are hits until the TTL runs out. Pull minimises storage on the CDN, since only recently requested content stays, and it spreads traffic naturally for high-traffic sites. Its drawback is redundant traffic: when a TTL expires, the PoP fetches the object again even if it has not changed. Conditional revalidation fixes most of this. The PoP sends If-None-Match with the stored ETag, and if nothing changed, the origin replies 304 Not Modified with no body, so only headers cross the network.
The hybrid most teams use. Pull for everything, plus prewarming (asking the CDN to fetch specific URLs in advance) for known big events, and origin failover (a secondary origin, often a second bucket in another region, used when the primary returns errors).
Netflix's Open Connect shows push at its most extreme. Netflix places its own caching appliances inside internet providers' networks and fills them with the titles predicted to be popular in that region during off-peak hours, overnight in local time. When viewers press play in the evening, nearly all bytes come from an appliance a few network hops away, and Netflix's own backbone carries little peak-hour video.
Cache hit ratio and offload, in depth#
Two different ratios matter:
- Request hit ratio: the share of requests answered from cache. It drives latency.
- Byte hit ratio (often called offload): the share of bytes served from cache. It drives origin bandwidth and cost.
They can differ a lot. A site might serve 98% of its large video bytes from cache (high byte hit ratio) while many small API calls miss (lower request hit ratio).
Worked example. A service delivers 1 PB a month through its CDN at a 95% byte hit ratio. The origin sends only 5%, which is 50 TB. Without the CDN, the origin would send the full 1 PB. At cloud internet egress list prices, which have been roughly 5-9 US cents per GB in the main regions at volume tiers, 1 PB is on the order of 50,000-90,000 dollars a month; 50 TB is about a twentieth of that. CDN delivery is billed too, but large committed contracts are priced well below on-demand cloud egress. That is the trade the primer describes: CDN costs can be significant, but they must be weighed against what serving the traffic yourself would cost.
What limits the hit ratio. Request popularity on the web roughly follows a Zipf-like distribution: a few objects get most requests, then there is a very long tail of objects requested rarely. Head content is almost always a hit. Tail content misses unless the cache is large enough to hold it, and every PoP must hold its own copy. That is why big CDNs add tiered caching: a miss at a small PoP goes to a large regional cache first, which holds far more of the tail, and only that regional tier talks to the origin.
What lowers it by mistake. Cache keys that include needless parts (tracking parameters such as utm_source, session cookies, every header), Vary: User-Agent, short TTLs on content that rarely changes, and unversioned assets that force short TTLs. A drop in hit ratio after a deploy is one of the most useful alerts a CDN setup can have.
What to cache#
- Static assets: JavaScript, CSS, fonts, images. Cache for a long time with versioned URLs.
- Media and video: video is split into small segments (HLS/DASH), each cached like a static file. This is the largest share of CDN traffic. See Design a Video Streaming Platform.
- Downloads: software packages, installers, documents.
- API responses that are the same for many users: product catalog, public prices, search suggestions, configuration. Even a 1-5 second TTL ("micro-caching") can absorb huge spikes.
- Not personalised or sensitive responses (account pages, carts) unless the cache key includes the user, which usually defeats the purpose.
Cache keys, TTL, invalidation and versioned URLs#
- Cache key: what makes two requests "the same" for caching. Usually host plus path plus selected query parameters. Add headers (
Accept-Encoding, language) only when the response truly differs. Including unnecessary parts (tracking parameters, every cookie) splits the cache and kills the hit ratio. - TTL: how long the edge keeps a copy, set by
Cache-Control: max-age(browsers) ands-maxage(shared caches like CDNs), or overridden in CDN rules.stale-while-revalidatelets the edge serve a slightly old copy while it refreshes in the background. - Invalidation (purge): tell the CDN to drop cached copies by URL, prefix or tag. Modern CDNs purge globally in seconds, but purges are rate-limited and still race with traffic, so they are a tool for emergencies and content updates, not for every deploy.
- Versioned URLs (cache busting): put a content hash or version in the file name (
app.3f9a1c.js). A new deploy produces a new URL, so you can cache each file "forever" and never purge. This is the preferred approach for static assets.
| Content | Cache-Control | Update strategy |
|---|---|---|
| Hashed JS/CSS/images | public, max-age=31536000, immutable | New file name per version |
| HTML pages | public, s-maxage=60, stale-while-revalidate=300 | Short TTL, or purge on publish |
| Public API (catalog) | public, s-maxage=5 | Micro-cache; purge by tag on change |
| Personal API (cart) | private, no-store | Never cached at the edge |
Invalidation in depth#
"There are only two hard things in computer science: cache invalidation and naming things," as Phil Karlton's well-known quip goes. A CDN makes it harder still, because copies live in hundreds of places and also in users' browsers.
Ways to remove or refresh content.
| Method | What it does | Speed | Good for |
|---|---|---|---|
| TTL expiry | Copies age out on their own | As long as the TTL | Most content |
| Revalidation | Edge asks origin "changed?" with ETag, gets 304 or new body | One origin round trip per PoP | HTML, APIs with short TTLs |
| Purge by URL | Delete specific objects everywhere | Seconds on modern CDNs | Fixing a specific file |
| Purge by tag (surrogate key) | Delete every object labelled with a tag, such as "product-42" | Seconds | A product change that affects many pages |
| Soft purge | Mark objects stale instead of deleting, so they can be served while refreshing | Seconds | Protecting the origin from a refetch spike |
| Purge everything | Empty the cache | Seconds, then a huge origin spike | Emergencies only |
| Versioned URLs | Never invalidate; publish under a new name | Instant for new pages | Static assets |
Versioned URLs are the default for static assets. Build tools put a content hash in the file name (app.3f9a1c.js), HTML refers to the new name after each deploy, and old files can be cached for a year with immutable. Nothing ever needs purging, browser caches are never wrong, and rollbacks are instant because the old files are still there. The only thing that needs a short TTL is the HTML that points at them.
When an update must be visible immediately. Options, from simplest:
- Do not cache it at the edge, or cache it for 1-5 seconds. Simple and often enough.
- Short TTL plus revalidation: the edge checks back with the origin, cheaply, using ETags.
- Event-driven purges: when data changes, the application (or a change-data-capture stream from the database) calls the CDN's purge API with the affected URLs or tags.
- Versioned keys for data: include a version number in the API URL (
/catalog?v=1842) that clients learn from a small, uncached endpoint.
The purge race. Purging is fast, but it can race with reads. If the CDN is purged before a database read replica has caught up, the next miss can fetch the old data from a lagging replica and cache it again for a full TTL. Fixes include purging only after replication catches up (or after a short delay), reading from the primary for cache fills, and purging twice: once immediately and again a few seconds later.
Browsers cannot be purged. Once a browser caches a response for a day, no CDN purge reaches it. Give browsers short TTLs on anything that might change (max-age=0, must-revalidate for HTML) while giving the CDN a longer one with s-maxage, and rely on versioned URLs for long-lived assets.
Caching API responses and HTML at the edge#
Modern CDNs such as Cloudflare, Fastly and Akamai cache far more than files: public API responses, whole HTML pages, and responses produced by code running at the edge. Still, the most common and most valuable use is media. In an interview, the safest moment to introduce a CDN is when the system serves images or video at scale; start with that reason, and add API or edge caching only when the problem needs it.
What makes an API response cacheable at the edge. It must be the same for many users (or for a small, well-defined group, such as everyone in one country with one language), tolerate being a little stale, and be marked as shareable with Cache-Control: public, s-maxage=.... Product catalogues, public prices, sports scores, search suggestions, configuration and feature flags all qualify. Anything tied to one user (account, cart, messages) does not.
Case study: URL shortener redirects at the edge. A URL shortener is almost entirely reads: each short code maps to one long URL, and popular codes are clicked millions of times. Serve the short domain through a CDN and let PoPs cache the mapping, so a popular code's redirect is answered from a city near the user and never reaches the origin. Go further with edge compute (Cloudflare Workers, Lambda@Edge, Fastly Compute): a small function at the PoP looks up the code in an edge key-value store and returns the redirect itself.
The trade-offs: keeping mappings consistent across every PoP when a link is edited or deleted is harder; edge functions have limits on CPU time, memory and available libraries; edge compute and CDN requests cost money at high volume; and debugging code that runs in hundreds of places is harder than debugging one service. The redirect status matters too. A 301 Moved Permanently may be cached by browsers indefinitely, so later clicks never reach you, which saves load but loses click analytics. A 302 Found keeps every click visible. Whether the latency gain is worth the cost and complexity depends on how price-sensitive the company is, what the user experience requires, and the traffic pattern.
Hot content is naturally replicated. A distributed cache sharded by key has a hot-key problem: if a viral post lives on one cache shard, that shard melts while others idle. The news-feed fix is to stop sharding hot data and instead run replicated cache instances that can each serve any post, behind a load balancer, so a viral post's reads spread across all of them. A CDN is this pattern at internet scale: every PoP holds its own copy of popular objects, so a viral image is served by hundreds of PoPs in parallel. The cost of replication is more misses at first (each PoP or replica fetches the object once), which is tiny compared with the load the copies absorb.
Personalised pages from cached parts. A page can be mostly shared (layout, product details) with small personal parts (the user's name, cart count). Options: cache the shared page and fill personal parts in the browser with a small uncached API call; or assemble at the edge, using edge compute or the older Edge Side Includes (ESI) markup to stitch cached fragments with personal ones.
Video delivery through a CDN#
Video is the largest share of CDN traffic. Streaming formats such as HLS and MPEG-DASH split each video into short segments, typically 2-6 seconds, at several quality levels (bitrates), and describe them in a manifest file. The player downloads the manifest, then fetches segments one after another, switching quality as bandwidth changes (adaptive bitrate streaming).
To a CDN this is ideal: each segment is an ordinary, immutable file with its own URL, cached like any static asset. For video on demand, segments are cached for a long time and only the popular head of the catalogue lives on edges. For live streams, segments are created every few seconds, the manifest changes constantly and gets a TTL of about one segment duration, and request collapsing matters enormously, because every viewer asks for the newest segment at the same moment. A popular live event can mean millions of viewers asking for the same 2-second segment within the same second.
Rough sizing: 1 million concurrent viewers at 5 Mbps is 5 Tbps of delivery. No single origin or data center serves that; only a widely distributed CDN, or several, can. See Design a Video Streaming Platform.
Image optimisation at the edge#
Images are often the heaviest part of a web page. CDNs can resize, crop and re-encode images on the fly, so the origin stores one high-quality master and the edge produces the variant each device needs. Format negotiation sends AVIF or WebP to browsers that list them in the Accept header and JPEG to the rest, which can cut image bytes by roughly a quarter to a half. Cache each variant under a key that includes the width and format, and normalise the requested sizes to a small set (for example 320, 640, 1280 pixels), or every odd size creates a new cache entry.
Dynamic site acceleration#
Even uncacheable requests benefit. With dynamic site acceleration, the user connects to a nearby edge (short TCP and TLS handshakes), and the CDN carries the request to the origin over its own optimised, persistent connections and backbone routes. A request that would need several long round trips for handshakes now needs one long round trip, often saving 100 ms or more for distant users.
Dynamic site acceleration in depth#
For requests that cannot be cached (checkout, search with personal results, API writes), a CDN still helps, through several effects that add up:
- Short handshakes. TCP and TLS are set up between the user and a nearby PoP, a 10-20 ms round trip instead of 200 ms.
- Warm connections to the origin. The PoP keeps long-lived, already-open connections to the origin (or to a shield PoP near it), with large congestion windows, so no handshake and no slow start is paid on the long leg.
- Better routes. CDNs measure paths across their own networks and send traffic over the fastest one, which is often not the path the public internet's routing would pick. Akamai's SureRoute and Cloudflare's Argo Smart Routing are examples.
- Modern protocols at the edge. The user gets HTTP/2 or HTTP/3 and modern TLS, even if the origin only speaks HTTP/1.1.
Worked example for a user in Sydney and an origin in Virginia, with a 200 ms round trip:
| Step | Without a CDN | With dynamic acceleration |
|---|---|---|
| TCP handshake | 200 ms | 15 ms (to the Sydney PoP) |
| TLS 1.3 handshake | 200 ms | 15 ms |
| Request to origin and response | 200 ms | 15 ms to the PoP, plus about 190 ms on a warm, well-routed backbone path |
| Total to first byte | About 600 ms | About 235 ms |
The saving grows when connections are new for every visit (mobile apps, first visits) and when the public internet's path is congested or roundabout.
Security benefits#
- DDoS absorption: attack traffic is spread across hundreds of PoPs with huge total capacity, far more than your origin could take.
- WAF (web application firewall): rules at the edge block common attacks (SQL injection, bad bots) before they reach you.
- Origin hiding: only the CDN talks to the origin; firewall the origin so it accepts only CDN traffic.
- TLS at the edge, bot management and rate limiting near the attacker.
Security benefits in depth#
DDoS absorption. A large CDN has a total network capacity measured in hundreds of terabits per second, spread over hundreds of PoPs. A volumetric attack of a few terabits per second, which would flatten any single origin, is split across many PoPs and dropped near its sources. Attacks at the protocol layer (SYN floods) are handled by edge TCP stacks with SYN cookies, and attacks at the application layer (floods of valid-looking HTTP requests) by rate limits, bot detection and challenges at the edge.
WAF at the edge. Managed rule sets block common attack patterns such as SQL injection, cross-site scripting and known exploit payloads, and can be updated within hours when a new vulnerability is disclosed. Blocking at the edge means attack traffic never uses origin capacity.
Locking down the origin. A CDN only protects you if attackers cannot go around it. Ways to make the origin reachable only through the CDN:
- Allow only the CDN's published IP ranges in the origin's firewall.
- Authenticated origin pulls: the CDN presents a client certificate (mTLS) that the origin checks.
- A secret header added by the CDN and checked by the origin (weaker, but simple).
- Private connectivity: an outbound-only tunnel from the origin to the CDN (such as Cloudflare Tunnel), or CloudFront's Origin Access Control, so an S3 bucket can only be read through CloudFront.
Signed URLs and cookies let the edge enforce access to paid or private content (a course video, a private download) without asking the origin: the origin signs a URL or cookie with an expiry time, and the edge checks the signature.
TLS at the edge. The CDN manages and renews certificates for your domains, supports the latest protocol versions, and absorbs the CPU cost of handshakes. For organisations that cannot hand their private keys to a third party, some CDNs offer modes where the key stays on the customer's server and only the signing step is done remotely, such as Cloudflare's Keyless SSL.
Costs and downsides#
- Cost: CDNs charge per GB delivered and per request; at video scale, CDN egress is one of the largest bills. Price per GB drops with volume and commitments.
- Stale content: wrong TTLs can show outdated pages or prices.
- Complexity of cache rules: mistakes can leak personal data if a personal response is cached publicly.
- Debugging: problems may affect only some PoPs or regions.
- Vendor dependency: a CDN outage can take your site down; critical services use multi-CDN setups.
Costs and downsides in depth#
Pricing. CDNs usually charge per GB delivered (with higher prices in regions such as South America, Africa and parts of Asia, where bandwidth costs more), per 10,000 or per million requests, and for extra features such as WAF rules, image processing, edge compute and log streaming. Large customers sign committed-volume contracts at much lower prices than the published rates. Small sites often pay nothing at all on free tiers.
Stale content. Content can be out of date if it changes before its TTL expires. This is the primer's second listed drawback, handled with versioned URLs, short TTLs for changing content, revalidation and purges.
URL changes. Moving static content to a CDN host name means changing the URLs your pages use. Build tools and frameworks usually handle this with an "asset prefix" setting, or the whole domain moves behind the CDN.
Outages at the CDN. A CDN becomes part of your critical path. Some public incidents show the scale of the risk:
- On 2 July 2019 a WAF rule containing a badly behaved regular expression exhausted CPU across Cloudflare's network, causing errors for many sites for about half an hour.
- On 8 June 2021 a valid configuration change by one Fastly customer triggered a latent bug that caused errors across most of Fastly's network for under an hour, taking down many major news and government sites.
- On 22 July 2021 an Akamai Edge DNS configuration problem briefly made many large websites unreachable.
The lessons: CDN configuration changes are among the riskiest changes on the internet, so they need staged rollouts; and very large or critical services use multi-CDN setups, steering traffic between providers by DNS based on real-user measurements of performance, availability and cost.
Data location and privacy. A CDN may cache content in any of its PoPs. If regulations require that certain data stays in a region, use regional PoP restrictions, or do not cache that data at the edge at all.
A complete CDN setup, end to end#
Putting the pieces together, here is how a typical global web product places its CDN. Media and static assets live in object storage; HTML and APIs come from application servers in one or two regions; the CDN sits in front of both, with a shield tier in the middle.
A worked cache policy for an online shop:
| Content | Cache-Control sent by origin | Cache key | Why |
|---|---|---|---|
| JS, CSS, fonts with content hash in the name | public, max-age=31536000, immutable | Path | Never changes at this URL |
| Product images | public, max-age=31536000 | Path, width, format class | New upload means new URL |
| Home page HTML | public, s-maxage=60, stale-while-revalidate=30 | Path, country, language | Same for everyone in a market |
| Product page HTML | public, s-maxage=300 plus tag purge on price change | Path, country | Prices must update within seconds of a change |
| Stock level API | public, s-maxage=5 | Path, product ID | Brief staleness is fine, absorbs flash-sale spikes |
| Cart, account, checkout | private, no-store | Not cached | Personal data |
Two observations. First, the most important column is "why": every TTL is a business decision about how stale each piece of content may be. Second, the price-sensitive product page uses a fairly long TTL together with a targeted purge. This gives a high hit ratio most of the time and fast updates when it matters, which neither a short TTL nor a long TTL alone can achieve.
Multi-CDN in practice#
Using two or more CDNs protects against provider outages and gives pricing leverage, but it changes how the system is run.
Practical points:
- Configuration parity. Cache rules, headers, redirects and security rules must behave the same on every CDN. Keep them in version control and generate each provider's configuration from one source, or the same URL will behave differently depending on who serves it.
- Purging everywhere. Purges and tag invalidations must be sent to every provider, and a purge is not complete until all of them confirm.
- Lower hit ratios. Each CDN keeps its own cache, so splitting traffic means each sees fewer requests per object. A shared shield in front of the origin limits the extra origin load.
- Certificates and keys must be installed on every provider, and signed URL schemes must work on all of them.
- Steering. A steering service (or a managed DNS product with traffic policies) uses real-user measurements to shift traffic away from a CDN that is slow or failing in a given country, within the DNS TTL, typically under a minute.
The extra effort is why multi-CDN is common among very large streaming, news and e-commerce companies, and rare among smaller ones, for whom a single good provider plus a tested origin fallback is usually enough.
Choosing a TTL with numbers#
A TTL trades freshness against origin load, and the trade can be worked out. Suppose one object is requested 1,000 times per second worldwide, spread over 100 PoPs (10 requests per second each), and every PoP goes to a shield.
- TTL of 1 second: each PoP misses about once per second, so the shield gets about 100 requests per second for this object, and with collapsing the origin gets about 1 per second. Content is at most about 1 second stale.
- TTL of 60 seconds: each PoP misses about once a minute, so the shield sees under 2 requests per second, and the origin about 1 per minute. Content may be up to a minute stale.
- No caching: the origin gets all 1,000 requests per second.
Even a 1-second TTL removes 99.9% of origin load for a hot object, which is why micro-caching works so well for flash sales and breaking news. The longer TTL matters for the long tail: an object requested once every 30 seconds per PoP never hits with a 1-second TTL, but hits about half the time with a 60-second TTL.
A practical rule: start from the business question "how stale may this be?" and set the TTL to that value. Then add stale-while-revalidate so users never wait for the refresh, add stale-if-error so an origin outage does not become a user-facing outage, and purge by tag for the few changes that cannot wait for the TTL.
Browser TTL and edge TTL are separate decisions. You can purge a CDN, but you cannot purge the millions of browsers that already stored a copy. So for content that might need to change in place, keep the browser TTL short (max-age=0 or a few seconds) and give the edge a longer one (s-maxage=300), relying on purges at the edge. For content behind versioned URLs, both TTLs can be a year, because a change always means a new URL. Mixing these up is behind many "we purged it but users still see the old version" incidents: the CDN was correct, and the old copy lived in browser caches until its long max-age ran out.
Measuring whether the CDN is working#
A CDN that is configured but not measured often performs far worse than expected. The core metrics:
- Hit ratio by requests and by bytes. These differ. Many small API responses may miss while large video segments hit, giving a low request hit ratio but a high byte hit ratio. Bytes drive cost; requests drive origin CPU. Track both.
- Origin offload. The share of bytes and requests that never reach the origin. This is the number that decides how big the origin must be.
- Time to first byte (TTFB) by region and by hit or miss. A hit in Mumbai should take tens of milliseconds; if misses from Mumbai take 600 ms, a regional shield or a closer origin may help.
- Error rates split by source. A 5xx generated by the edge (timeout to origin, configuration error) needs a different fix from a 5xx passed through from the origin.
- Cache status header. Most CDNs add a response header such as
X-Cache: HITorcf-cache-status. Reading it in the browser developer tools is the fastest way to see why a request missed. - Real-user monitoring (RUM). Synthetic tests from data centers do not show what real users on mobile networks experience. Collect timing data from real browsers and apps, broken down by country, network and CDN. Multi-CDN steering is usually driven by exactly this data.
A useful habit: when the hit ratio drops, look at the cache keys of the top missing URLs. The cause is almost always a new query parameter, a cookie that leaked into the key, a Vary header, or a TTL that someone set to zero.
Failure modes and how to survive them#
| Failure | What users see | Defence |
|---|---|---|
| Origin down or slow | Errors or timeouts on misses | stale-if-error, long TTLs for content that can be stale, origin shield, static fallback pages at the edge |
| Mass expiry (stampede) | Origin overload when many popular objects expire together | Request collapsing, stale-while-revalidate, adding random jitter to TTLs |
| Full purge after a deploy | Sudden flood of misses | Versioned URLs, targeted tag purges, pre-warming the most popular objects |
| One PoP unhealthy | Users in one city see errors | The CDN steers them to the next PoP; you verify with per-region monitoring |
| Whole CDN down | Site unreachable worldwide | Multi-CDN with DNS steering and short TTLs on the CDN host names, or a tested path straight to the origin with enough capacity |
| Bad configuration push | Wrong content or errors everywhere | Configuration in version control, staged rollout, instant rollback |
| Cache poisoning | Users served a harmful or broken response | Only cache what the key fully describes, strip unknown headers, never cache error pages for long |
Web cache poisoning deserves a word. If the origin builds its response using a request header that is not part of the cache key (for example X-Forwarded-Host to construct script URLs), an attacker can send one crafted request, the poisoned response gets cached, and every later visitor receives it. James Kettle's 2018 research "Practical Web Cache Poisoning" showed this against many real sites. The defence: anything that changes the response must be in the cache key, or the origin must ignore it.
Web cache deception is the reverse: tricking the CDN into caching a private page as if it were a static file, for example a request for /account/profile.css that the application answers with the profile page while the CDN caches it because the path ends in .css. The defence is to cache based on the origin's Cache-Control headers rather than on file extensions alone, and to return 404 for paths the application does not really serve.
Uploads, two-way traffic and the CDN#
CDNs are mostly about downloads, but they can help uploads too. An upload from a phone in Jakarta to an origin in Virginia suffers from the same long round trips and lossy last-mile links. Some CDNs and clouds offer upload acceleration: the client sends to the nearest edge, which forwards over a fast backbone (Amazon S3 Transfer Acceleration works this way through CloudFront's edges). For very large files, combine this with multipart or resumable uploads so a dropped connection loses only one part. WebSockets and other long-lived connections can also be proxied through many CDNs, which gives them DDoS protection and nearby TLS termination, though nothing is cached.
Choosing a provider#
| Provider | Known for | Consider when |
|---|---|---|
| Amazon CloudFront | Tight integration with S3, ALB, Lambda@Edge and CloudFront Functions | Your stack is on AWS |
| Cloudflare | Anycast network with DDoS protection, WAF, Workers and free tiers | You want security and edge compute bundled, from small sites to large |
| Akamai | One of the oldest and most widely deployed CDNs, strong in media and enterprise | Very large media delivery, enterprise security needs |
| Fastly | Very fast purges, programmable caching (VCL and Compute), real-time logs | Frequently changing content, news and commerce |
| Google Cloud CDN, Media CDN | Google's edge network | Origins on Google Cloud, large-scale video |
| Azure Front Door | Global L7 entry point with CDN and WAF | Origins on Azure |
| Own CDN (Open Connect style) | Appliances inside ISPs | Only at the scale of the very largest video services |
When to Use It#
- Any public website or app with users spread over a large area.
- Static assets, images and video: almost always.
- High-traffic public APIs with shared responses.
- When you need DDoS protection or a WAF in front of the origin.
When NOT to Use It#
- Internal tools used from one office close to the servers.
- Highly personalised, write-heavy APIs where nothing is cacheable (though dynamic acceleration may still help).
- When data must stay in specific countries and the CDN cannot guarantee where it is cached.
How to Implement It#
- Put static files in object storage (S3, GCS) as the origin, and front it with the CDN.
- Use versioned file names and long TTLs for static assets.
- Set
Cache-Controldeliberately on every response type; mark personal dataprivate. - Define cache keys carefully: drop tracking parameters, include only headers that change the response.
- Enable origin shield and lock the origin to accept only CDN traffic.
- Monitor hit ratio, origin load and edge errors; alert when the hit ratio drops.
# Illustrative CDN behaviour rules (provider-agnostic)
- match: "/assets/*"
cache_key: [host, path]
ttl: 365d
- match: "/api/catalog/*"
cache_key: [host, path, query: [page, category]]
ttl: 5s
stale_while_revalidate: 30s
- match: "/api/me/*"
cache: bypass
origin_shield: us-east| Technology | Fits when |
|---|---|
| Amazon CloudFront | AWS origins (S3, ALB), tight AWS integration |
| Cloudflare | Anycast network with built-in DDoS, WAF and edge compute |
| Akamai | Large enterprise and media delivery, very broad PoP footprint |
| Fastly | Fast purges, programmable edge logic, real-time logs |
| Google Cloud CDN, Azure Front Door | Origins on those clouds |
Trade-offs#
| Choice | Pros | Cons | Pick when |
|---|---|---|---|
| Long TTL + versioned URLs | Highest hit ratio, no purges | Needs a build step that renames files | Static assets |
| Short TTL | Fresh content | More origin traffic | HTML, public API data |
| Purge on change | Fresh and cacheable | Purge latency, rate limits, races | CMS content, product updates |
| Pull | Simple, caches only what is used | First-request miss | Most content |
| Push | Fast from the first request | Manage uploads, pay storage | Known large releases |
| Multi-CDN | Resilience, price leverage | Harder config and debugging | Very large or critical services |
| Anycast routing | Simple, fast failover, absorbs DDoS | Coarse control of which PoP serves whom | Most modern CDNs |
| DNS-based mapping | Fine-grained, per-resolver steering | Depends on resolver location and DNS TTLs | Very large CDNs with detailed measurements |
| Edge compute | Logic and redirects without an origin trip | Platform limits, cost, harder debugging | Redirects, auth checks, personalisation of cached pages |
| Origin shield | One fetch per object instead of one per PoP | An extra hop on misses, one more component | Long-tail catalogues, live video |
Common Pitfalls#
- Caching a personalised page publicly and showing one user's data to another.
- Cache keys that include every query parameter or cookie, so nothing ever hits.
- Purging the whole CDN on every deploy, causing an origin traffic spike.
- Leaving the origin publicly reachable, so attackers bypass the CDN.
- Forgetting that browsers also cache: a bad long TTL can live in users' browsers after you purge the CDN.
- Using
Vary: User-AgentorVary: Cookie, which splits the cache into thousands of copies. - Leaving heuristic caching to chance by not sending
Cache-Controlat all. - Using
301redirects for links that may change or need analytics, since browsers may cache them forever. - Resizing images to any requested width, creating unbounded cache variants and processing cost.
- Pushing CDN configuration everywhere at once instead of rolling it out in stages.
Real-World Examples#
Netflix runs its own CDN, Open Connect, placing caching appliances inside internet providers' networks so most video traffic is served close to viewers.
Cloudflare, Akamai, Fastly and Amazon CloudFront are widely used commercial CDNs; several well-known internet outages have been traced to configuration problems at a single CDN, which is why some large companies use more than one.
Netflix places Open Connect appliances inside internet service providers and fills them with the next day's popular titles during off-peak hours, so most viewing traffic never crosses the wider internet. Large media and news sites often use Fastly for its fast, tag-based purges, since breaking stories change by the minute. Public CDN outages at Cloudflare (2019), Fastly (2021) and Akamai (2021) each affected many large websites at once, showing how much of the web depends on a few providers.
Giphy, as the System Design Newsletter describes it, serves billions of GIFs a day through Fastly with a shield tier, so a newly viral GIF reaches the origin once per shield rather than once per edge; see More Company Architectures. Cloudflare's own tiered cache and purge design is covered in Cloudflare's engineering lessons.
In the Interview#
How to introduce a CDN in an interview#
Bring the CDN in as soon as the design serves media or static files to users in many places, and say why in one sentence: "Images and video are most of the bytes, they never change once uploaded, and users are global, so they go to object storage behind a CDN." Then draw it in the right place: clients fetch media from the CDN host name directly, never through your application servers. The API servers only hand out URLs (often signed) that point at the CDN.
Next, give the numbers that justify it. A user far from the origin might wait 250-300 ms per request to the origin and 20-40 ms to a nearby PoP. With a 95% hit ratio, the origin serves one request in twenty, so a 100 Gbps delivery load becomes about 5 Gbps at the origin.
Then mention one or two of the design decisions that show depth, rather than listing every CDN feature:
- Cache policy: versioned, immutable URLs with a one-year TTL for media; short
s-maxagemicro-caching for shared API responses; no caching for personal data. - Origin protection: origin shield and request collapsing for viral content and live streams.
- Access control: signed URLs for private media.
- Failure: stale-if-error so the edge keeps serving during an origin outage, and multi-CDN for the most critical services.
Estimating CDN traffic and cost#
A worked example for a photo-sharing app with 50 million daily users, each viewing 100 images of 200 KB on average:
- Daily bytes: 50,000,000 × 100 × 200 KB = 1 PB per day.
- Average bandwidth: 1 PB ÷ 86,400 s is about 11.6 GB/s, or about 93 Gbps. The evening peak might be 2-3 times that, so 200-300 Gbps.
- With a 95% hit ratio, the origin (object storage) serves about 50 TB per day and 5-15 Gbps at peak.
- Monthly delivery is about 30 PB. At a negotiated rate of, say, 0.5-1 cent per GB this is 150,000-300,000 dollars a month, which is why large companies negotiate hard, push for higher hit ratios and better compression, and sometimes build their own caches.
State such prices as assumptions; the interviewer cares that you know egress is a major cost driver, not about exact rates.
Follow-up questions to expect#
- "A user uploads a new profile picture but still sees the old one." Use a new URL (include a version or content hash in the path) so the new picture is a different object; the old one simply ages out.
- "How do you stop people hot-linking or sharing paid videos?" Signed URLs or cookies with short expiry, checked at the edge; optionally bind them to a session or region.
- "What is in your cache key?" Path, the query parameters that change the response, and a normalised device or format class; never the whole cookie header.
- "Live event with 5 million viewers?" Segments of a few seconds, short manifest TTLs, request collapsing at edge and shield, and multiple CDNs with capacity reserved in advance.
- "Why not just add more origin servers?" Distance: extra servers in one region do not reduce the round trip to a user on another continent, and they do not absorb DDoS attacks.
Deep Dive: Request collapsing, edge compute and cache economicsShow
Request collapsing. When a popular object expires and thousands of requests arrive at once, a good CDN sends one request to the origin and makes the rest wait for it (collapsed forwarding). Combined with an origin shield and stale-while-revalidate, this prevents a "thundering herd" at the origin.
Cache hierarchy math. If each of 200 PoPs misses independently, a new object causes up to 200 origin fetches. With a shield, it is one. For long-tail content (many objects each requested rarely), edge hit ratio is low, so the shield and the origin's own capacity matter more than edge size.
Edge compute. CDNs now run code at the edge (Cloudflare Workers, Lambda@Edge, Fastly Compute). Uses include A/B routing, auth checks, personalisation of cached pages by stitching small dynamic pieces, image resizing on the fly and geo-based redirects. Logic moves closer to users, but debugging and data access become harder because edge code runs in hundreds of places.
Signed URLs and tokens. For paid or private content, the origin issues a URL or cookie signed with an expiry; the edge validates it without calling the origin. This keeps private video cacheable while restricting who can fetch it.
Economics. For large media companies, CDN egress cost drives architecture: higher hit ratios, better compression codecs (AV1, HEVC) and placing caches inside ISPs all reduce cost per GB. At smaller scale, a commercial CDN is almost always cheaper than serving from your own servers.
Deep Dive: HTTP caching headers, preciselyShow
CDNs follow the HTTP caching rules (RFC 9111, 2022), plus some vendor extensions. Knowing these exactly avoids most CDN bugs.
| Header or directive | Meaning |
|---|---|
Cache-Control: max-age=N | Any cache (browser or CDN) may reuse the response for N seconds |
s-maxage=N | Overrides max-age for shared caches (CDNs, proxies) only, so the browser and edge can have different TTLs |
public | Shared caches may store it, even if the request carried credentials |
private | Only the user's own browser may store it; a CDN must not |
no-cache | May be stored, but must be revalidated with the origin before each reuse |
no-store | Must not be stored anywhere; for sensitive data |
immutable | The content will never change at this URL; browsers skip revalidation even on reload |
stale-while-revalidate=N | After expiry, serve the stale copy for up to N seconds while fetching a fresh one in the background (RFC 5861) |
stale-if-error=N | If the origin fails, keep serving the stale copy for up to N seconds |
ETag, Last-Modified | Validators: the cache asks "has it changed?" with If-None-Match or If-Modified-Since, and a 304 Not Modified answer costs almost no bytes |
Vary: Accept-Encoding | Store separate copies per listed request header value |
Surrogate-Control, CDN-Cache-Control | CDN-only directives, stripped before the response reaches the browser |
Surrogate-Key or Cache-Tag | Labels for purging groups of objects at once (Fastly, Cloudflare and others) |
A typical policy:
- Fingerprinted assets (
app.3f9a1c.js):public, max-age=31536000, immutable. - HTML pages:
public, max-age=0, s-maxage=60, stale-while-revalidate=30. Browsers always check, and the edge serves for a minute. - Shared API responses:
public, s-maxage=5, stale-if-error=300. - Personal API responses:
private, no-store.
Vary pitfalls. Vary: User-Agent creates a separate cache entry for each of thousands of browser strings and destroys the hit ratio; normalise to a device class at the edge instead. Vary: Cookie has the same effect. A missing Vary: Accept-Encoding can send a compressed body to a client that cannot read it.
Heuristic caching. If a response has no explicit freshness information but has Last-Modified, caches may guess a lifetime (commonly 10% of the time since last modification). This is a common source of "why is this cached?" surprises, so always set Cache-Control explicitly.
Deep Dive: How large CDNs are engineeredShow
Origins of the field. Akamai grew out of MIT research on consistent hashing: Karger and colleagues' 1997 paper "Consistent Hashing and Random Trees" proposed spreading web content over caches so that adding or removing a cache moves only a small share of objects. Nygren, Sitaraman and Sun's 2010 paper "The Akamai Network: A Platform for High-Performance Internet Applications" describes the overall design: a mapping system that picks a nearby, healthy, lightly loaded edge cluster for each user using DNS, a large distributed fleet of edge servers, tiered distribution through parent clusters, and an overlay network that routes dynamic traffic over the best measured path.
The mapping problem. Choosing an edge for each user is an optimisation over latency, packet loss, PoP load and cost. DNS-based mapping only sees the resolver's address, not the user's, so a user of a far-away public resolver could be sent to the wrong PoP. The EDNS Client Subnet extension (RFC 7871) lets resolvers pass a truncated client prefix to fix this, at some privacy cost. Anycast CDNs avoid the problem by letting internet routing pick the nearest PoP, but give up fine control over load: if one PoP is overloaded, the CDN must withdraw or change route announcements, which moves traffic in large, coarse chunks.
Spreading objects inside a PoP. A PoP may have dozens of servers. If every server cached everything, the effective cache size would be one server's disk. Instead, a consistent hash of the cache key picks the "owner" server, so the PoP's cache capacity is the sum of its servers' disks, and each object is fetched from upstream only once per PoP. Very popular objects are copied to many servers so no single machine becomes a hot spot.
Eviction. Edge caches are full all the time, so the eviction policy directly sets the hit ratio. Plain LRU is common but lets one-hit wonders push out useful objects. Production caches add admission rules (cache only on the second request), segment LRU into probation and protected areas, or use frequency-aware schemes. Research continues: Yang and colleagues' 2023 paper "FIFO Queues are All You Need for Cache Eviction" (S3-FIFO) showed that simple FIFO queues with a small probationary queue can match or beat LRU-based algorithms on many production traces, while being cheaper to run.
Storage hierarchy. Hot objects stay in RAM, warm ones on NVMe SSDs, and in some designs a long tail on spinning disks. Netflix has described Open Connect appliances serving tens to hundreds of gigabits per second each, with an operating system and web server tuned for sending files straight from storage to the network, including kernel-level TLS so encrypted video needs little extra copying.
Configuration as the main risk. A CDN pushes configuration (routing rules, WAF rules, customer settings) to every server worldwide, often within seconds. The largest CDN outages have come from such pushes rather than hardware failures. Mature CDNs now roll changes out in stages (canary PoPs, then a region, then everywhere), validate configuration before shipping it, and keep a fast global rollback.
Key Takeaways#
- A CDN serves content from edge PoPs near users, routed by DNS or anycast, fetching from your origin on a miss.
- Pull CDNs cache on demand and suit most content; push suits large, predictable releases.
- Cache static assets with long TTLs and versioned URLs; micro-cache shared API responses; never cache personal data publicly.
- Design cache keys carefully and use an origin shield to protect the origin.
- CDNs also accelerate dynamic requests and absorb DDoS attacks, at a per-GB cost that dominates at video scale.
- Distance sets latency: a nearby PoP turns 200 ms round trips into 10-20 ms, which matters most for handshakes and many small requests.
- Prefer versioned URLs over purges; use purges, tags and short TTLs only for content that must change in place.
- Set
Cache-Controlexplicitly, uses-maxage,stale-while-revalidateandstale-if-error, and keepVarynarrow. - Lock the origin so only the CDN can reach it, and treat CDN configuration changes as high-risk deployments.
- In interviews, introduce the CDN for media first, size it with hit ratio and egress, then discuss shield, signed URLs and failure.