CloudFront là gì?
Amazon CloudFront là dịch vụ mạng phân phối nội dung (Content Delivery Network — CDN) toàn cầu của AWS. CloudFront phân phối dữ liệu, video, ứng dụng và API đến người dùng cuối với độ trễ thấp và tốc độ truyền tải cao thông qua mạng lưới hơn 600+ Points of Presence (PoPs) trên toàn thế giới.
Use Cases phổ biến
- Static Website Acceleration: Phân phối HTML, CSS, JS, hình ảnh từ S3 qua CloudFront
- Dynamic Content Delivery: Tăng tốc API responses, dynamic pages từ ALB/EC2
- Video Streaming: Live streaming và VOD (Video on Demand) với HLS, DASH
- Software Distribution: Phân phối packages, game patches, firmware updates
- API Acceleration: Giảm latency cho REST/GraphQL API qua edge routing
- Security at Edge: Chặn DDoS, bot, geo-restriction trước khi request đến origin
So sánh CloudFront vs các CDN khác
| Tiêu chí | CloudFront | Cloudflare | Akamai |
|---|---|---|---|
| Edge Locations | 600+ PoPs | 300+ PoPs | 4,000+ PoPs |
| Tích hợp AWS | Native | Qua API/DNS | Qua API/DNS |
| Edge Computing | Lambda@Edge, CF Functions | Workers | EdgeWorkers |
| DDoS Protection | Shield Standard (miễn phí) | Có (miễn phí) | Có (trả phí) |
| Free Tier | 1 TB/tháng (12 tháng đầu) | Unlimited (plan free) | Không |
| Origin Shield | Có | Tiered Cache | SureRoute |
Kiến trúc CloudFront
CloudFront hoạt động dựa trên kiến trúc 3 tầng: Edge Locations, Regional Edge Caches và Origin. Khi người dùng request nội dung, CloudFront tự động route đến edge location gần nhất thông qua AWS global network.
Edge Locations
Edge Locations là các data center nhỏ nằm rải rác khắp thế giới, nơi CloudFront cache nội dung. Khi người dùng request, CloudFront route đến edge location gần nhất dựa trên latency.
- 600+ PoPs tại hơn 90 thành phố, 47 quốc gia
- Mỗi edge location có cache riêng, xử lý SSL termination
- CloudFront Functions chạy tại tất cả edge locations
- Tự động scale theo traffic — không cần provision
Regional Edge Caches
Regional Edge Caches là tầng cache trung gian giữa Edge Locations và Origin. Chúng có dung lượng cache lớn hơn, giúp giữ nội dung lâu hơn trước khi bị evict.
- 13 Regional Edge Caches trên toàn cầu
- Cache size lớn hơn → content tồn tại lâu hơn
- Lambda@Edge chạy tại regional edge caches
- Giảm tải cho origin khi nhiều edge locations cùng miss cache
Origin Types
| Origin Type | Mô tả | Use Case |
|---|---|---|
| S3 Bucket | Static files (HTML, CSS, JS, images) | Static website, media |
| ALB / ELB | Application Load Balancer (phải public) | Dynamic web app, API |
| EC2 Instance | Instance trực tiếp (phải public IP) | Custom web server |
| API Gateway | REST/HTTP API endpoint | Serverless API |
| MediaStore | AWS media services | Video streaming |
| Custom HTTP | Bất kỳ HTTP server nào | Hybrid / multi-cloud |
Distributions
Một Distribution là đơn vị cấu hình chính của CloudFront. Mỗi distribution có một domain name duy nhất (vd: d1234abcd.cloudfront.net) và chứa toàn bộ cấu hình về origins, cache behaviors, SSL, security.
Các loại Distribution
| Loại | Trạng thái | Mô tả |
|---|---|---|
| Web Distribution | Active | Phân phối nội dung qua HTTP/HTTPS. Hỗ trợ static + dynamic content, WebSocket, streaming. |
| RTMP Distribution | Deprecated | Streaming media qua RTMP protocol. Đã ngừng hỗ trợ từ 12/2020. Dùng HLS/DASH thay thế. |
Origin Groups — Failover
Origin Groups cho phép cấu hình automatic failover giữa primary và secondary origin:
// Khi primary origin trả về 500/502/503/504 // → CloudFront tự động chuyển sang secondary { "OriginGroup": { "Id": "my-origin-group", "FailoverCriteria": { "StatusCodes": { "Items": [500, 502, 503, 504] } }, "Members": { "Items": [ { "OriginId": "primary-s3-us-east-1" }, { "OriginId": "secondary-s3-eu-west-1" } ] } } }
InProgress sang Deployed.
Cache Behaviors
Cache Behaviors là thành phần quan trọng nhất trong cấu hình CloudFront. Mỗi behavior định nghĩa cách CloudFront xử lý request dựa trên path pattern, bao gồm: origin nào sẽ nhận request, cách cache, headers/cookies/query strings nào được forward.
Path Pattern Matching
CloudFront đánh giá path patterns theo thứ tự từ trên xuống. Request khớp với pattern đầu tiên sẽ được xử lý bởi behavior tương ứng. Nếu không khớp pattern nào → dùng Default (*) behavior.
| Path Pattern | Ví dụ URL khớp | Origin | Ghi chú |
|---|---|---|---|
/api/* | /api/users, /api/v2/orders | ALB | Forward all headers, no cache |
/images/*.jpg | /images/photo.jpg | S3 | Cache lâu, compress |
/static/* | /static/app.js, /static/style.css | S3 | Immutable, TTL dài |
/video/* | /video/intro.mp4 | MediaStore | Streaming optimized |
Default (*) | Tất cả URL còn lại | S3 | Fallback behavior |
TTL (Time to Live)
TTL quyết định thời gian CloudFront giữ object trong cache trước khi kiểm tra lại origin:
| Cấu hình | Giá trị | Mô tả |
|---|---|---|
| Minimum TTL | 0 giây (mặc định) | Thời gian tối thiểu cache, bất kể origin header |
| Default TTL | 86,400 giây (24h) | Áp dụng khi origin không gửi Cache-Control/Expires |
| Maximum TTL | 31,536,000 giây (365 ngày) | Giới hạn trên, dù origin header yêu cầu lâu hơn |
- Nếu origin gửi
Cache-Control: max-age=3600→ CloudFront dùng 3600s (nếu nằm trong min-max range) - Nếu origin gửi
Cache-Control: no-cachehoặcno-store→ CloudFront vẫn cache nhưng revalidate mỗi request - Nếu origin không gửi header nào → dùng Default TTL
Cache-Control: s-maxageđược ưu tiên hơnmax-agecho shared caches (CDN)
Forwarded Values — Cache Key
CloudFront tạo cache key từ URL + các giá trị bạn chọn forward. Càng nhiều giá trị forward → cache key càng unique → cache hit rate giảm.
Headers
- None (khuyến nghị cho static): Không forward header → cache key chỉ dựa trên URL → hit rate cao nhất
- Whitelist: Forward một số headers cụ thể (vd:
Accept-Language,Authorization) - All: Forward tất cả headers → mỗi request unique → không cache (dùng cho dynamic content)
Query Strings
- None: Bỏ qua query strings →
/page?v=1và/page?v=2cùng cache key - Whitelist: Chỉ include một số params (vd:
id,lang) - All: Include tất cả query strings vào cache key
- All-Except: Include tất cả trừ một số params
Cookies
- None (khuyến nghị): Không forward cookies → tốt cho static content
- Whitelist: Forward cookies cụ thể (vd:
session_id) - All: Forward tất cả cookies → cache key rất unique
Cache Policy vs Origin Request Policy
- Quyết định cache key gồm những gì
- Cấu hình TTL (min, default, max)
- Headers, cookies, query strings nào tham gia cache key
- Compression support (Gzip, Brotli)
- Managed policies: CachingOptimized, CachingDisabled
- Quyết định gửi gì đến origin khi cache miss
- Forward thêm headers, cookies, query strings
- Không ảnh hưởng cache key
- Managed policies: AllViewer, CORS-S3Origin
- Dùng khi origin cần thông tin mà cache key không cần
# Tạo custom cache policy
aws cloudfront create-cache-policy \
--cache-policy-config '{
"Name": "MyCustomCachePolicy",
"DefaultTTL": 86400,
"MinTTL": 1,
"MaxTTL": 31536000,
"ParametersInCacheKeyAndForwardedToOrigin": {
"EnableAcceptEncodingGzip": true,
"EnableAcceptEncodingBrotli": true,
"HeadersConfig": {
"HeaderBehavior": "whitelist",
"Headers": { "Items": ["Accept-Language"], "Quantity": 1 }
},
"CookiesConfig": { "CookieBehavior": "none" },
"QueryStringsConfig": {
"QueryStringBehavior": "whitelist",
"QueryStrings": { "Items": ["id", "page"], "Quantity": 2 }
}
}
}'
Origin Access Control (OAC) & Origin Access Identity (OAI)
Khi dùng S3 làm origin, bạn muốn chỉ cho phép CloudFront truy cập bucket — chặn truy cập trực tiếp từ internet. AWS cung cấp 2 cơ chế: OAC (mới, khuyến nghị) và OAI (cũ, legacy).
So sánh OAC vs OAI
| Tiêu chí | OAC (Khuyến nghị) | OAI (Legacy) |
|---|---|---|
| Hỗ trợ SSE-KMS | Có | Không |
| Hỗ trợ S3 PUT/DELETE | Có | Chỉ GET |
| Hỗ trợ tất cả Region | Có | Có |
| SigV4 signing | Có | Không |
| Hỗ trợ S3 Object Lambda | Có | Không |
| Trạng thái | Recommended | Legacy |
Cấu hình OAC
aws cloudfront create-origin-access-control \
--origin-access-control-config '{
"Name": "my-s3-oac",
"Description": "OAC for S3 bucket",
"SigningProtocol": "sigv4",
"SigningBehavior": "always",
"OriginAccessControlOriginType": "s3"
}'
{
"Version": "2012-10-17",
"Statement": [{
"Sid": "AllowCloudFrontOAC",
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/EDFDVBD6EXAMPLE"
}
}
}]
}
OAI (Legacy) — Tham khảo
{
"Version": "2012-10-17",
"Statement": [{
"Effect": "Allow",
"Principal": {
"AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1234567890"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::my-bucket/*"
}]
}
- OAC là best practice hiện tại — luôn chọn OAC trong câu hỏi mới
- OAI không hỗ trợ SSE-KMS encryption — nếu đề bài nhắc KMS → chọn OAC
- OAC hỗ trợ cả PUT/DELETE → dùng cho upload qua CloudFront
- Bucket phải Block Public Access = ON khi dùng OAC/OAI
SSL/TLS & Custom Domains
CloudFront hỗ trợ HTTPS cho cả viewer-facing (client → edge) và origin-facing (edge → origin). Bạn có thể dùng custom domain name (CNAME) với SSL certificate từ AWS Certificate Manager (ACM).
Viewer Protocol Policy
| Policy | Hành vi | Khuyến nghị |
|---|---|---|
| HTTP and HTTPS | Cho phép cả HTTP và HTTPS | Không khuyến nghị |
| Redirect HTTP to HTTPS | Tự động redirect HTTP → HTTPS (301) | Khuyến nghị |
| HTTPS Only | Chỉ chấp nhận HTTPS, reject HTTP | Cho API, sensitive data |
Origin Protocol Policy
| Policy | Mô tả | Ghi chú |
|---|---|---|
| HTTP Only | CloudFront → Origin qua HTTP | S3 website endpoint chỉ hỗ trợ HTTP |
| HTTPS Only | CloudFront → Origin qua HTTPS | ALB, custom origin với SSL |
| Match Viewer | Dùng cùng protocol với viewer | Linh hoạt nhưng cần origin hỗ trợ cả 2 |
SSL Certificate Options
Cấu hình Custom Domain với ACM
- Request certificate từ ACM — phải ở region
us-east-1(N. Virginia) - Validate domain — DNS validation (khuyến nghị) hoặc Email validation
- Thêm CNAME vào distribution — Alternate Domain Names:
cdn.example.com - Tạo DNS record — CNAME hoặc Alias record trỏ đến
d1234.cloudfront.net
# Certificate cho CloudFront PHẢI ở us-east-1 aws acm request-certificate \ --region us-east-1 \ --domain-name cdn.example.com \ --subject-alternative-names "*.example.com" \ --validation-method DNS # Sau khi validate, gán vào distribution aws cloudfront update-distribution \ --id E1234567890 \ --distribution-config '{ "ViewerCertificate": { "ACMCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/abc-123", "SSLSupportMethod": "sni-only", "MinimumProtocolVersion": "TLSv1.2_2021" }, "Aliases": { "Items": ["cdn.example.com"], "Quantity": 1 } }'
- ACM certificate cho CloudFront bắt buộc phải ở us-east-1 — tạo ở region khác sẽ không thấy trong dropdown
- CNAME trong distribution phải khớp với domain trong certificate
- Không thể dùng cùng CNAME cho 2 distributions khác nhau
Cache Invalidation & Versioning
Khi bạn cập nhật nội dung tại origin, CloudFront vẫn serve bản cũ từ cache cho đến khi TTL hết hạn. Có 2 cách để người dùng nhận nội dung mới: Invalidation (xóa cache) và Versioning (đổi URL).
Cache Invalidation
Invalidation yêu cầu CloudFront xóa object khỏi cache tại tất cả edge locations. Object sẽ được fetch lại từ origin ở request tiếp theo.
# Invalidate một file cụ thể aws cloudfront create-invalidation \ --distribution-id E1234567890 \ --paths "/index.html" # Invalidate nhiều files aws cloudfront create-invalidation \ --distribution-id E1234567890 \ --paths "/images/*" "/css/*" "/js/*" # Invalidate TẤT CẢ (wildcard) aws cloudfront create-invalidation \ --distribution-id E1234567890 \ --paths "/*" # Kiểm tra trạng thái invalidation aws cloudfront get-invalidation \ --distribution-id E1234567890 \ --id I1234567890
| Tiêu chí | Chi tiết |
|---|---|
| Thời gian hoàn thành | Thường 1-2 phút, tối đa 10-15 phút |
| Miễn phí | 1,000 invalidation paths/tháng (mỗi /* tính 1 path) |
| Phí vượt | $0.005/path sau 1,000 paths |
| Giới hạn đồng thời | Tối đa 3,000 invalidation paths đang xử lý |
| Wildcard | Hỗ trợ * ở cuối path (vd: /images/*) |
File Versioning (Khuyến nghị)
Thay vì invalidate cache, best practice là dùng versioned file names. Khi nội dung thay đổi, đổi tên file → CloudFront tự động fetch bản mới.
- Tốn phí sau 1,000 paths/tháng
- Mất 1-15 phút để propagate
- Không đảm bảo tất cả edge đồng bộ cùng lúc
- Khó rollback nếu deploy lỗi
- Miễn phí — không tốn invalidation cost
- Hiệu lực ngay lập tức
- Dễ rollback — chỉ cần trỏ lại URL cũ
- Ví dụ:
/app.v2.js,/style.abc123.css
- Static assets (JS, CSS, images): Dùng versioned filenames + TTL dài (1 năm)
- HTML files: TTL ngắn (vài phút) hoặc
no-cache+ invalidate khi deploy - API responses: TTL = 0 hoặc rất ngắn, forward relevant headers
Lambda@Edge & CloudFront Functions
CloudFront cho phép chạy code tại edge để customize request/response mà không cần thay đổi origin. Có 2 lựa chọn: CloudFront Functions (lightweight, nhanh) và Lambda@Edge (mạnh mẽ, linh hoạt).
So sánh CloudFront Functions vs Lambda@Edge
| Tiêu chí | CloudFront Functions | Lambda@Edge |
|---|---|---|
| Runtime | JavaScript (ECMAScript 5.1) | Node.js, Python |
| Chạy tại | Tất cả Edge Locations (600+) | Regional Edge Caches (13) |
| Events | Viewer Request, Viewer Response | Tất cả 4 events |
| Execution time | < 1ms | 5s (viewer) / 30s (origin) |
| Memory | 2 MB | 128 MB – 10 GB |
| Package size | 10 KB | 50 MB (zipped) |
| Network access | Không | Có |
| File system | Không | Có (/tmp) |
| Request body access | Không | Có |
| Giá | $0.10/1M invocations | $0.60/1M invocations + duration |
| Scale | 10,000,000 req/s | 10,000 req/s/region |
Ví dụ: CloudFront Function — URL Rewrite
function handler(event) { var request = event.request; var uri = request.uri; // Nếu URI không có extension → thêm /index.html if (uri.endsWith('/')) { request.uri += 'index.html'; } else if (!uri.includes('.')) { request.uri += '/index.html'; } return request; }
Ví dụ: Lambda@Edge — A/B Testing
'use strict'; exports.handler = async (event) => { const request = event.Records[0].cf.request; const headers = request.headers; // Đọc cookie để xác định variant const cookie = headers.cookie || []; const abCookie = cookie.find(c => c.value.includes('X-AB-Variant=') ); if (abCookie && abCookie.value.includes('B')) { // Route đến origin B request.origin.s3.domainName = 'variant-b-bucket.s3.amazonaws.com'; request.headers['host'] = [{ value: 'variant-b-bucket.s3.amazonaws.com' }]; } return request; };
Use Cases phổ biến
Security
CloudFront cung cấp nhiều lớp bảo mật từ edge đến origin: AWS WAF, AWS Shield, Geo Restriction, Signed URLs/Cookies, và Field-Level Encryption.
AWS WAF Integration
AWS WAF (Web Application Firewall) có thể gắn trực tiếp vào CloudFront distribution để lọc request tại edge:
- Rate limiting: Chặn IP gửi quá nhiều request
- IP whitelist/blacklist: Cho phép/chặn IP ranges
- SQL injection & XSS protection: Managed rules từ AWS
- Bot control: Phát hiện và chặn bot traffic
- Geo-based rules: Chặn theo quốc gia
- Custom rules: Dựa trên headers, query strings, body
Geo Restriction (Geoblocking)
| Loại | Mô tả | Ví dụ |
|---|---|---|
| Whitelist | Chỉ cho phép truy cập từ các quốc gia được chọn | Chỉ cho VN, US, JP |
| Blacklist | Chặn truy cập từ các quốc gia được chọn | Chặn CN, RU |
CloudFront xác định quốc gia dựa trên IP address và thêm header CloudFront-Viewer-Country vào request.
Signed URLs & Signed Cookies
Dùng để hạn chế truy cập nội dung — chỉ người có URL/cookie hợp lệ mới xem được:
- Mỗi URL chỉ truy cập được 1 file
- Có thời hạn (expiration time)
- Có thể giới hạn IP range
- Dùng cho: download file, video streaming
- Tương thích với mọi client
- Truy cập được nhiều files cùng lúc
- Không thay đổi URL gốc
- Có thời hạn + IP restriction
- Dùng cho: subscription content, premium area
- Cần client hỗ trợ cookies
Signed URL vs S3 Pre-signed URL
| Tiêu chí | CloudFront Signed URL | S3 Pre-signed URL |
|---|---|---|
| Truy cập qua | CloudFront (edge cache) | S3 trực tiếp |
| Caching | Có — serve từ edge | Không — luôn đến S3 |
| IP restriction | Có | Không |
| Path restriction | Có (canned/custom policy) | Chỉ 1 object |
| Ký bằng | CloudFront key pair (trusted key group) | IAM credentials |
| Khi nào dùng | Phân phối content qua CDN | Truy cập S3 trực tiếp (upload/download) |
Field-Level Encryption
Field-Level Encryption cho phép mã hóa các trường nhạy cảm (credit card, SSN) ngay tại edge location. Dữ liệu được mã hóa bằng public key và chỉ application server có private key mới giải mã được.
- Mã hóa tại edge → dữ liệu nhạy cảm được bảo vệ suốt đường truyền
- Chỉ áp dụng cho POST requests với specific fields
- Dùng RSA encryption với public/private key pair
- Tối đa 10 fields có thể encrypt
AWS Shield
| Tier | Giá | Bảo vệ |
|---|---|---|
| Shield Standard | Miễn phí | Tự động bảo vệ DDoS Layer 3/4 cho tất cả CloudFront distributions |
| Shield Advanced | $3,000/tháng | DDoS Layer 3/4/7, DDoS Response Team (DRT), cost protection, WAF miễn phí |
Performance Optimization
CloudFront cung cấp nhiều tính năng để tối ưu hiệu năng: Compression, HTTP/2 & HTTP/3, Origin Shield, và Price Classes.
Compression
CloudFront có thể tự động compress nội dung trước khi gửi đến viewer, giảm bandwidth và tăng tốc tải trang:
| Compression | Hỗ trợ | Ghi chú |
|---|---|---|
| Gzip | Có | Hỗ trợ rộng rãi, giảm 60-80% kích thước text files |
| Brotli | Có | Nén tốt hơn Gzip 15-25%, hỗ trợ browser hiện đại |
- Bật trong Cache Policy:
EnableAcceptEncodingGzipvàEnableAcceptEncodingBrotli - CloudFront tự chọn Gzip hoặc Brotli dựa trên
Accept-Encodingheader của viewer - Chỉ compress files từ 1,000 bytes đến 10 MB
- Compress các content types: text/html, text/css, application/javascript, application/json, v.v.
HTTP/2 & HTTP/3
| Protocol | Tính năng | Lợi ích |
|---|---|---|
| HTTP/2 | Multiplexing, header compression, server push | Tải nhiều files song song trên 1 connection, giảm latency |
| HTTP/3 (QUIC) | UDP-based, 0-RTT handshake, better loss recovery | Nhanh hơn trên mạng không ổn định (mobile, WiFi), giảm connection setup time |
Origin Shield
Origin Shield là một tầng cache bổ sung giữa Regional Edge Caches và Origin. Nó hoạt động như một "single point of contact" cho origin, giảm đáng kể số request đến origin.
- Khi nào dùng: Viewers phân tán nhiều region, origin không chịu được nhiều request
- Chọn region: Chọn region gần origin nhất để giảm latency
- Chi phí: Tính thêm phí cho request qua Origin Shield
- Lợi ích: Tăng cache hit ratio, giảm origin load, giảm chi phí origin
Price Classes
Price Classes cho phép bạn giới hạn edge locations mà CloudFront sử dụng, giúp giảm chi phí:
| Price Class | Edge Locations | Chi phí | Khi nào dùng |
|---|---|---|---|
| Price Class All | Tất cả 600+ PoPs | Cao nhất | Cần performance tốt nhất toàn cầu |
| Price Class 200 | Hầu hết regions (trừ South America, Australia) | Trung bình | Cân bằng giá/performance |
| Price Class 100 | Chỉ North America + Europe | Thấp nhất | Users chủ yếu ở US/EU |
Monitoring & Logging
CloudFront cung cấp nhiều công cụ giám sát: CloudWatch Metrics, Standard Access Logs, và Real-time Logs.
CloudWatch Metrics
CloudFront tự động gửi metrics đến CloudWatch (miễn phí). Các metrics quan trọng:
| Metric | Mô tả | Alarm gợi ý |
|---|---|---|
| Requests | Tổng số HTTP/HTTPS requests | Spike detection (anomaly) |
| BytesDownloaded | Bytes gửi từ CloudFront đến viewers | Bandwidth monitoring |
| BytesUploaded | Bytes gửi từ viewers đến CloudFront (POST/PUT) | Upload monitoring |
| 4xxErrorRate | % requests trả về 4xx | > 5% → alarm |
| 5xxErrorRate | % requests trả về 5xx | > 1% → alarm |
| TotalErrorRate | % tổng requests lỗi | > 5% → alarm |
| CacheHitRate | % requests served từ cache | < 80% → investigate |
| OriginLatency | Thời gian origin xử lý request (ms) | > 2000ms → alarm |
Standard Access Logs
CloudFront có thể ghi log mỗi request vào S3 bucket. Log file chứa thông tin chi tiết:
- Timestamp, Client IP, HTTP method, URI, Status code
- Edge location xử lý request
- Cache result: Hit, Miss, RefreshHit, Error
- Time taken: Thời gian xử lý (seconds)
- User-Agent, Referer, Query string
- SSL protocol, cipher
#Fields: date time x-edge-location sc-bytes c-ip cs-method cs(Host) cs-uri-stem sc-status cs(Referer) cs(User-Agent) cs-uri-query cs(Cookie) x-edge-result-type x-edge-request-id
2026-04-14 08:30:15 SIN2-C1 12345 203.0.113.50 GET d1234.cloudfront.net /images/logo.png 200 https://example.com/ Mozilla/5.0... - - Hit AbCdEf123==
- Logs được ghi vào S3 với delay 1-24 giờ (không real-time)
- Log bucket phải ở cùng account, bật ACL cho CloudFront
- Không tính phí CloudFront cho logging, nhưng tính phí S3 storage
- Dùng Athena để query logs hiệu quả
Real-time Logs
Nếu cần log gần real-time (vài giây), dùng Real-time Logs → gửi đến Kinesis Data Streams:
- Latency: Vài giây (so với hàng giờ của standard logs)
- Destination: Kinesis Data Streams → có thể xử lý bằng Lambda, Kinesis Data Firehose → S3/OpenSearch/Splunk
- Sampling rate: Có thể cấu hình 1-100% requests
- Fields: Chọn fields cần log (giảm chi phí Kinesis)
- Chi phí: Tính phí Kinesis Data Streams + CloudFront real-time log fee
aws cloudfront create-realtime-log-config \
--name my-realtime-logs \
--sampling-rate 100 \
--fields "timestamp" "c-ip" "sc-status" "cs-uri-stem" \
"x-edge-result-type" "time-taken" \
--end-points '{
"StreamType": "Kinesis",
"KinesisStreamConfig": {
"RoleARN": "arn:aws:iam::111122223333:role/CloudFrontRealtimeLogRole",
"StreamARN": "arn:aws:kinesis:us-east-1:111122223333:stream/cf-realtime-logs"
}
}'
Monitoring Architecture
Các lỗi thường gặp & Best Practices
Lỗi thường gặp
| Lỗi | Nguyên nhân | Cách khắc phục |
|---|---|---|
| 403 Access Denied | S3 bucket policy không cho phép CloudFront, OAC/OAI chưa cấu hình đúng | Kiểm tra bucket policy, đảm bảo OAC/OAI được gán đúng distribution |
| 502 Bad Gateway | CloudFront không kết nối được origin, SSL mismatch, origin timeout | Kiểm tra origin health, SSL certificate, security group cho ALB/EC2 |
| 503 Service Unavailable | Origin quá tải, CloudFront rate limiting | Scale origin, bật Origin Shield, tăng TTL để giảm origin requests |
| 504 Gateway Timeout | Origin xử lý quá lâu (> 30s mặc định) | Tăng origin response timeout (tối đa 180s), optimize origin |
| Stale content | Cache chưa hết hạn, TTL quá dài | Invalidate cache hoặc dùng versioned filenames |
| CORS errors | Origin không trả CORS headers, CloudFront không forward Origin header | Forward Origin header, cấu hình CORS tại origin, dùng Response Headers Policy |
| SSL certificate error | ACM cert không ở us-east-1, cert expired, domain mismatch | Tạo cert ở us-east-1, renew cert, kiểm tra CNAME khớp cert |
| Low cache hit rate | Forward quá nhiều headers/cookies/query strings | Giảm forwarded values, dùng Cache Policy tối ưu |
Debugging Headers
CloudFront thêm các headers hữu ích vào response để debug:
# Cache result X-Cache: Hit from cloudfront # Served từ cache X-Cache: Miss from cloudfront # Fetch từ origin X-Cache: RefreshHit from cloudfront # Cache expired, revalidated # Edge location xử lý request X-Amz-Cf-Pop: SIN2-C1 # Singapore edge location # Request ID (dùng cho support ticket) X-Amz-Cf-Id: AbCdEf123456789== # Age (seconds object đã ở trong cache) Age: 3600 # Đã cache 1 giờ # Kiểm tra bằng curl curl -I https://cdn.example.com/index.html
Best Practices
Tối ưu Cache Hit Rate
- Forward ít headers/cookies/query strings nhất có thể
- Dùng Cache Policy thay vì legacy forwarded values
- Normalize query string order (a=1&b=2 vs b=2&a=1)
- Tách static và dynamic content vào behaviors khác nhau
- Dùng Origin Shield cho multi-region viewers
- Set TTL phù hợp: dài cho static, ngắn cho dynamic
- Forward All headers → mỗi request unique → no cache
- Forward All cookies cho static content
- Dùng wildcard invalidation (/*) thường xuyên
- TTL = 0 cho tất cả content
- Không bật compression
- Dùng OAI thay vì OAC cho S3 mới
AWS CLI Cheat Sheet
Distribution Management
# Liệt kê tất cả distributions aws cloudfront list-distributions \ --query "DistributionList.Items[].{Id:Id,Domain:DomainName,Status:Status,Aliases:Aliases.Items[0]}" \ --output table # Xem chi tiết distribution aws cloudfront get-distribution --id E1234567890 # Xem cấu hình distribution aws cloudfront get-distribution-config --id E1234567890 # Tạo distribution từ S3 origin (basic) aws cloudfront create-distribution \ --origin-domain-name my-bucket.s3.amazonaws.com \ --default-root-object index.html # Disable distribution (trước khi xóa) aws cloudfront get-distribution-config --id E1234567890 --query "ETag" --output text # Sửa Enabled: false trong config, rồi: aws cloudfront update-distribution --id E1234567890 \ --if-match ETAG_VALUE \ --distribution-config file://disabled-config.json # Xóa distribution (phải disable trước) aws cloudfront delete-distribution --id E1234567890 --if-match ETAG_VALUE
Cache Invalidation
# Invalidate file cụ thể aws cloudfront create-invalidation \ --distribution-id E1234567890 \ --paths "/index.html" "/about.html" # Invalidate tất cả files trong thư mục aws cloudfront create-invalidation \ --distribution-id E1234567890 \ --paths "/images/*" # Invalidate TẤT CẢ aws cloudfront create-invalidation \ --distribution-id E1234567890 \ --paths "/*" # Liệt kê invalidations aws cloudfront list-invalidations --distribution-id E1234567890 # Kiểm tra trạng thái invalidation aws cloudfront get-invalidation \ --distribution-id E1234567890 \ --id I1234567890
OAC Management
# Tạo OAC aws cloudfront create-origin-access-control \ --origin-access-control-config '{ "Name": "my-s3-oac", "Description": "OAC for S3", "SigningProtocol": "sigv4", "SigningBehavior": "always", "OriginAccessControlOriginType": "s3" }' # Liệt kê OACs aws cloudfront list-origin-access-controls # Xem chi tiết OAC aws cloudfront get-origin-access-control --id E1234567890
CloudFront Functions
# Tạo function aws cloudfront create-function \ --name my-url-rewrite \ --function-config '{ "Comment": "URL rewrite for SPA", "Runtime": "cloudfront-js-2.0" }' \ --function-code fileb://function.js # Test function aws cloudfront test-function \ --name my-url-rewrite \ --if-match ETAG_VALUE \ --event-object fileb://test-event.json \ --stage DEVELOPMENT # Publish function (DEVELOPMENT → LIVE) aws cloudfront publish-function \ --name my-url-rewrite \ --if-match ETAG_VALUE # Liệt kê functions aws cloudfront list-functions # Xem code function aws cloudfront get-function --name my-url-rewrite --stage LIVE
Monitoring & Logs
# Xem CloudWatch metrics (requests trong 1 giờ qua) aws cloudwatch get-metric-statistics \ --namespace AWS/CloudFront \ --metric-name Requests \ --dimensions Name=DistributionId,Value=E1234567890 \ Name=Region,Value=Global \ --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%S) \ --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \ --period 300 \ --statistics Sum # Xem cache hit rate aws cloudwatch get-metric-statistics \ --namespace AWS/CloudFront \ --metric-name CacheHitRate \ --dimensions Name=DistributionId,Value=E1234567890 \ Name=Region,Value=Global \ --start-time $(date -u -v-1H +%Y-%m-%dT%H:%M:%S) \ --end-time $(date -u +%Y-%m-%dT%H:%M:%S) \ --period 300 \ --statistics Average # Tạo CloudWatch alarm cho 5xx errors aws cloudwatch put-metric-alarm \ --alarm-name "CloudFront-5xx-High" \ --namespace AWS/CloudFront \ --metric-name 5xxErrorRate \ --dimensions Name=DistributionId,Value=E1234567890 \ Name=Region,Value=Global \ --statistic Average \ --period 300 \ --threshold 1 \ --comparison-operator GreaterThanThreshold \ --evaluation-periods 2 \ --alarm-actions arn:aws:sns:us-east-1:111122223333:my-alerts
Useful Queries
-- Tạo table cho CloudFront logs CREATE EXTERNAL TABLE cloudfront_logs ( `date` DATE, time STRING, location STRING, bytes BIGINT, request_ip STRING, method STRING, host STRING, uri STRING, status INT, referrer STRING, user_agent STRING, query_string STRING, cookie STRING, result_type STRING, request_id STRING ) ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' LOCATION 's3://my-cf-logs-bucket/cf-logs/'; -- Top 10 URIs có nhiều 5xx errors SELECT uri, COUNT(*) as error_count FROM cloudfront_logs WHERE status >= 500 AND `date` >= '2026-04-01' GROUP BY uri ORDER BY error_count DESC LIMIT 10; -- Cache hit rate theo ngày SELECT `date`, COUNT(CASE WHEN result_type = 'Hit' THEN 1 END) * 100.0 / COUNT(*) as hit_rate FROM cloudfront_logs GROUP BY `date` ORDER BY `date` DESC;
- Dùng
--queryvới JMESPath để lọc output — tránh output quá dài - Dùng
--output tablecho output dễ đọc,--output jsoncho scripting - Dùng
aws cloudfront wait distribution-deployed --id E123để chờ distribution deploy xong - Lưu distribution config ra file:
aws cloudfront get-distribution-config --id E123 > config.json