CDN Là Gì? Content Delivery Network Chi Tiết
CDN (Content Delivery Network) là hệ thống server phân tán geografically để deliver web content nhanh hơn bằng cách serve từ server gần nhất với user. Thay vì user phải fetch content từ origin server (có thể ở xa), CDN cache content tại edge servers gần user, giảm latency đáng kể.
CDN không chỉ là caching – đó là distributed network với nhiều functions: load balancing, DDoS protection, security, và edge computing. Các CDN providers lớn: Cloudflare, Akamai, AWS CloudFront, Fastly, Google Cloud CDN.
Tại Sao Cần CDN?
1. Giảm Latency
Speed of light limit: mỗi 100km tạo ~0.5ms latency. User ở Vietnam connect đến origin server ở US (~15,000km) sẽ có ~75ms base latency, chưa kể network hops. CDN edge server ở Singapore hoặc Japan có thể reduce xuống 5-15ms.
2. Reduce Origin Load
CDN cache static assets (images, CSS, JS, videos), giảm số requests đến origin server. Origin chỉ handle requests cho dynamic content hoặc cache misses. This protects origin khỏi traffic spikes.
3. High Availability
Nếu origin fail, CDN vẫn serve cached content. Multi-region distribution đảm bảo content available ngay cả khi entire data center down.
4. DDoS Protection
CDN absorb và mitigate DDoS attacks bằng cách distribute traffic across global network. Attackers phải target nhiều edge servers thay vì single origin.
5. Cost Savings
Bandwidth costs giảm đáng kể vì origin server bandwidth usage giảm. Nhiều CDN providers có transparent pricing, pay-for-what-you-use.
CDN Architecture
1. PoPs (Points of Presence)
PoPs là các data centers ở worldwide locations, chứa edge servers. Mỗi PoP có multiple servers và caches. Typical CDN có 100+ PoPs globally.
2. Origin Server
Origin là primary server nơi content được stored và served khi không có cache. CDN pull content từ origin (origin pull) hoặc origin push content đến CDN (origin push).
3. Cache Hierarchy
- Edge Cache: First level, closest to user
- Regional Cache: Middle level, larger caches serving geographic regions
- Origin Shield: Optional extra layer in front of origin
4. Anycast Routing
CDN sử dụng Anycast để route user đến nearest PoP. Tất cả PoPs share same IP address, routing infrastructure tự động direct traffic đến closest location.
How CDN Caching Works
Cache Miss Flow
- 1. User requests asset:
GET /images/logo.png - 2. CDN edge server check cache – not found
- 3. CDN fetch from origin:
GET /images/logo.png - 4. Origin returns asset với Cache-Control headers
- 5. CDN cache asset và return to user
Cache Hit Flow
- 1. User requests asset:
GET /images/logo.png - 2. CDN edge server check cache – found (cache hit)
- 3. CDN return asset directly from cache
- 4. Latency minimal, origin không load
Cache-Control Headers
| Header | Description |
|---|---|
| max-age | Seconds asset is valid (Cache-Control: max-age=86400) |
| s-maxage | Max-age for shared caches (CDN) |
| public | Can be cached by anyone |
| private | Cannot be cached by CDN (browser only) |
| no-cache | Always revalidate before serving |
| no-store | Never cache (sensitive data) |
CDN Cache Invalidation
1. TTL Expiration
Asset được serve từ cache cho đến khi max-age hết hạn. Sau đó CDN revalidate với origin trước khi serve stale hoặc refresh.
2. Purge/Invalidation API
- Manually remove specific assets từ cache
- Typically async operation (takes seconds to minutes)
- Cloudflare:
POST /zones/{zone}/purge_cache
3. Cache Tags/Bypass
Tag assets với custom identifiers, sau đó purge by tag. Useful khi need invalidate all product images, all CSS, etc.
CDN Providers Comparison
| Provider | PoPs | Strengths | Pricing |
|---|---|---|---|
| Cloudflare | 200+ | Free tier, DDoS protection, performance | Free-Enterprise |
| Akamai | 4,100+ | Enterprise, largest network | Enterprise |
| AWS CloudFront | 600+ | AWS integration, Lambda@Edge | Pay-as-you-go |
| Fastly | 300+ | Real-time cache purging, VCL | Pay-as-you-go |
| Google Cloud CDN | 100+ | GCP integration, Cloud Armor | Pay-as-you-go |
CDN với SSL
Full SSL Chain
- 1. User → CDN Edge: HTTPS (encrypt)
- 2. CDN Edge → Origin: HTTPS hoặc HTTP (configurable)
CDN SSL Options
- Shared Certificate: CDN-provided certificate (*.cdnprovider.com)
- Custom Certificate: Upload your own cert (additional cost)
- Full/End-to-End Encryption: User ↔ CDN ↔ Origin all encrypted
Cloudflare SSL Modes
- Flexible: User → CDN (HTTPS), CDN → Origin (HTTP)
- Full: User → CDN (HTTPS), CDN → Origin (HTTPS, self-signed)
- Full (strict): User → CDN (HTTPS), CDN → Origin (HTTPS, CA cert)
Edge Computing
Modern CDNs không chỉ serve static files – chúng execute code at the edge:
- Cloudflare Workers: JavaScript workers at edge, 50ms CPU time
- AWS Lambda@Edge: Lambda functions triggered by CloudFront events
- Fastly Compute@Edge: Rust/WebAssembly at edge
Edge Computing Use Cases
- A/B Testing: Serve different versions based on user location/attributes
- Authentication: Validate tokens before hitting origin
- Geolocation Routing: Redirect users to regional versions
- Bot Detection: Identify và block malicious traffic early
CDN Performance Optimization
1. Cache Static Assets
- Images, CSS, JS, fonts – long cache (1 year)
- Use cache-busting: filename với hash
app.abc123.js
2. Compression
- Gzip/Brotli compression at edge
- Modern formats: WebP, AVIF cho images; Brotli cho text
3. HTTP/2 và HTTP/3
- CDN enable HTTP/2 tự động
- HTTP/3 (QUIC) provide even better performance
4. Image Optimization
- Cloudflare Images, CloudFront Image Optimization
- Auto-convert to WebP/AVIF based on browser support
- Responsive images với srcset
CDN Security Features
DDoS Protection
CDN absorbs volumetric attacks ở edge, chỉ clean traffic đến origin. Cloudflare claims absorb attacks lên đến 2 Tbps.
WAF (Web Application Firewall)
Filter malicious traffic: SQL injection, XSS, path traversal. Cloudflare WAF, AWS WAF, Fastly WAF.
Rate Limiting
Limit requests per IP/client để prevent abuse và brute force attacks.
Bot Management
Detect và block bot traffic. Challenge browsers, identify automated tools. Cloudflare Bot Management, Akamai Bot Manager.
CDN Caching Chiến Lược
Cache Everything Possible
# HTML pages - short cache (5 minutes) Cache-Control: public, max-age=300 # Static assets - long cache (1 year) Cache-Control: public, max-age=31536000, immutable # API responses - no cache or short Cache-Control: private, no-cache
Origin Shield
Additional cache layer giữa CDN edge và origin. Reduces origin load khi many edge servers need same asset simultaneously.
Stale-While-Revalidate
Cache-Control: public, max-age=3600, stale-while-revalidate=86400
CDN Implementation Example
Cloudflare Setup
- 1. Add site to Cloudflare, update nameservers
- 2. Configure DNS: point A record to origin IP
- 3. Enable caching: Cache Rules for static content
- 4. SSL mode: Full (strict) recommended
- 5. Performance: Auto-Minify, Brotli, HTTP/2
AWS CloudFront Setup
- 1. Create CloudFront distribution
- 2. Set origin (ALB, S3, EC2)
- 3. Configure cache behavior: path pattern, TTL, headers
- 4. Attach Lambda@Edge for request/response manipulation
CDN Metrics để Monitor
| Metric | Description |
|---|---|
| Cache Hit Ratio | % requests served from cache (target: >90%) |
| Origin Request Rate | Requests forwarded to origin (lower is better) |
| Latency (TTFB) | Time to first byte |
| Bandwidth | Data transferred |
| 4xx/5xx Errors | Error rates |
Kết Luận
CDN là critical infrastructure cho modern web performance. Ngoài việc cache và deliver content nhanh hơn, CDN cung cấp security (DDoS, WAF), availability, và edge computing capabilities. Với options từ free (Cloudflare) đến enterprise (Akamai), có CDN solution cho every budget và use case.
Key takeaway: implement CDN early, cache aggressively, monitor cache hit ratio, và leverage edge computing cho beyond-caching benefits.
Các Câu Hỏi Thường Gặp (FAQ)
1. CDN có làm chậm website không?
Ngược lại, CDN làm website nhanh hơn đáng kể. CDN reduce latency bằng cách serve từ edge servers gần users. Tuy nhiên, misconfiguration có thể cause issues: cache không working, origin shield not set up, hoặc SSL handshake adds latency.