CDN (Content Delivery Network)
CDN Nədir?
CDN (Content Delivery Network) - content-i istifadəçilərə coğrafi olaraq yaxın server-lərdən çatdırmaq üçün istifadə olunan geografik bölgülərə yerləşdirilmiş server-lər şəbəkəsidir.
Məqsədlər:
- Latency-nin azaldılması
- Bandwidth-in optimizasiyası
- Load-un paylaşdırılması
- High availability
- DDoS protection
- Global reach
graph TD
A[Origin Server<br/>US East] --> B[CDN Network]
B --> C[Edge Server<br/>Europe]
B --> D[Edge Server<br/>Asia]
B --> E[Edge Server<br/>US West]
B --> F[Edge Server<br/>Australia]
C --> G[User Europe]
D --> H[User Asia]
E --> I[User US]
F --> J[User Australia]
style A fill:#FFD700
style B fill:#87CEEB
style C fill:#90EE90
style D fill:#90EE90
style E fill:#90EE90
style F fill:#90EE90
CDN İş Prinsipi
Traditional vs CDN
graph LR
subgraph Without CDN
A1[User Japan] -->|8000 km<br/>200ms| B1[Origin Server<br/>US]
A2[User Europe] -->|6000 km<br/>150ms| B1
A3[User Australia] -->|12000 km<br/>300ms| B1
end
subgraph With CDN
C1[User Japan] -->|100 km<br/>10ms| D1[Edge Japan]
C2[User Europe] -->|100 km<br/>10ms| D2[Edge Europe]
C3[User Australia] -->|100 km<br/>10ms| D3[Edge Australia]
D1 -.Cache Miss.-> E1[Origin US]
D2 -.Cache Miss.-> E1
D3 -.Cache Miss.-> E1
end
style B1 fill:#FF6B6B
style D1 fill:#90EE90
style D2 fill:#90EE90
style D3 fill:#90EE90
CDN Request Flow
sequenceDiagram
participant User
participant DNS
participant Edge as Edge Server
participant Origin as Origin Server
User->>DNS: example.com
DNS->>User: edge-server-nearby.cdn.com
User->>Edge: GET /image.jpg
alt Cache Hit
Edge->>User: Return cached content
Note over Edge: Fast response<br/>No origin request
else Cache Miss
Edge->>Origin: GET /image.jpg
Origin->>Edge: image.jpg
Note over Edge: Cache content
Edge->>User: image.jpg
end
CDN Architecture
PoP (Point of Presence)
PoP - CDN şəbəkəsinin bir coğrafi location-dakı physical datacenter-i.
graph TD
A[CDN Network] --> B[North America PoP]
A --> C[Europe PoP]
A --> D[Asia PoP]
A --> E[South America PoP]
B --> B1[Edge Servers]
B --> B2[Cache Servers]
B --> B3[Load Balancers]
C --> C1[Edge Servers]
C --> C2[Cache Servers]
D --> D1[Edge Servers]
D --> D2[Cache Servers]
style A fill:#FFD700
CDN Components
graph TD
A[User Request] --> B[DNS Resolution<br/>GeoDNS]
B --> C[Edge Server]
C --> D{Cache Status}
D -->|HIT| E[Return from Cache]
D -->|MISS| F[Fetch from Origin]
F --> G[Origin Shield]
G --> H[Origin Server]
H --> I[Store in Cache]
I --> E
C --> J[WAF/Security]
C --> K[DDoS Protection]
C --> L[Analytics]
style C fill:#90EE90
style G fill:#87CEEB
Cache Strategies
1. Cache Headers
HTTP Cache Headers:
HTTP/1.1 200 OK
Content-Type: image/jpeg
Cache-Control: public, max-age=31536000
Expires: Thu, 31 Dec 2025 23:59:59 GMT
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT
Cache-Control Directives:
| Directive | Məna |
|---|---|
public | Hər kəs cache edə bilər (CDN, browser) |
private | Yalnız browser cache edə bilər |
no-cache | Revalidation tələb olunur |
no-store | Heç cache edilməməlidir |
max-age=3600 | 1 saat cache et |
s-maxage=7200 | Shared cache (CDN) üçün 2 saat |
must-revalidate | Expire olduqda mütləq yoxla |
immutable | Heç vaxt dəyişməyəcək |
2. Cache Levels
graph TD
A[User Request] --> B[Browser Cache<br/>L1]
B -->|Cache Miss| C[Edge Server Cache<br/>L2]
C -->|Cache Miss| D[Regional Cache<br/>L3]
D -->|Cache Miss| E[Origin Shield<br/>L4]
E -->|Cache Miss| F[Origin Server]
style B fill:#FFE4E1
style C fill:#90EE90
style D fill:#87CEEB
style E fill:#DDA0DD
style F fill:#FFD700
3. Cache Key
Cache key - content-in cache-də unique identifikatorudur.
cache_key = hash(
scheme + // https
host + // example.com
path + // /images/logo.png
query_params + // ?width=100&quality=high
custom_headers // Accept-Language, Cookie (optional)
)
Example:
GET /api/users?page=2&limit=10
Accept-Language: en-US
Cookie: session=abc123
Cache Key: https://example.com/api/users?page=2&limit=10
4. Cache Invalidation
Problem: Content dəyişdikdə köhnə cache təmizlənməlidir.
sequenceDiagram
participant Admin
participant Origin
participant CDN
participant Users
Admin->>Origin: Update content
Note over Origin: New version available
Admin->>CDN: Purge cache<br/>/images/logo.png
Note over CDN: Remove from cache
Users->>CDN: Request logo.png
CDN->>Origin: Fetch new version
Origin->>CDN: New content
CDN->>Users: New content
Note over CDN: Cache new version
Invalidation Methods:
Purge (Hard Delete)
# Delete specific file
curl -X PURGE https://cdn.example.com/images/logo.png
# Purge by tag
curl -X POST https://api.cdn.com/purge \
-d '{"tags": ["homepage", "products"]}'
Soft Purge (Mark as stale)
# Mark as stale, revalidate on next request
curl -X PURGE https://cdn.example.com/images/logo.png \
-H "Fastly-Soft-Purge: 1"
TTL Expiration
Cache-Control: max-age=3600 # Auto-expire after 1 hour
Versioning
# Old: /assets/style.css
# New: /assets/style.v2.css
# Or: /assets/style.css?v=2
5. Cache Hit Ratio
Məqsəd: Cache-dən cavab verə bilmə nisbəti.
Cache Hit Ratio = (Cache Hits / Total Requests) × 100%
Example:
1000 requests total
800 served from cache (hits)
200 from origin (misses)
Hit Ratio = (800 / 1000) × 100% = 80%
Optimization:
- Longer TTL
- Better cache key design
- Prewarming cache
- Origin shield
pie title Cache Hit Ratio (Goal: 80%+)
"Cache Hits" : 80
"Cache Misses" : 15
"Uncacheable" : 5
CDN Content Types
1. Static Content
Perfect for CDN:
- Images (JPEG, PNG, WebP)
- CSS, JavaScript files
- Fonts
- Videos (VOD)
- Documents (PDF)
# CDN configuration for static files
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff2)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
2. Dynamic Content
Cacheable with conditions:
- API responses (with proper headers)
- Personalized content (with Vary header)
- HTML pages (with ESI)
# API response with cache
HTTP/1.1 200 OK
Cache-Control: public, max-age=300, s-maxage=600
Vary: Accept-Encoding, Accept-Language
3. Streaming Content
Live və VOD:
graph TD
A[Live Stream Source] --> B[Origin Server<br/>Transcoding]
B --> C[CDN Edge<br/>HLS/DASH]
C --> D[User 1<br/>1080p]
C --> E[User 2<br/>720p]
C --> F[User 3<br/>480p]
style B fill:#FFD700
style C fill:#90EE90
Streaming Protocols:
- HLS (HTTP Live Streaming) - Apple
- DASH (Dynamic Adaptive Streaming) - Standard
- RTMP - Legacy live streaming
Edge Computing
Edge Computing - CDN edge server-lərində kod icra etmək.
graph LR
A[User Request] --> B[Edge Server]
B --> C[Edge Function<br/>Code Execution]
C --> D{Logic}
D -->|Auth| E[Check JWT]
D -->|Personalize| F[A/B Testing]
D -->|Transform| G[Image Resize]
D -->|Route| H[Blue-Green Deploy]
E --> I[Response]
F --> I
G --> I
H --> I
I --> A
style C fill:#90EE90
Edge Functions Use Cases
1. Image Optimization
// Cloudflare Worker - Image resize
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url)
const width = url.searchParams.get('width') || 800
// Fetch original image
const response = await fetch(url.origin + url.pathname)
// Resize using Cloudflare Image Resizing
return new Response(response.body, {
headers: {
...response.headers,
'cf-image-width': width,
'cache-control': 'public, max-age=31536000'
}
})
}
2. A/B Testing
// Edge A/B testing
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const cookie = request.headers.get('cookie')
// Assign variant
let variant = 'A'
if (cookie && cookie.includes('variant=B')) {
variant = 'B'
} else if (Math.random() < 0.5) {
variant = 'B'
}
// Fetch variant-specific content
const url = new URL(request.url)
url.pathname = `/variant-${variant}${url.pathname}`
const response = await fetch(url)
// Set cookie
const newResponse = new Response(response.body, response)
newResponse.headers.set('Set-Cookie', `variant=${variant}; Path=/; Max-Age=86400`)
return newResponse
}
3. Authentication
// Edge authentication
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const token = request.headers.get('Authorization')
if (!token) {
return new Response('Unauthorized', { status: 401 })
}
// Verify JWT at edge
const isValid = await verifyJWT(token)
if (!isValid) {
return new Response('Invalid token', { status: 403 })
}
// Forward to origin
return fetch(request)
}
4. Geolocation Routing
// Route based on location
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const country = request.cf.country // Cloudflare provides this
let origin
switch(country) {
case 'JP':
case 'CN':
case 'KR':
origin = 'https://asia.example.com'
break
case 'GB':
case 'DE':
case 'FR':
origin = 'https://eu.example.com'
break
default:
origin = 'https://us.example.com'
}
const url = new URL(request.url)
url.host = new URL(origin).host
return fetch(url)
}
CDN Security
1. DDoS Protection
graph TD
A[Attack Traffic<br/>1M req/s] --> B[CDN Edge<br/>DDoS Mitigation]
B --> C{Filter}
C -->|Malicious| D[Block/Rate Limit]
C -->|Legitimate| E[Pass to Origin]
E --> F[Origin Server<br/>Normal load]
D --> G[Challenge Page<br/>Captcha]
style B fill:#90EE90
style D fill:#FF6B6B
style F fill:#FFD700
2. WAF (Web Application Firewall)
Protection against:
- SQL Injection
- XSS (Cross-Site Scripting)
- CSRF
- Bot traffic
- Bad user agents
# WAF Rule example
rules:
- id: block_sql_injection
pattern: (?i)(union|select|insert|update|delete|drop).*from
action: block
- id: rate_limit_api
path: /api/*
limit: 100 req/minute
action: challenge
- id: block_bad_bots
user_agent: (curl|wget|python-requests)
action: block
3. Token Authentication
Signed URLs:
import hmac
import hashlib
import time
def generate_signed_url(base_url, secret_key, expiration=3600):
expires = int(time.time()) + expiration
# Create signature
message = f"{base_url}{expires}"
signature = hmac.new(
secret_key.encode(),
message.encode(),
hashlib.sha256
).hexdigest()
# Build URL
return f"{base_url}?expires={expires}&signature={signature}"
# Example
url = generate_signed_url(
"https://cdn.example.com/video.mp4",
"my-secret-key",
3600 # 1 hour
)
print(url)
# https://cdn.example.com/video.mp4?expires=1698765432&signature=abc123...
Validation at CDN:
// Validate signed URL
function validateSignedURL(request, secretKey) {
const url = new URL(request.url)
const expires = url.searchParams.get('expires')
const signature = url.searchParams.get('signature')
// Check expiration
if (parseInt(expires) < Date.now() / 1000) {
return false
}
// Verify signature
const message = url.origin + url.pathname + expires
const expectedSignature = hmac_sha256(message, secretKey)
return signature === expectedSignature
}
4. HTTPS Everywhere
graph LR
A[User] -->|HTTPS| B[CDN Edge]
B -->|HTTPS| C[Origin Server]
style B fill:#90EE90
Benefits:
- Data encryption
- MITM protection
- SEO boost
- HTTP/2 support
CDN Performance Optimization
1. HTTP/2 & HTTP/3
HTTP/2:
- Multiplexing
- Header compression
- Server push
HTTP/3 (QUIC):
- UDP-based
- Faster connection
- Better mobile performance
graph TD
A[HTTP/1.1] --> A1[6 Requests<br/>Serial]
A1 --> A2[Slow]
B[HTTP/2] --> B1[6 Requests<br/>Multiplexed]
B1 --> B2[Faster]
C[HTTP/3] --> C1[6 Requests<br/>QUIC]
C1 --> C2[Fastest]
style C2 fill:#90EE90
2. Compression
# Brotli compression (better than gzip)
brotli on;
brotli_comp_level 6;
brotli_types text/plain text/css application/javascript application/json;
# Gzip fallback
gzip on;
gzip_types text/plain text/css application/javascript;
Compression Ratios:
- Text files: 70-90% reduction
- JavaScript: 60-80% reduction
- Images (already compressed): 0-10%
3. Image Optimization
graph TD
A[Original Image<br/>5 MB JPEG] --> B[CDN Optimization]
B --> C[Format Conversion]
C --> D[WebP 1.2 MB<br/>or AVIF 0.8 MB]
B --> E[Compression]
E --> F[Quality 85%]
B --> G[Responsive]
G --> H[Multiple sizes]
style D fill:#90EE90
Automatic optimization:
<!-- Cloudflare Polish / Cloudinary -->
<img src="https://cdn.example.com/image.jpg"
srcset="https://cdn.example.com/image.jpg?w=400 400w,
https://cdn.example.com/image.jpg?w=800 800w,
https://cdn.example.com/image.jpg?w=1200 1200w"
sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px">
4. Prefetching & Preloading
<!-- DNS prefetch -->
<link rel="dns-prefetch" href="https://cdn.example.com">
<!-- Preconnect -->
<link rel="preconnect" href="https://cdn.example.com">
<!-- Preload critical resources -->
<link rel="preload" href="https://cdn.example.com/main.css" as="style">
<link rel="preload" href="https://cdn.example.com/app.js" as="script">
<!-- Prefetch next page -->
<link rel="prefetch" href="https://cdn.example.com/next-page.html">
CDN Analytics & Monitoring
Key Metrics:
graph TD
A[CDN Metrics] --> B[Traffic<br/>Requests, Bandwidth]
A --> C[Performance<br/>Latency, TTFB]
A --> D[Cache<br/>Hit Ratio, Misses]
A --> E[Security<br/>Blocked Requests]
A --> F[Errors<br/>4xx, 5xx]
A --> G[Geographic<br/>User Distribution]
style A fill:#FFD700
Monitoring Dashboard:
┌─────────────────────────────────────┐
│ CDN Performance Dashboard │
├─────────────────────────────────────┤
│ Requests/sec: 45,000 │
│ Bandwidth: 2.5 GB/s │
│ Cache Hit Ratio: 87% │
│ Avg Latency: 45ms │
│ P95 Latency: 120ms │
│ Origin Requests: 5,850/s │
│ Error Rate: 0.02% │
├─────────────────────────────────────┤
│ Top Locations: │
│ 🌍 US: 35% │
│ 🌍 EU: 28% │
│ 🌍 Asia: 25% │
│ 🌍 Other: 12% │
└─────────────────────────────────────┘
Popular CDN Providers
Cloudflare
Xüsusiyyətlər:
- 300+ PoPs worldwide
- Free tier available
- DDoS protection included
- Edge workers (serverless)
- WAF
- Analytics
Use cases:
- Websites
- APIs
- Video streaming
AWS CloudFront
Xüsusiyyətlər:
- AWS ecosystem integration
- Lambda@Edge
- 450+ PoPs
- Pay-as-you-go
- Origin shield
Use cases:
- AWS-hosted applications
- S3 static websites
- Video streaming
Fastly
Xüsusiyyətlər:
- Instant purge (150ms)
- VCL (Varnish) configuration
- Real-time analytics
- Edge compute
- Advanced caching
Use cases:
- High-traffic sites
- Real-time applications
- Media delivery
Akamai
Xüsusiyyətlər:
- Largest CDN (300,000+ servers)
- Enterprise-focused
- Advanced security
- IoT support
Use cases:
- Enterprise applications
- Large-scale streaming
- Gaming
Others
- Azure CDN - Microsoft ecosystem
- Google Cloud CDN - GCP integration
- KeyCDN - Budget-friendly
- BunnyCDN - Performance-focused
- StackPath - Edge computing
CDN Configuration Example
Cloudflare Page Rules
page_rules:
- name: cache_static
url_pattern: example.com/static/*
settings:
cache_level: Cache Everything
edge_cache_ttl: 1 month
browser_cache_ttl: 1 day
- name: api_caching
url_pattern: example.com/api/v1/products
settings:
cache_level: Cache Everything
edge_cache_ttl: 5 minutes
bypass_cache_on_cookie: session=*
- name: no_cache_admin
url_pattern: example.com/admin/*
settings:
cache_level: Bypass
NGINX Origin Configuration
server {
listen 80;
server_name origin.example.com;
# Only allow CDN IPs
allow 103.21.244.0/22; # Cloudflare IPs
deny all;
location /static/ {
root /var/www;
# Cache headers
expires 1y;
add_header Cache-Control "public, immutable";
# Security
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "DENY";
}
location /api/ {
proxy_pass http://backend;
# Vary header for proper caching
add_header Vary "Accept-Encoding, Accept-Language";
# Cache control
add_header Cache-Control "public, max-age=300";
}
}
Multi-CDN Strategy
Məqsəd: Bir neçə CDN provider istifadə etmək.
graph TD
A[DNS / Traffic Manager] --> B{Route}
B -->|Primary| C[CDN 1<br/>Cloudflare]
B -->|Secondary| D[CDN 2<br/>Fastly]
B -->|Failover| E[CDN 3<br/>AWS CloudFront]
C --> F[Origin Servers]
D --> F
E --> F
style A fill:#FFD700
Benefits:
- No vendor lock-in
- Better global coverage
- Failover capability
- Cost optimization
- Performance comparison
Best Practices
-
Caching Strategy:
- Set appropriate TTLs
- Use cache tags
- Implement versioning
- Monitor hit ratio (target: 80%+)
-
Security:
- Always use HTTPS
- Enable WAF
- Implement rate limiting
- Use signed URLs for private content
-
Performance:
- Enable compression (Brotli/Gzip)
- Use HTTP/2 or HTTP/3
- Optimize images
- Minimize origin requests
-
Monitoring:
- Track cache hit ratio
- Monitor latency (P50, P95, P99)
- Alert on high error rates
- Analyze geographic performance
-
Cost Optimization:
- Increase cache hit ratio
- Use origin shield
- Compress content
- Right-size TTLs
- Consider multi-CDN for arbitrage
-
Origin Protection:
- Restrict access to CDN IPs only
- Implement rate limiting
- Use origin shield
- Configure proper health checks
Troubleshooting
Common Issues:
1. Low Cache Hit Ratio:
- Check TTL values
- Verify cache headers
- Look for query string issues
- Review Vary headers
2. High Latency:
- Check origin performance
- Verify PoP proximity
- Look for cache misses
- Analyze TCP/SSL handshake
3. Stale Content:
- Purge cache
- Check TTL expiration
- Verify Last-Modified headers
- Implement cache invalidation
4. Origin Overload:
- Enable origin shield
- Increase TTLs
- Implement rate limiting
- Scale origin servers
Əlaqəli Mövzular
- Load Balancing
- HTTP/HTTPS Protocols
- Caching Strategies
- DNS and GeoDNS
- DDoS Protection
- Image Optimization
- Video Streaming
- Edge Computing
- Web Performance Optimization