The 30 second answer
A CDN is a network of servers in many locations that keeps cached copies of content close to users. A request goes to the nearest edge; if the edge has the file it answers immediately, otherwise it fetches from my origin once and caches it. It helps most for static assets and cacheable responses, because it cuts latency for distant users and takes load off my servers.
How it works. MDN defines a CDN as a group of servers spread over many locations that store duplicate copies of data, so a request can be served from the server closest to the user. AWS describes CloudFront the same way: requests are routed to the edge location with the lowest latency; if the content is already there it is delivered immediately, otherwise CloudFront retrieves it from the origin you configured.
What to put behind it.
- Static assets: images, JavaScript, CSS, fonts, video segments. These are the easy win.
- Cacheable API responses: public product pages or catalogue data that is the same for everyone, with a short lifetime.
- Not personalised or private data, unless you are very deliberate about cache keys, because a shared cache can leak one user's response to another.
How the origin controls caching. The CDN is an HTTP shared cache, so the rules come from HTTP caching (RFC 9111) and the Cache-Control header:
max-agesets freshness for all caches;s-maxagesets it only for shared caches like a CDN.privatekeeps a response out of shared caches;no-storekeeps it out of every cache.stale-while-revalidatelets the cache serve a slightly stale copy while it refreshes in the background.
Updating content. CloudFront documents two options: invalidate the file in the edge caches, or use versioned file names, for example app.3f9c2.js. Versioned names are the usual answer for assets, because the new HTML points to a new URL and no invalidation is needed.
Common mistakes interviewers listen for.
- Treating the CDN as only for static files; edge caching of public API responses can remove a large share of origin traffic.
- Long
max-ageon an unversioned file name, then being unable to ship a fix. - Forgetting that a cache miss still goes to the origin, so the origin must survive the traffic when the cache is cold.
Sources (5)
- MDN: CDNdeveloper.mozilla.org
- AWS: What is Amazon CloudFront?docs.aws.amazon.com
- AWS: Invalidate files to remove content from CloudFrontdocs.aws.amazon.com
- MDN: Cache-Control headerdeveloper.mozilla.org
- RFC 9111: HTTP Cachingrfc-editor.org