App chạy ở Singapore, user Hà Nội load 3 giây, user US load 8 giây. S3 static hosting chỉ HTTP. CloudFront: 600+ Points of Presence toàn cầu, cache static + dynamic, HTTPS với ACM TLS miễn phí. Và điều đầu tiên bạn nghĩ — thêm server ở Hà Nội — hầu như không bao giờ là giải pháp đúng.
flowchart LR
User["User"] --> CF["CloudFront 600+ PoPs"]
CF -->|"/static/*"| S3["S3 (OAC)<br/>bucket private"]
CF -->|"/api/*"| ALB["ALB dynamic"]
CF -->|"/graphql"| APIG["API Gateway"]
WAF["WAF Rate Limiting"] -.-> CF
OAC thay OAI
OAC (Origin Access Control) thay thế OAI từ 2022: hỗ trợ SSE-KMS, POST/PUT methods, request signing.
aws cloudfront create-origin-access-control \
--origin-access-control-config Name=s3-oac,SigningProtocol=sigv4,SigningBehavior=always,OriginAccessControlOriginType=s3
Flag --signing-behavior=always buộc mọi request phải ký, không cho phép request unsigned từ public internet. OAC hoạt động ở cấp CloudFront, không phải S3 bucket policy, nên dễ quản lý hơn OAI.
// CDK: CloudFront + OAC + SPA fallback
const distribution = new cloudfront.Distribution(this, "CDN", {
defaultRootObject: "index.html",
domainNames: ["myapp.com"],
certificate: acmCert, // Phải us-east-1!
defaultBehavior: {
origin: origins.S3BucketOrigin.withOriginAccessControl(bucket),
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
},
errorResponses: [
{
httpStatus: 404,
responseHttpStatus: 200,
responsePagePath: "/index.html",
},
],
});
Cache Policy & Invalidation Strategy
| Managed Policy | Use Case | TTL |
|---|---|---|
CachingOptimized | Static assets (JS, CSS, images) | 24h default |
CachingDisabled | Dynamic API | No cache |
UseOriginCacheControlHeaders | Origin tự quyết định cache | Theo origin header |
Invalidation pattern: File content hash main.a1b2c3d.js cache 1 năm → không invalidate. Chỉ invalidate index.html khi deploy (reference file mới).
aws cloudfront create-invalidation --distribution-id E1ABCDEFGHIJKL --paths "/index.html"
WAF rate limiting
# WAF ACL cho CloudFront cũng phải us-east-1, giống ACM certificate
aws wafv2 create-web-acl --name cloudfront-waf --scope CLOUDFRONT --region us-east-1 \
--default-action Allow={} --visibility-config SampledRequestsEnabled=true,CloudWatchMetricsEnabled=true,MetricName=cloudfront-waf \
--rules '[{"Name":"rate-limit","Priority":0,"Statement":{"RateBasedStatement":{"Limit":2000,"AggregateKeyType":"IP"}},"Action":{"Block":{}},"VisibilityConfig":{"SampledRequestsEnabled":true,"CloudWatchMetricsEnabled":true,"MetricName":"rate-limit"}}]'
- OAC > OAI: SSE-KMS, POST/PUT, request signing
- ACM cert phải us-east-1 cho CloudFront
- Content hash: cache 1 năm, chỉ invalidate index.html
- SPA fallback: 404 → 200 /index.html
- WAF rate limit: 2,000 req/IP/5min chống DDoS
Bài sau: Phần 16: API Gateway — REST, HTTP, WebSocket, authorizer