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

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

graph TB User1[User - US East] User2[User - Europe] User3[User - Asia] PoP1[PoP - New York
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
Interview Tip: Explain CDN reduces latency via geographic proximity, offloads origin traffic (80-95% cache hit rates), and improves availability through redundancy. Mention anycast routing.

Push vs Pull CDN

Push CDN

Content is pre-uploaded to CDN edge servers by origin. Origin controls when content is distributed.

Pull CDN

CDN fetches content from origin on-demand when first requested. Lazy loading approach.

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
Interview Tip: Most modern CDNs use pull (CloudFront, Cloudflare). Push used for controlled distribution (software updates). Hybrid possible: push critical assets, pull everything else.

Cache Hierarchy

Multi-tier caching reduces origin load and improves cache hit rates through cache promotion.

Tiers

  1. Edge Cache: First tier, geographically closest to users (200+ locations)
  2. Regional Cache: Second tier, consolidates edge misses (10-20 locations)
  3. Shield Cache: Third tier, single point before origin (1-3 locations)
  4. Origin Server: Source of truth, fallback for all cache misses

Multi-Tier Diagram

graph LR subgraph Edge Tier E1[Edge NYC] E2[Edge Boston] E3[Edge Miami] end subgraph Regional Tier R1[Regional
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

Interview Tip: Explain how cache hierarchy multiplies hit rates: 90% edge hit + 80% regional hit of remaining 10% = 98% total. Shield reduces origin load from thousands of edge servers to single connection.

Origin Shielding

Origin Shield: Additional caching layer between regional caches and origin, consolidating all cache misses through single PoP.

Without Shield

graph TB E1[Edge NYC] -->|Miss| Origin E2[Edge London] -->|Miss| Origin E3[Edge Tokyo] -->|Miss| Origin E4[Edge Sydney] -->|Miss| Origin E5[Edge Mumbai] -->|Miss| Origin Origin[Origin Server
250 edge servers
× 10% miss rate
= 25 connections] style Origin fill:#f44336

With Shield

graph TB E1[Edge NYC] -->|Miss| Shield E2[Edge London] -->|Miss| Shield E3[Edge Tokyo] -->|Miss| Shield E4[Edge Sydney] -->|Miss| Shield E5[Edge Mumbai] -->|Miss| Shield Shield[Shield PoP
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

Interview Tip: Shield reduces origin "connection fan-out" from hundreds of edge servers to single connection. Essential for protecting legacy origins or expensive origin compute (database queries).

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).

Interview Tip: 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

sequenceDiagram participant Origin participant CDN API participant Edge1 participant Edge2 participant EdgeN Origin->>CDN API: Purge /api/users/123 CDN API->>Edge1: Invalidate command CDN API->>Edge2: Invalidate command CDN API->>EdgeN: Invalidate command Edge1->>Edge1: Delete from cache Edge2->>Edge2: Delete from cache EdgeN->>EdgeN: Delete from cache Note over Edge1,EdgeN: Next request cache miss,
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

Interview Tip: Versioned URLs (cache busting) are best practice - instant, free, no propagation delay. Purge/ban for emergency fixes. Avoid invalidating everything - use cache tags for surgical invalidation.

Dynamic Acceleration

CDN optimizations for uncacheable dynamic content (APIs, personalized pages, real-time data).

Techniques

1. Route Optimization

2. TCP Optimization

3. Connection Pooling

4. Smart Compression

Dynamic Acceleration Flow

graph LR User[User
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
Interview Tip: Dynamic acceleration helps when content can't be cached (APIs, personalized). Key insight: Edge terminates user connection (fast), maintains persistent connection to origin (eliminating handshakes), routes over private backbone (avoiding congestion).

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

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
Interview Tip: Edge functions trade flexibility for speed. Cloudflare Workers use V8 isolates (lighter than containers) for sub-1ms cold starts. Use for auth, routing, simple transforms. Complex logic still needs origin/Lambda.

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.

graph TD Source[Source Video
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

Video CDN Architecture

graph LR Origin[Origin
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

Interview Tip: Video segments are highly cacheable (immutable, large). Manifest files have low TTL (frequently updated). Edge caching reduces origin load 95%+. Adaptive bitrate switches quality based on network conditions - player measures throughput every few segments.

CDN Security

CDNs provide security layers: DDoS mitigation, WAF, bot protection, origin cloaking.

Security Features

1. DDoS Mitigation

2. Web Application Firewall (WAF)

3. Bot Protection

4. Origin Cloaking

DDoS Mitigation Flow

graph TB Attacker[Attacker
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
Interview Tip: CDN absorbs DDoS at edge (100+ Tbps capacity), only sends clean traffic to origin. Origin cloaking hides origin IP - attackers can't bypass CDN. WAF blocks app-layer attacks (SQL injection, XSS). Bot protection stops scraping without impacting legit users.

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

Interview Tip: CloudFront for AWS integration, Cloudflare for cost/security, Fastly for real-time control, Akamai for enterprise reliability. Cloudflare's flat pricing attractive for high traffic. Fastly/Cloudflare have instant purge (CloudFront takes 5-15min).

Summary