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 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. CDN edge server ở Singapore hoặc Japan giảm xuống 5-15ms.
- 2. Giảm 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.
- 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. Tiết kiệm chi phí: 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
PoPs (Points of Presence)
PoPs là các data centers ở worldwide locations, chứa edge servers và caches. Mỗi PoP có multiple servers. Typical CDN có 100+ PoPs globally.
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).
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
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
- 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.
- Purge/Invalidation API: Manually remove specific assets từ cache. Typically async operation (takes seconds to minutes). Cloudflare:
POST /zones/{zone}/purge_cache - 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: User → CDN Edge: HTTPS (encrypt). CDN Edge → Origin: HTTPS hoặc HTTP (configurable).
- 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
- Cache Static Assets: Images, CSS, JS, fonts — long cache (1 year). Use cache-busting: filename với hash
app.abc123.js - Compression: Gzip/Brotli compression at edge. Modern formats: WebP, AVIF cho images; Brotli cho text.
- HTTP/2 và HTTP/3: CDN enable HTTP/2 tự động. HTTP/3 (QUIC) provide even better performance.
- Image Optimization: Cloudflare Images, CloudFront Image Optimization. Auto-convert to WebP/AVIF based on browser support.
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.
- 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.
CDN Caching Chiến lược
# 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 # Stale-While-Revalidate Cache-Control: public, max-age=3600, stale-while-revalidate=86400
Stale-While-Revalidate cho phép serve stale content trong khi revalidate ở background. User không experience delay khi cache expires.
Origin Shield
Additional cache layer giữa CDN edge và origin. Reduces origin load khi many edge servers need same asset simultaneously.
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 |
FAQ – Các câu hỏi thường gặp
- 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. Misconfiguration có thể cause issues: cache không working, origin shield not set up, hoặc SSL handshake adds latency.
- Khi nào nên dùng CDN? Ngay khi có traffic từ multiple geographic locations. Nếu audience ở Vietnam và origin ở US, CDN là must-have. Ngay cả local audiences benefit từ CDN’s caching và security features.
- CDN có bảo mật không? Có, CDN cung cấp multiple security layers: DDoS protection, WAF, bot management, SSL/TLS encryption. Tuy nhiên, CDN không thay thế proper application security — vẫn cần input validation, authentication, authorization.
- Làm sao test CDN performance? Sử dụng WebPageTest hoặc GTmetrix để so sánh before/after CDN. Check “Cache Hit Ratio” trong CDN dashboard. Monitor Time to First Byte (TTFB) — should be < 200ms từ edge.
- Cloudflare Free đủ dùng không? Đủ cho most small to medium websites. Cloudflare Free includes DDoS protection, global CDN, SSL, basic performance optimization. Pro ($20/tháng) thêm image optimization, mobile redirect, advanced caching.
Tìm hiểu thêm về các chủ đề liên quan trên vnhte.com:
- SSL/TLS HTTPS là gì? — Bảo mật website toàn diện
- VPS, VDS, Dedicated Server, Cloud Hosting — Phân biệt các loại hosting
- Monitoring và Logging là gì? — Monitor CDN metrics