CDNs
How a CDN serves files from caches near users, how caching headers and invalidation work, how private content is handled, and what interviewers ask.
On this page
- Where a CDN sits
- How a user reaches a nearby edge
- Pull and push CDNs
- The cache key
- Cache-Control headers
- Updating cached content
- Origin shield and tiered caching
- Serving stale content
- Dynamic content
- Private content: signed URLs and signed cookies
- What must never be cached
- Failures and using a second CDN
- In the interview
- What to practise next
A content delivery network (CDN) is a group of caching servers, called edges, placed in many cities around the world. A user's request goes to a nearby edge. If the edge has a copy of the file it answers immediately, and if not, it fetches the file from your own servers (the origin) and keeps a copy for the next user. A CDN cuts latency for users who are far from your servers and takes most of the traffic for images, video and scripts away from the origin.
Without a CDN, every user downloads every file from the origin. Distant users wait for a long round trip on each request, and the origin needs bandwidth for every download. A CDN is a cache, so its copies sit in hundreds of places and cannot all be updated instantly.
Where a CDN sits
How a user reaches a nearby edge
DNS-based routing
The site's hostname is a CNAME that points at the CDN's DNS service. When a user's resolver looks it up, the CDN's DNS server returns the address of an edge that is close to the resolver and has spare capacity. There are two limits. The CDN sees the location of the resolver, not of the user, so someone using a distant public resolver may be sent to the wrong region. And because answers are cached for their TTL, a routing change takes that long to reach users.
Anycast
With anycast, many edges announce the same IP address over BGP, and the network delivers each packet to the closest location by routing distance. No DNS decision is needed, and when a location fails and stops announcing the address, traffic moves to the next closest one without waiting for a TTL. The cost is less control over who is served where.
Pull and push CDNs
With a pull CDN you publish files only to your origin. Each edge fetches a file the first time someone asks for it. Edges do not share caches, so the first request in each region is a miss that goes to the origin. Pull is the right choice for almost every site. Its weakness is that a launch of new content sends a burst of misses to the origin.
With a push CDN you upload files to the CDN yourself, and it copies them to its edges before anyone asks. Nothing misses, so a large release does not hit the origin. The cost is that you manage uploads and deletions, and you pay to store every file everywhere whether or not it is requested. Push is worth it for large files with a known release time, such as a game patch, where every edge would otherwise pull gigabytes from the origin at once.
The cache key
The cache key decides which requests share one stored copy. By default it is made of the host, the path and the query string, and the aim is to include exactly the parts of a request that change the response.
If the key contains too much, the hit rate drops. With a tracking parameter such as ?utm_source=mail in the key, every campaign link gets its own copy of the same image.
If the key contains too little, users receive the wrong content. When the key ignores ?size=small, everyone gets whichever size was cached first. A server that returns different bytes depending on Accept-Encoding lists that header in Vary, and the CDN then stores one copy for each value. A header with many distinct values, such as User-Agent, makes the cache useless.
Cache-Control headers
The origin tells every cache how to treat a response with the Cache-Control header. The directives that matter for a CDN are these.
max-age=Nlets any cache, including the browser, reuse the response for N seconds without asking the origin.s-maxage=Napplies only to shared caches such as a CDN and overridesmax-agefor them. It lets a CDN keep a response for an hour while browsers keep it for a minute.privateallows only the user's own browser to store the response, so a CDN must not.no-storeforbids every cache from keeping the response. It is not the same asno-cache, which allows storing but requires a check with the origin before each reuse.
When a copy has expired, the cache does not have to download the file again. It sends a conditional request with the validator it saved (ETag or Last-Modified), and an unchanged file comes back as a short 304 Not Modified response with no body.
Updating cached content
Versioned file names
You put a content hash in the file name, such as app.3f9a1c.js, and cache the file for a year. A new release has a new name, so the old copy is never wrong and nothing has to be removed. Only the HTML page that links to the file must change, and that page gets a short lifetime. This method does not work for URLs that people have bookmarked or that other sites link to.
TTL expiry
You do nothing, and the copies expire when their lifetime ends. This suits content that may be a little stale. After a change, users can see the old version for up to the whole TTL.
Purge
You ask the CDN to remove a path, a prefix or everything with a given tag, and the next request fetches the new version. Use it for corrections and fixed URLs. A purge reaches all edges within seconds to a minute, not instantly, and it throws away a warm cache, so a broad purge sends every edge to the origin at once.
Origin shield and tiered caching
Because each edge fills its own cache, a new file causes one origin request for every edge that receives a request for it. An origin shield is one designated cache, usually near the origin, that all edges ask on a miss. The origin then sees at most one request per file, and simultaneous requests for the same file are merged. Tiered caching is the same idea with more levels: edges ask regional caches, and regional caches ask the origin.
Serving stale content
stale-while-revalidate=N lets the edge answer with an expired copy for up to N seconds while it fetches a fresh one in the background. The user never waits for the origin, and the origin gets one refresh request instead of a burst.
stale-if-error=N lets the edge serve an expired copy for up to N seconds when the origin returns errors or cannot be reached. During an origin outage the site keeps working for everything that was cached.
Dynamic content
A CDN also speeds up responses that cannot be cached. The user's TLS handshake takes several round trips, and with an edge nearby it completes with that edge instead of the distant origin, which is called edge TLS termination. The edge also keeps long-lived connections open to the origin and reuses them, so a request does not pay a new TCP and TLS setup.
Private content: signed URLs and signed cookies
Private files such as paid videos can be served by a CDN if the edge can check permission itself. A signed URL contains an expiry time and a signature over the path and the expiry, usually an HMAC made with a secret that your application and the CDN share. The application checks that the user may see the file and creates the URL, and the edge recomputes the signature and refuses a mismatch or an expired time.
https://cdn.example.com/videos/v881/seg-0042.ts
?expires=1767225600
&sig=HMAC(secret, "/videos/v881/seg-0042.ts" + "1767225600")A signed URL works for anyone who has it until it expires, so keep the lifetime to minutes for sensitive files. The signature must not be part of the cache key, or the hit rate falls to zero. A signed cookie covers a whole path prefix, which suits a video with hundreds of segments: the application sets it once, and the edge validates it on every request for that folder.
What must never be cached
A shared cache must never store a response that depends on who is asking. If an account page or an API response with private data is cached under a shared key, the next visitor receives someone else's data. Mark such responses private or no-store and do not rely on the CDN's defaults.
Failures and using a second CDN
The origin fails
Cached files carry on being served until their lifetime ends, and stale-if-error extends that to expired files. Dynamic requests and uncached files fail, so the origin needs its own redundancy.
The CDN fails
If the provider has an outage, every user is affected. A site that cannot accept that runs two CDNs and uses DNS health checks to send everything to the survivor, and failover takes as long as the DNS TTL. Traffic is split, so each CDN has a lower hit rate. When one fails, the other has a cold cache for the extra traffic, and the origin can be overloaded by the burst of misses. Signing and purge APIs differ between providers, so you maintain both. A second CDN is justified only when downtime would be very costly.
Cost
CDN providers charge mainly for the data sent to users, plus smaller charges for requests. A CDN usually lowers the total bill, because a high hit rate cuts the bandwidth you pay for at the origin. With a low hit rate you pay the CDN and the origin for the same request, so a clean cache key, longer lifetimes and a shield are also the way to control cost.
In the interview
Bring in a CDN when a large share of the bytes are static files or media, or when users are spread across regions. For example: "Images and video are most of our bytes and are the same for everyone, so they go on a pull CDN. File names contain a content hash, so I cache them for a year and never purge. The HTML has a short lifetime."
Questions to expect:
- "How does a user get to the nearest edge?" With DNS routing, the CDN's name server answers with the address of an edge near the user's resolver. With anycast, many locations announce the same IP and the network sends the user to the closest one. DNS depends on the resolver's location and on TTLs, while anycast fails over quickly.
- "How do you update an image that is already cached?" Give the new file a new name, which makes it a new cache key, and link to it from a page with a short lifetime. A purge works for fixed URLs but is not instant and causes a burst of misses.
- "The hit rate is 60% and the origin is struggling. What do you check?" Look first at the cache key for tracking parameters, cookies and
Varyheaders that split copies. Then check the lifetimes, and add an origin shield if a long tail of files is spread across many edges. - "How do you serve private videos through a CDN?" The application checks the subscription and issues a signed URL or signed cookie that expires in minutes. A weak answer has the CDN call the application on every request, which undoes the CDN.
- "What happens when the CDN or the origin goes down?" If the origin fails, edges keep serving cached files, and
stale-if-errorcovers expired ones. If the CDN fails, DNS can send traffic to a second CDN, but that one starts with a cold cache and can overload the origin, so the origin needs a shield and some headroom. - "What do you never cache?" Anything that depends on the user, such as an account page or an API response with personal data, is marked
privateorno-store, because a shared cache would otherwise hand one user's data to the next visitor. Values that must be exact, such as a balance at checkout, also stay out of the CDN.
Your video catalogue is large and subscribers are spread across the world. How do you serve it?
I would put the video segments and thumbnails on a pull CDN with an origin shield. Segment names never change, so they get a long lifetime and need no purging.
The videos are for paying subscribers only. Can they still be cached?
Yes. The app checks the subscription and sets a signed cookie for that video's path that expires in minutes. The edge checks the signature itself, and the signature is not part of the cache key.
What if the CDN has an outage?
DNS health checks would move traffic to a second CDN. Its cache starts cold, so the shield and some origin capacity are needed.
You deploy a new JavaScript bundle. The old bundle was cached at the CDN for a year. How do you make users load the new one?
A public product page is the same for everyone. You want browsers to reuse it for 1 minute but the CDN to keep it for 1 hour. Which header does that?
What to practise next
Read Caching for the strategies and failure cases that also apply to CDN caches, and Networking Essentials for DNS, TCP and TLS. To see a CDN carry most of a system's bytes, work through Design Video Streaming.