What is a CDN and how does it work? When should you use one?
A Content Delivery Network (CDN) is a globally distributed network of servers (Points of Presence — PoPs) that cache and serve content from locations geographically closer to the user.
How it works:
- User requests
cdn.example.com/image.jpg - DNS resolves to the nearest CDN edge server (based on anycast routing or GeoDNS)
- Edge server checks its cache:
- Cache hit: Returns content immediately (~5-20ms)
- Cache miss: Fetches from origin, caches it, returns to user
- Subsequent requests from same region → cache hit
What CDNs cache:
- Static assets: JS, CSS, images, fonts, videos
- Cacheable API responses (with proper Cache-Control headers)
- Dynamically rendered HTML (edge-side rendering)
CDN Features:
- SSL termination at edge — reduces TLS handshake latency
- DDoS protection — absorbs traffic at edge, protects origin
- Compression — Brotli/gzip at edge
- Image optimization — WebP conversion, resizing on-the-fly
- Edge computing — Cloudflare Workers, Lambda@Edge for logic at edge
Cache-Control headers:
Cache-Control: public, max-age=86400— CDN caches for 24hCache-Control: no-store— never cache (user-specific data)Vary: Accept-Encoding— cache separate copy per encoding
Cache invalidation: URL versioning (main.abc123.js) or CDN API purge
Providers: Cloudflare, AWS CloudFront, Fastly, Akamai, Azure CDN
Use when: Serving media/static assets globally; high traffic with cacheable content; DDoS protection needed; reducing origin load.