Geographically distributed network of servers that deliver content to users from the nearest location
What is CDN?
A CDN is a network of strategically placed servers (edge servers) around the world that cache and deliver content to users from the closest geographical location.
Purpose:
- Reduce Latency → Faster content delivery
- Improve Performance → Better user experience
- Reduce Server Load → Distribute traffic
- Increase Availability → Redundancy and fault tolerance
How CDN Works
Basic Flow:
1. User requests content (e.g., image, video, webpage)
2. DNS routes request to nearest CDN edge server
3. If content exists in cache → Return cached content
4. If not in cache → Fetch from origin server
5. Cache content at edge server for future requests
6. Return content to user
Architecture Diagram:
[User in NYC] → [CDN Edge NYC] → [Origin Server California]
[User in London] → [CDN Edge London] → [Origin Server California]
[User in Tokyo] → [CDN Edge Tokyo] → [Origin Server California]
CDN Components
1. Edge Servers (PoP - Point of Presence)
- Location: Major cities worldwide
- Function: Cache and serve content
- Capacity: High-performance SSD storage
- Examples: 100+ locations globally
2. Origin Server
- Source: Original content location
- Backup: Authoritative content source
- Updates: Push updates to edge servers
3. Cache Management
- TTL: Time-to-live for cached content
- Invalidation: Remove outdated content
- Prefetching: Proactively cache popular content
4. Load Balancers
- Traffic Distribution: Route to best edge server
- Health Checks: Monitor server availability
- Failover: Redirect if server fails
CDN Types
1. Traditional Pull CDN
- On-demand: Content cached when first requested
- Lazy Loading: Cache-miss triggers origin fetch
- Best For: General web content, images
User Request → Edge Server (cache miss) → Origin Server
↓ (cache content)
User Request → Edge Server (cache hit) → Direct response
2. Push CDN
- Proactive: Content pushed to edge servers
- Scheduled: Regular content updates
- Best For: Static content, scheduled releases
Origin Server → Push content → All Edge Servers
User Request → Edge Server → Cached content (always available)
3. Hybrid CDN
- Combination: Both pull and push strategies
- Intelligent: Based on content type and usage patterns
- Optimal: Best of both approaches
CDN Caching Strategies
1. Cache-Control Headers
Cache-Control: public, max-age=31536000 # 1 year
Cache-Control: private, no-store # Don't cache at all
Cache-Control: no-cache # Store, but revalidate with origin before each use
Cache-Control: public, s-maxage=3600 # CDN cache 1 hour2. Content Types & TTL
| Content Type | TTL | Reason |
|---|---|---|
| Static Images | 1 year | Rarely change |
| CSS/JS Files | 1 month | Version controlled |
| HTML Pages | 1 hour | Dynamic content |
| API Responses | 5 minutes | Real-time data |
| User Profiles | No cache | Personal data |
3. Cache Invalidation
// Purge specific file
cdn.purge('/images/logo.png');
// Purge by pattern
cdn.purge('/css/*');
// Purge by tags
cdn.purgeByTags(['product-123', 'category-electronics']);Geographic Distribution
CDN Locations (Examples)
North America:
- East Coast: New York, Atlanta, Miami
- West Coast: Los Angeles, San Francisco, Seattle
- Central: Chicago, Dallas, Denver
Europe:
- Western: London, Paris, Amsterdam, Frankfurt
- Eastern: Warsaw, Prague, Moscow
Asia-Pacific:
- East Asia: Tokyo, Seoul, Hong Kong, Singapore
- South Asia: Mumbai, Bangalore
- Oceania: Sydney, Melbourne
Routing Methods
- DNS-based: GeoDNS routes to nearest server
- Anycast: Same IP, different physical servers
- HTTP Redirect: Application-level routing
Performance Benefits
Latency Reduction
Without CDN:
User (NYC) → Server (California) = ~4000km = ~60-80ms RTT (fibre floor ~40ms)
With CDN:
User (NYC) → CDN Edge (NYC) = ~50km = a few ms RTT
Large latency reduction (exact savings depend on route)
Bandwidth Optimization
- Compression: Gzip, Brotli compression
- Image Optimization: WebP, AVIF formats
- Minification: Remove unnecessary characters
- HTTP/2: Multiplexing, header compression
Concurrent Connections
HTTP/1.1 browser limit: ~6 connections per domain
Legacy HTTP/1.1 workaround (domain sharding): multiple subdomains
- cdn1.example.com
- cdn2.example.com
- cdn3.example.com
Result: 18 concurrent connections
HTTP/2 & HTTP/3: one connection multiplexes all requests → domain sharding
is an anti-pattern (extra DNS/TLS handshakes, breaks prioritisation)
Security Features
DDoS Protection
- Traffic Filtering: Block malicious requests
- Rate Limiting: Prevent abuse
- Geographic Blocking: Restrict by country
- Bot Protection: CAPTCHA challenges
SSL/TLS Termination
User → [HTTPS] → CDN Edge → [HTTPS, origin cert validated] → Origin Server
Benefits:
- Offload SSL processing from origin
- Latest TLS versions at edge
- Certificate management
Web Application Firewall (WAF)
- SQL Injection: Block malicious SQL queries
- XSS Protection: Filter cross-site scripting
- OWASP Top 10: Protection against common attacks
Popular CDN Providers
Major Players
| Provider | Strengths | Use Cases |
|---|---|---|
| Cloudflare | Security, DNS, Edge computing | General purpose, security-focused |
| AWS CloudFront | AWS integration, global reach | AWS ecosystem, enterprise |
| Akamai | Largest network, enterprise features | Large enterprises, streaming |
| Fastly | Real-time purging, edge computing | Developer-friendly, real-time apps |
| Google Cloud CDN | GCP integration, YouTube network | Google ecosystem, video content |
| Azure CDN | Microsoft integration, enterprise | Microsoft ecosystem, enterprise |
Specialized CDNs
- Video: Wowza, JW Player, Brightcove (video platforms that run on top of CDNs, not CDNs themselves)
- Gaming: Game downloads are served by general CDNs (Akamai, CloudFront, etc.); Amazon GameLift hosts game servers and is not a CDN (Google Stadia shut down Jan 2023)
- Mobile: Akamai Ion
Implementation Examples
1. Basic CDN Setup
<!-- Before CDN -->
<img src="https://example.com/images/logo.png" alt="Logo">
<link rel="stylesheet" href="https://example.com/css/style.css">
<!-- After CDN -->
<img src="https://cdn.example.com/images/logo.png" alt="Logo">
<link rel="stylesheet" href="https://cdn.example.com/css/style.css">2. Dynamic Content Caching
// Cache API responses with short TTL
app.get('/api/products', (req, res) => {
res.set({
'Cache-Control': 'public, max-age=300', // 5 minutes
'Vary': 'Accept-Encoding'
});
// Return product data
res.json(products);
});3. Edge Side Includes (ESI)
<!-- Cached page template -->
<html>
<head>
<esi:include src="/api/user-menu" ttl="60" />
</head>
<body>
<esi:include src="/api/dynamic-content" ttl="300" />
<esi:include src="/api/footer" ttl="3600" />
</body>
</html>Monitoring & Analytics
Key Metrics
Performance Metrics:
- Cache Hit Ratio: 95%+ target
- Origin Load: Should be minimal
- Response Time: <100ms target
- Bandwidth Savings: 70%+ typical
Traffic Metrics:
- Requests per second
- Data transfer volume
- Geographic distribution
- Popular content analysis
Monitoring Tools
// CDN Analytics API example
const analytics = await cdn.getAnalytics({
startDate: '2024-01-01',
endDate: '2024-01-31',
metrics: ['requests', 'bandwidth', 'cacheRatio'],
groupBy: ['country', 'contentType']
});
console.log('Cache Hit Ratio:', analytics.cacheRatio);
console.log('Bandwidth Saved:', analytics.bandwidthSaved);Best Practices
1. Content Strategy
- ✅ Static Assets: Always use CDN
- ✅ Dynamic Content: Cache with short TTL
- ✅ User-Specific: Avoid caching personal data
- ✅ API Responses: Cache public data only
2. Performance Optimization
- ✅ HTTP/2: Enable for multiplexing
- ✅ Compression: Gzip/Brotli for text content
- ✅ Image Optimization: WebP/AVIF formats
- ✅ Minification: CSS, JS, HTML
3. Cache Management
- ✅ Versioning: Use cache-busting for updates
- ✅ Purging: Automate cache invalidation
- ✅ Headers: Set appropriate Cache-Control
- ✅ Monitoring: Track cache hit ratios
4. Security
- ✅ HTTPS: Always use SSL/TLS
- ✅ Headers: Set security headers
- ✅ Access Control: Restrict sensitive content
- ✅ DDoS: Enable protection features
Common Pitfalls
1. Cache Invalidation Issues
Problem: Stale content served to users
Solution: Implement proper versioning and purging
2. Dynamic Content Caching
Problem: Caching user-specific data
Solution: Use proper cache headers and vary headers
3. Origin Server Overload
Problem: Cache miss storms during traffic spikes
Solution: Implement cache warming and proper TTLs
4. Geographic Routing Issues
Problem: Users routed to distant edge servers
Solution: Verify DNS configuration and CDN settings
Use Cases
1. E-commerce Websites
- Product images and catalogs
- Static CSS/JS files
- Product recommendation APIs
- Geographic price optimization
2. Media & Entertainment
- Video streaming (Netflix, YouTube)
- Image galleries (Instagram, Pinterest)
- Audio streaming (Spotify, Apple Music)
- Live event broadcasting
3. Gaming
- Game asset downloads
- (Not real-time multiplayer data: that goes to game servers, not the CDN)
- Leaderboards and statistics
- Mobile game content
4. SaaS Applications
- Application assets
- Documentation sites
- API responses
- User interface components
CDNs are essential for modern web applications, providing faster content delivery, improved user experience, and reduced server costs. Choose the right CDN provider based on your specific needs, budget, and geographic requirements.