CDN (Content Delivery Network) is a distributed network infrastructure designed to deliver web content to users in the fastest way possible. In this article, we'll examine how CDN works in a lab environment.
What is CDN?
CDN caches static content (images, CSS, JS, video) on geographically distributed servers (edge servers), delivering it from the closest location to users.
Core Components
- Origin Server: Server where original content resides
- Edge Servers: Distributed servers where content is cached
- PoP (Point of Presence): Data centers containing edge servers
- DNS: System that routes users to the nearest edge server
Lab Environment Setup
CDN Simulation with Docker
# Origin server (Nginx)
docker run -d --name origin-server \
-p 8080:80 \
-v $(pwd)/content:/usr/share/nginx/html \
nginx:alpine
# Edge server 1 (Istanbul)
docker run -d --name edge-istanbul \
-p 8081:80 \
-e ORIGIN_URL=http://origin-server:80 \
nginx:alpine
# Edge server 2 (Frankfurt)
docker run -d --name edge-frankfurt \
-p 8082:80 \
-e ORIGIN_URL=http://origin-server:80 \
nginx:alpine
Nginx Cache Configuration
http {
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m;
server {
listen 80;
server_name edge.example.com;
location / {
proxy_cache my_cache;
proxy_cache_valid 200 60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://origin-server;
}
}
}
Cache Strategies
Cache-Control Headers
# Long-term cache for static files
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# Short-term cache for HTML
location ~* \.(html)$ {
expires 5m;
add_header Cache-Control "public, must-revalidate";
}
Purge/Invalidation
# Clear cache (Cloudflare API)
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/purge_cache" \
-H "Authorization: Bearer {api_token}" \
-H "Content-Type: application/json" \
--data '{"files":["https://example.com/image.jpg"]}'
Real World Testing
RTT (Round Trip Time) Comparison
# Without CDN
time curl -o /dev/null -s -w "%{time_total}\n" http://origin-server.com/image.jpg
# Result: 450ms
# With CDN
time curl -o /dev/null -s -w "%{time_total}\n" http://cdn.example.com/image.jpg
# Result: 45ms
Cache Hit Ratio
# Nginx cache stats
curl -s http://edge-server/nginx_status | grep cache
# cache_hits: 9876
# cache_misses: 234
# cache_hit_ratio: 97.7%
CloudFlare Workers
Run JavaScript at the edge:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const cache = caches.default
let response = await cache.match(request)
if (!response) {
response = await fetch(request)
// Cache for 1 hour
const headers = new Headers(response.headers)
headers.set('Cache-Control', 'max-age=3600')
response = new Response(response.body, {
status: response.status,
headers: headers
})
event.waitUntil(cache.put(request, response.clone()))
}
return response
}
Load Balancing
Routing with GeoDNS
; For Istanbul users
edge-tr.example.com. 300 IN A 185.10.10.10
; For European users
edge-eu.example.com. 300 IN A 195.20.20.20
; Global fallback
edge.example.com. 300 IN CNAME edge-eu.example.com.
Monitoring
Grafana Dashboard
# Cache hit rate
rate(nginx_http_cache_hits_total[5m]) /
rate(nginx_http_cache_total[5m]) * 100
# Average response time
histogram_quantile(0.95,
rate(nginx_http_request_duration_seconds_bucket[5m]))
# Bandwidth saved
(rate(nginx_http_cache_hits_total[5m]) * avg(response_size)) / 1024 / 1024
Best Practices
- Aggressive Caching: Cache static content for long periods
- Version Control: Add hash to file names (app.v1.2.3.css)
- Gzip Compression: Compress all text-based files
- HTTP/2: Use multiplexing and server push
- Image Optimization: Prefer WebP format
Cost Analysis
With CDN usage:
- Origin server load: 95% reduction
- Bandwidth cost: 70% reduction
- TTFB (Time to First Byte): 80% improvement
- Page load speed: 3x faster
Conclusion
CDN is essential for modern web applications. With proper cache strategies and edge computing, both performance and cost optimization can be achieved.
"Every millisecond counts in user experience. CDN makes those milliseconds matter."