Chapter 23: CDN Deep Dive
What is a CDN?
Content Delivery Network (CDN): Distributed network of edge servers that cache content geographically close to users, reducing latency from 200ms+ to 20-50ms.
Core Components
- PoP (Point of Presence): Data center with edge servers in specific geographic location
- Edge Servers: Cache servers at PoPs serving content to nearby users
- Origin Server: Source of truth for content
- Anycast: Single IP routes to nearest PoP automatically
Latency Impact
| Scenario | Without CDN | With CDN | Improvement |
|---|---|---|---|
| US → US origin | 50ms | 15ms | 70% |
| Europe → US origin | 150ms | 20ms | 87% |
| Asia → US origin | 250ms | 30ms | 88% |
| Australia → US origin | 200ms | 25ms | 88% |
CDN Architecture
Edge Servers] PoP2[PoP - London
Edge Servers] PoP3[PoP - Tokyo
Edge Servers] Regional1[Regional Cache
Virginia] Regional2[Regional Cache
Frankfurt] Origin[Origin Server
US West] User1 -->|20ms| PoP1 User2 -->|18ms| PoP2 User3 -->|25ms| PoP3 PoP1 -->|Cache miss| Regional1 PoP2 -->|Cache miss| Regional2 PoP3 -->|Cache miss| Regional2 Regional1 -->|Cache miss| Origin Regional2 -->|Cache miss| Origin style PoP1 fill:#4CAF50 style PoP2 fill:#4CAF50 style PoP3 fill:#4CAF50 style Regional1 fill:#2196F3 style Regional2 fill:#2196F3 style Origin fill:#FF9800
Push vs Pull CDN
Push CDN
Content is pre-uploaded to CDN edge servers by origin. Origin controls when content is distributed.
- Origin pushes content to all edge locations
- Content available immediately when requested
- Good for infrequently changing content
- Examples: Software releases, static marketing sites
Pull CDN
CDN fetches content from origin on-demand when first requested. Lazy loading approach.
- First request fetches from origin (cache miss)
- Subsequent requests served from cache (cache hit)
- Content expires based on TTL
- Examples: User-generated content, dynamic sites
Comparison
| Aspect | Push CDN | Pull CDN |
|---|---|---|
| Content Distribution | Pre-upload by origin | Fetch on first request |
| First Request | Fast (already cached) | Slow (cache miss) |
| Storage Cost | Higher (all content stored) | Lower (only requested content) |
| Origin Load | Low (no requests) | Moderate (cache misses) |
| Content Updates | Manual push required | Automatic on TTL expiry |
| Traffic Prediction | Not required | Helpful for capacity |
| Best For | Low-traffic, static content | High-traffic, dynamic content |
| Complexity | Higher (manage uploads) | Lower (automatic) |
| Examples | Software binaries, firmware | Websites, APIs, media |
Cache Hierarchy
Multi-tier caching reduces origin load and improves cache hit rates through cache promotion.
Tiers
- Edge Cache: First tier, geographically closest to users (200+ locations)
- Regional Cache: Second tier, consolidates edge misses (10-20 locations)
- Shield Cache: Third tier, single point before origin (1-3 locations)
- Origin Server: Source of truth, fallback for all cache misses
Multi-Tier Diagram
Virginia] end subgraph Shield Tier S1[Shield
US East] end Origin[Origin
California] E1 -->|Miss| R1 E2 -->|Miss| R1 E3 -->|Miss| R1 R1 -->|Miss| S1 S1 -->|Miss| Origin style E1 fill:#4CAF50 style E2 fill:#4CAF50 style E3 fill:#4CAF50 style R1 fill:#2196F3 style S1 fill:#9C27B0 style Origin fill:#FF9800
Cache Hit Rates by Tier
| Tier | Typical Hit Rate | Traffic to Next Tier | Latency |
|---|---|---|---|
| Edge | 85-95% | 5-15% to Regional | 10-30ms |
| Regional | 60-80% (of misses) | 1-6% to Shield | 30-60ms |
| Shield | 70-90% (of misses) | 0.1-2% to Origin | 50-100ms |
| Origin | 100% (source) | N/A | 100-200ms |
Benefits
- Origin Protection: Only 0.1-2% of requests reach origin
- Cache Warming: Regional caches warm edge caches faster
- Resilience: Multiple fallback layers
- Cost: Reduced origin bandwidth by 98%+
Origin Shielding
Origin Shield: Additional caching layer between regional caches and origin, consolidating all cache misses through single PoP.
Without Shield
250 edge servers
× 10% miss rate
= 25 connections] style Origin fill:#f44336
With Shield
Single connection] -->|Miss| Origin Origin[Origin Server
1 connection
96% reduction] style Shield fill:#9C27B0 style Origin fill:#4CAF50
Impact
| Metric | Without Shield | With Shield | Improvement |
|---|---|---|---|
| Origin Requests | 10,000/sec | 500/sec | 95% |
| Origin Bandwidth | 1 Gbps | 50 Mbps | 95% |
| Origin CPU | 80% | 8% | 90% |
| Shield Hit Rate | N/A | 85-95% | - |
| Cache Coherency | Lower | Higher | Better |
Use Cases
- Origin Protection: Prevents origin overload during traffic spikes
- Cost Reduction: Reduces origin bandwidth costs 90%+
- Dynamic Content: Caches API responses, personalized content
- Cache Warming: Shield acts as pre-warmed cache for all edges
Cache-Control Headers
HTTP headers control CDN caching behavior. Origin sets headers, CDN respects them.
Key Directives
| Directive | Meaning | Use Case | Example |
|---|---|---|---|
max-age |
Browser & CDN cache TTL (seconds) | Static assets | max-age=31536000 (1 year) |
s-maxage |
CDN cache TTL, overrides max-age | Separate CDN/browser TTL | s-maxage=3600 (1 hour CDN) |
no-cache |
Revalidate before serving cached copy | Always check freshness | no-cache |
no-store |
Never cache (private data) | Sensitive/personalized | no-store |
public |
Cacheable by CDN & browser | Public content | public, max-age=3600 |
private |
Browser only, not CDN | User-specific content | private, max-age=600 |
immutable |
Content never changes | Versioned assets | immutable, max-age=31536000 |
stale-while-revalidate |
Serve stale, fetch fresh async | Low-latency updates | max-age=3600, swr=86400 |
stale-if-error |
Serve stale if origin down | Availability over freshness | max-age=3600, sie=86400 |
must-revalidate |
Never serve stale | Critical accuracy | max-age=3600, must-revalidate |
Common Patterns
| Content Type | Cache-Control Header | Rationale |
|---|---|---|
| Versioned JS/CSS | public, max-age=31536000, immutable |
Never changes, cache forever |
| HTML Pages | public, max-age=0, s-maxage=3600, must-revalidate |
CDN caches 1hr, browser revalidates |
| API Responses | public, max-age=60, s-maxage=300 |
CDN caches 5min, browser 1min |
| User Profile | private, no-store |
Never cache personal data |
| Images | public, max-age=2592000, stale-while-revalidate=86400 |
Cache 30d, serve stale 1d while refreshing |
Expires Header (Legacy)
Expires: Wed, 21 Oct 2026 07:28:00 GMT
Older alternative to Cache-Control. Use Cache-Control instead (more flexible, no clock skew issues).
s-maxage lets you set longer CDN TTL than browser TTL (CDN serves stale, browser revalidates). stale-while-revalidate improves P99 latency by serving stale while fetching fresh copy asynchronously.
Invalidation Strategies
How to remove or update cached content before TTL expires.
Methods
| Method | How It Works | Speed | Cost | Use Case |
|---|---|---|---|---|
| Purge | Delete specific URL(s) from cache | Fast (seconds) | Low | Fix specific stale content |
| Ban | Invalidate by pattern (regex, tag) | Fast (seconds) | Low | Invalidate related content |
| Versioned URLs | Change URL per version (hash/timestamp) | Instant | Free | Best practice for static assets |
| TTL Expiry | Wait for natural cache expiration | Slow (minutes-hours) | Free | Non-critical updates |
| Cache Tags | Tag content, purge by tag | Fast (seconds) | Low | Complex invalidation logic |
Versioned URLs (Best Practice)
// Instead of invalidating:
/static/app.js
/static/styles.css
// Use versioned URLs:
/static/app.a3f2b9c.js
/static/styles.7d4e1f2.css
// Or query params:
/static/app.js?v=a3f2b9c
/static/styles.css?v=7d4e1f2
Invalidation Flow
fetches fresh from origin
Cache Tags Example
// Origin response:
Cache-Control: public, max-age=3600
Cache-Tag: user-123, profile-page, user-content
// Invalidate all content tagged with user-123:
POST /api/v1/purge
{
"tags": ["user-123"]
}
// Invalidates:
// - /users/123
// - /users/123/posts
// - /api/users/123
CloudFront Invalidation
- Cost: First 1,000 paths/month free, $0.005 per path after
- Wildcards:
/images/*counts as 1 path - Time: 5-15 minutes to propagate globally
- Limit: 3,000 invalidations in progress per distribution
Dynamic Acceleration
CDN optimizations for uncacheable dynamic content (APIs, personalized pages, real-time data).
Techniques
1. Route Optimization
- Private Backbone: CDN routes traffic over optimized private network, avoiding congested public internet
- BGP Optimization: Real-time route selection based on network conditions
- Impact: 20-40% latency reduction vs public internet
2. TCP Optimization
- TCP Termination: Edge server terminates TCP with user, separate optimized connection to origin
- TCP BBR: Google's congestion control algorithm, better throughput
- TCP Fast Open: Send data in SYN packet (0-RTT)
- Impact: Eliminates slow-start, reduces handshake overhead
3. Connection Pooling
- Persistent Connections: Edge maintains warm connections to origin
- Multiplexing: HTTP/2 multiplexes requests over single connection
- Impact: Eliminates per-request TLS handshake (100-200ms saved)
4. Smart Compression
- Gzip/Brotli: Compress responses at edge (not origin)
- Delta Compression: Send only changes for repeated requests
- Impact: 60-80% size reduction, faster transfer
Dynamic Acceleration Flow
Sydney] -->|1. TCP to edge
25ms| Edge[Edge PoP
Sydney] Edge -->|2. Persistent HTTP/2
over private backbone
100ms| Origin[Origin
US East] Origin -->|3. Response| Edge Edge -->|4. Compressed
25ms| User style Edge fill:#4CAF50 style Origin fill:#FF9800
Performance Impact
| Optimization | Latency Saved | Applicable To |
|---|---|---|
| Route optimization | 20-50ms | All requests |
| TCP termination | 50-150ms | First request |
| TLS session reuse | 100-200ms | Repeat connections |
| HTTP/2 multiplexing | 50-100ms | Multiple resources |
| Compression at edge | 100-300ms | Large payloads |
Edge Computing
Run code at CDN edge servers for sub-10ms response times without origin roundtrip.
Comparison
| Platform | Provider | Runtime | Cold Start | Locations | Max Duration | Use Case |
|---|---|---|---|---|---|---|
| Cloudflare Workers | Cloudflare | V8 isolates | <1ms | 300+ | CPU: 50ms, Unbound: 30s | Auth, routing, A/B tests |
| Lambda@Edge | AWS CloudFront | Node.js, Python | 100-300ms | 13 regions | Viewer: 5s, Origin: 30s | Complex logic, auth |
| CloudFront Functions | AWS CloudFront | JavaScript | <1ms | 400+ | 1ms | Header rewrite, redirects |
| Fastly Compute | Fastly | WebAssembly | <1ms | 70+ | 60s | Complex edge logic |
| Akamai EdgeWorkers | Akamai | JavaScript | ~10ms | 4,000+ | 50ms | Personalization, AB test |
| Vercel Edge Functions | Vercel | V8 isolates | <1ms | 50+ | 30s | Next.js middleware |
Use Cases
- Authentication: Verify JWT at edge, block unauthorized requests
- A/B Testing: Route users to variants without origin roundtrip
- Personalization: Insert user data into HTML at edge
- Bot Detection: Block scrapers/bots before reaching origin
- Geo-Routing: Route based on user location
- Header Manipulation: Rewrite headers, add security headers
- Redirects: 301/302 redirects without origin
- Image Optimization: Resize/compress images on-demand
Cloudflare Worker Example
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
// Verify JWT at edge
const token = request.headers.get('Authorization')
if (!token || !await verifyJWT(token)) {
return new Response('Unauthorized', { status: 401 })
}
// A/B test routing
const variant = Math.random() < 0.5 ? 'A' : 'B'
const url = new URL(request.url)
url.hostname = variant === 'A' ? 'origin-a.com' : 'origin-b.com'
// Fetch from origin
const response = await fetch(url, request)
// Add security headers
const newResponse = new Response(response.body, response)
newResponse.headers.set('X-Frame-Options', 'DENY')
newResponse.headers.set('X-Variant', variant)
return newResponse
}
Edge vs Serverless
| Aspect | Edge Functions | Serverless (Lambda) |
|---|---|---|
| Latency | <10ms | 50-200ms |
| Cold Start | <1ms | 100-1000ms |
| Locations | 300+ edge PoPs | 20 regions |
| Runtime | Limited (V8, Wasm) | Full (any language) |
| Duration | 50ms - 60s | 15min |
| Memory | 128MB - 512MB | 128MB - 10GB |
| Best For | Fast, lightweight logic | Complex, long-running tasks |
Video CDN
Specialized CDN features for video streaming: adaptive bitrate, segment caching, live streaming.
Streaming Protocols
| Protocol | Full Name | Segment Size | Latency | Support |
|---|---|---|---|---|
| HLS | HTTP Live Streaming | 2-10s | 10-30s | iOS, Safari, universal |
| DASH | Dynamic Adaptive Streaming over HTTP | 2-10s | 10-30s | Android, Chrome, universal |
| CMAF | Common Media Application Format | 2-10s | 3-5s | Modern HLS + DASH |
| LL-HLS | Low-Latency HLS | 200ms | 2-3s | iOS 14+, Safari 14+ |
Adaptive Bitrate Streaming
Video encoded at multiple quality levels, player switches based on bandwidth.
4K 20Mbps] --> Encoder[Encoder] Encoder --> Q1[240p
400 Kbps] Encoder --> Q2[360p
800 Kbps] Encoder --> Q3[480p
1.5 Mbps] Encoder --> Q4[720p
3 Mbps] Encoder --> Q5[1080p
6 Mbps] Encoder --> Q6[4K
15 Mbps] Q1 --> CDN[CDN] Q2 --> CDN Q3 --> CDN Q4 --> CDN Q5 --> CDN Q6 --> CDN CDN --> Player[Player
Switches based on bandwidth] style Encoder fill:#FF9800 style CDN fill:#4CAF50 style Player fill:#2196F3
Segment Caching
- Manifest Files: .m3u8 (HLS) or .mpd (DASH), lists video segments, low TTL (1-5s)
- Video Segments: .ts or .m4s files, 2-10s chunks, high TTL (1 day - 1 year)
- Byte-Range Requests: CDN caches full file, serves ranges on demand
- Prefetching: CDN prefetches next segments based on player behavior
Video CDN Architecture
Encoder] -->|Push segments| CDN1[CDN Edge] CDN1 -->|Manifest: TTL 5s
Segments: TTL 1 day| Player1[Player 1
1080p] CDN1 --> Player2[Player 2
480p] CDN1 --> Player3[Player 3
720p] style Origin fill:#FF9800 style CDN1 fill:#4CAF50 style Player1 fill:#2196F3 style Player2 fill:#2196F3 style Player3 fill:#2196F3
Live vs VOD
| Aspect | Live Streaming | VOD (Video on Demand) |
|---|---|---|
| Cache TTL | Short (5-30s) | Long (1 day - 1 year) |
| Origin Load | High (manifest updates) | Low (95%+ cache hit) |
| Latency | 10-30s (standard), 2-5s (low-latency) | No concern |
| Complexity | High (real-time encoding) | Low (pre-encoded) |
| Cost | Higher (origin traffic) | Lower (high cache hit) |
Optimization Techniques
- Multi-CDN: Use multiple CDNs for redundancy, switch on failure
- Pre-Positioning: Upload popular content to edge before demand
- Tiered Caching: Shield origin from thousands of viewers
- Token Authentication: Signed URLs prevent hotlinking
CDN Security
CDNs provide security layers: DDoS mitigation, WAF, bot protection, origin cloaking.
Security Features
1. DDoS Mitigation
- L3/L4: SYN floods, UDP floods absorbed by CDN infrastructure
- L7: HTTP floods detected via rate limiting, CAPTCHA challenges
- Capacity: CDN PoPs absorb 10-100+ Tbps attacks
- Anycast: Distributes attack across all PoPs globally
2. Web Application Firewall (WAF)
- OWASP Top 10: Blocks SQL injection, XSS, CSRF, etc.
- Custom Rules: Block by IP, country, user-agent, headers
- Rate Limiting: Limit requests per IP/user
- Managed Rules: Pre-configured rulesets (AWS Shield, Cloudflare)
3. Bot Protection
- JavaScript Challenge: Render JS to prove real browser
- CAPTCHA: Challenge suspicious traffic
- Fingerprinting: Identify bots via TLS, HTTP/2 fingerprints
- Behavioral Analysis: Detect scraping patterns
4. Origin Cloaking
- Hide Origin IP: DNS points to CDN, origin IP not exposed
- Private VPC: Origin in private network, CDN connects via PrivateLink/VPN
- IP Allowlist: Origin only accepts traffic from CDN IPs
DDoS Mitigation Flow
100 Gbps flood] -->|Attack| CDN[CDN PoPs
10 Tbps capacity] Legit[Legitimate Users] -->|Normal traffic| CDN CDN -->|DDoS absorbed
at edge| CDN CDN -->|Only clean traffic
5 Mbps| Origin[Origin
Protected] style Attacker fill:#f44336 style CDN fill:#4CAF50 style Origin fill:#2196F3
WAF Rule Example
// Block SQL injection attempts
{
"rule": "sql-injection-protection",
"condition": "request.query contains 'union select' or request.body contains '1=1'",
"action": "block"
}
// Rate limit API
{
"rule": "api-rate-limit",
"condition": "request.path starts with '/api/'",
"action": "rate-limit: 100 req/min per IP"
}
// Geo-blocking
{
"rule": "block-country",
"condition": "request.country in ['CN', 'RU']",
"action": "block"
}
Security Comparison
| Feature | CloudFront | Cloudflare | Fastly | Akamai |
|---|---|---|---|---|
| DDoS Protection | AWS Shield (65 Tbps) | Unlimited (194 Tbps absorbed) | Included | Prolexic (4+ Tbps) |
| WAF | AWS WAF (pay-per-rule) | Included (Free/Pro/Biz) | Next-Gen WAF (paid) | Kona Site Defender |
| Bot Protection | AWS WAF Bot Control | Super Bot Fight Mode | Signal Sciences | Bot Manager |
| Origin Cloaking | Yes | Yes | Yes | Yes |
| HTTPS | Free (ACM certs) | Free (Universal SSL) | Free (Let's Encrypt) | Included |
CDN Provider Comparison
Major Providers
| Provider | PoPs | Edge Computing | Pricing Model | Strengths | Best For |
|---|---|---|---|---|---|
| CloudFront | 450+ | Lambda@Edge, CloudFront Functions | Pay-per-GB, per-request | AWS integration, global reach | AWS-heavy workloads |
| Cloudflare | 300+ | Workers (V8 isolates) | Flat monthly + overage | DDoS protection, free tier | Security-first, cost-effective |
| Akamai | 4,000+ | EdgeWorkers | Enterprise custom | Largest network, reliability | Enterprise, mission-critical |
| Fastly | 70+ | Compute@Edge (Wasm) | Pay-per-GB, per-request | Real-time purge, granular control | Developer-friendly, APIs |
| Azure CDN | 180+ | Azure Functions | Pay-per-GB | Azure integration, China access | Azure-heavy workloads |
| Google Cloud CDN | 180+ | Cloud Functions | Pay-per-GB + cache fill | GCP integration, low latency | GCP-heavy workloads |
Pricing Comparison (US/Europe)
| Provider | First 10TB | 50TB-150TB | Requests (per 10k) | Free Tier |
|---|---|---|---|---|
| CloudFront | $0.085/GB | $0.060/GB | $0.0075 (HTTP), $0.010 (HTTPS) | 1TB + 10M requests/month (12 months) |
| Cloudflare | $20/month (unlimited) | $200/month (unlimited) | Unlimited | Unlimited (Free plan) |
| Fastly | $0.12/GB | $0.09/GB | $0.0075 | $50 credit |
| Google CDN | $0.08/GB | $0.04/GB | Included | No |
| Azure CDN | $0.081/GB | $0.035/GB | Included | No |
Feature Matrix
| Feature | CloudFront | Cloudflare | Fastly | Akamai |
|---|---|---|---|---|
| Cache Purge Time | 5-15 min | Instant (150ms) | Instant (<150ms) | 5-10 min |
| Origin Shield | Yes | No (Argo Tiered Cache) | Yes | Yes |
| HTTP/3 (QUIC) | Yes | Yes | Yes | Yes |
| WebSocket | Yes | Yes | Yes | Yes |
| Image Optimization | No (use Lambda@Edge) | Yes (Polish) | Yes (Image Optimizer) | Yes (Image Manager) |
| Analytics | CloudWatch | Dashboard + GraphQL API | Real-time logs | Luna Control Center |
| China Access | Separate license | Enterprise only | Via partners | Yes |
When to Use Each
- CloudFront: Already on AWS, need tight S3/ALB integration, Lambda@Edge for complex logic
- Cloudflare: Cost-sensitive, need strong DDoS/security, Workers for edge compute, instant purge
- Fastly: Developer control, VCL customization, instant purge critical, high-performance APIs
- Akamai: Enterprise, mission-critical (99.999% SLA), largest network, China access
Summary
- CDN Basics: Edge servers cache content near users, reducing latency from 200ms to 20-50ms via geographic proximity and Anycast routing
- Push vs Pull: Pull CDN (most common) fetches on-demand, Push CDN pre-uploads content. Pull better for dynamic/high-traffic sites
- Cache Hierarchy: Edge → Regional → Shield → Origin. Multi-tier multiplies hit rates to 98%+, reducing origin load 90%+
- Origin Shield: Consolidates edge misses through single PoP, protecting origin from connection fan-out
- Cache-Control:
max-agesets TTL,s-maxagefor CDN-specific TTL,stale-while-revalidateserves stale while refreshing,immutablefor versioned assets - Invalidation: Versioned URLs best (instant, free), purge/ban for emergency fixes, cache tags for surgical invalidation
- Dynamic Acceleration: Route optimization (private backbone), TCP termination, connection pooling, compression at edge - helps uncacheable content
- Edge Computing: Run code at edge (Cloudflare Workers, Lambda@Edge) for sub-10ms responses. Auth, A/B tests, personalization without origin roundtrip
- Video CDN: HLS/DASH adaptive bitrate, segment caching (high TTL), manifest updates (low TTL), 95%+ cache hit for VOD
- Security: DDoS mitigation (100+ Tbps capacity), WAF (OWASP Top 10), bot protection, origin cloaking (hide origin IP)
- Providers: CloudFront (AWS integration), Cloudflare (cost/security), Fastly (instant purge/control), Akamai (enterprise/reliability)