CDNs & Edge Computing
18 min read
CDNEdge ComputingCache InvalidationPoPOrigin ServerTTL
Content Delivery Networks: Bringing Your App Closer to Users
A CDN is a globally distributed network of servers (called Points of Presence or PoPs) that cache and serve your content from the location closest to each user.
How CDNs Work
- First Request: User in Tokyo requests your site. The CDN's DNS routes them to the nearest PoP (e.g., Tokyo edge server).
- Cache Miss: The edge server doesn't have the content yet. It fetches from your Origin Server (e.g., in US-East), caches it, and serves it.
- Subsequent Requests: Any user in the Tokyo region gets the cached version — no round-trip to the US needed.
Caching Strategies
| Strategy | Header | Use Case |
|---|---|---|
| Cache Forever | Cache-Control: max-age=31536000, immutable | Hashed static assets (app.a1b2c3.js) |
| Revalidate | Cache-Control: no-cache | HTML pages (check freshness each time) |
| Never Cache | Cache-Control: no-store | Personalized/sensitive data |
| Stale While Revalidate | Cache-Control: max-age=60, stale-while-revalidate=3600 | API responses that can be slightly stale |
Edge Computing vs. Traditional CDN
Traditional CDNs just cache static files. Edge computing (Cloudflare Workers, Vercel Edge Functions) runs your code at the edge — enabling personalization, A/B testing, and geolocation logic without hitting the origin.
Cache Invalidation — The Hardest Problem
"There are only two hard things in Computer Science: cache invalidation and naming things." — Phil Karlton
When you deploy a new version, you need to purge the CDN cache. Strategies include:
- Cache Busting: Add content hashes to filenames (Webpack/Vite do this automatically).
- Purge API: Programmatically invalidate specific URLs via CDN API.
- Tag-based Invalidation: Tag cached responses (e.g., "product-123") and purge by tag.
Key Metrics
- Cache Hit Ratio: Percentage of requests served from cache (target: >90%).
- TTFB (Time to First Byte): Should be <100ms for cached content.
- Origin Shield: A secondary cache layer that protects your origin from thundering herd problems.