CDNs
How a CDN works
A content delivery network runs caching proxies in hundreds of points of presence (POPs, also called edge locations) around the world. DNS (or anycast routing) sends each user to a nearby POP:
- The user's request reaches the nearest edge.
- On a hit, the edge answers in a few milliseconds.
- On a miss, the edge asks a regional or shield cache, and only if that misses too does a request go to your origin (an S3 bucket, a load balancer, a server).
- The response is stored at each layer on the way back according to its TTL.
The middle layer (CloudFront Origin Shield, Cloudflare Tiered Cache) means a cold object is fetched from the origin once rather than once per POP, which matters a lot for big launches.
Besides speed, CDNs give you TLS at the edge close to users, DDoS absorption, a place to run a WAF and bot rules, and lower egress cost (data from CloudFront to users is cheaper than from EC2 or S3 directly, and origin-to-CloudFront transfer from AWS origins is free).
CloudFront in practice
- A distribution has one or more origins and an ordered list of cache behaviors, each matching a path pattern (
/api/*,/static/*, default*). - Each behavior has a cache policy (TTLs, and which headers, cookies and query strings go into the cache key) and an origin request policy (what is forwarded to the origin without being part of the key). Keep the key minimal and forward the rest.
- Managed policies cover common cases:
CachingOptimizedfor static content andCachingDisabledfor APIs that must reach the origin every time. - For S3 origins, use Origin Access Control (OAC, which replaced the older OAI) with a bucket policy that only allows CloudFront, and keep the bucket private.
- Signed URLs or signed cookies restrict private content (paid videos, downloads) to users with a valid signature.
- CloudFront Functions run tiny JavaScript at the viewer request and response stage (header rewrites, redirects, simple auth checks) in under a millisecond. Lambda@Edge runs fuller Node.js or Python code at all four stages, including origin request and response, and can make network calls.
- Invalidations remove paths from every edge. They take a minute or more, and beyond a monthly free allowance they cost per path (a wildcard like
/images/*counts as one).
Invalidation versus versioned assets
There are two ways to change content that is cached at the edge:
- Invalidate the path. Fine for occasional fixes, but slow, costly at scale, and it doesn't reach browsers that already cached the file.
- Version the URL: build tools put a content hash in the filename (
app.3f9a2c.js), and the HTML references the new name on each deploy. Old and new files can both be cached for a year withimmutable; only the short-lived HTML needs to refresh.
Deploy order matters with versioned assets: upload the new assets first, then the HTML that points to them, and keep the old assets for a while so users with an old page open don't get 404s.