CloudFront
CloudFront is AWS’s Content Delivery Network (CDN). It caches your content at edge locations worldwide, so users get faster responses from a server near them instead of your origin in a single region.
How CloudFront Works
Section titled “How CloudFront Works”User (Tokyo) ──► Edge Location (Tokyo) ──cache hit──► Response (fast, ~10ms) │ cache miss │ ▼ Origin (us-east-1) ──► Response (cached at edge for next request) (S3 / ALB / API GW)- User requests
https://cdn.example.com/image.jpg. - CloudFront routes to the nearest edge location.
- If the content is cached → return immediately (cache hit).
- If not cached → fetch from the origin, cache it, and return to the user (cache miss).
- Subsequent requests from the same region are served from cache.
Core Concepts
Section titled “Core Concepts”| Concept | What It Is |
|---|---|
| Distribution | A CloudFront configuration — maps a domain to one or more origins with caching rules |
| Origin | The source of your content (S3 bucket, ALB, API Gateway, custom HTTP server) |
| Edge location | A data center in the CloudFront network (~450+ worldwide). Caches content. |
| Regional edge cache | A larger cache between edge locations and your origin. Catches content evicted from edge. |
| Cache behavior | Rules that match URL patterns and define caching, compression, and protocols |
| TTL | Time to Live — how long content stays in the cache before re-checking the origin |
Origins
Section titled “Origins”S3 Origin (Static Content)
Section titled “S3 Origin (Static Content)”# S3 bucket as origin (static website, images, assets)Origin: my-bucket.s3.us-east-1.amazonaws.comUse Origin Access Control (OAC) to keep the S3 bucket private — only CloudFront can read from it:
{ "S3OriginConfig": { "OriginAccessIdentity": "" }, "OriginAccessControlId": "E1ABC2DEF3GH"}S3 bucket policy:
{ "Statement": [{ "Effect": "Allow", "Principal": {"Service": "cloudfront.amazonaws.com"}, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::my-bucket/*", "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1ABC2DEF3GH" } } }]}The bucket stays private (no public access) but CloudFront can serve its content.
ALB / Custom Origin (Dynamic Content)
Section titled “ALB / Custom Origin (Dynamic Content)”CloudFront ──► ALB (application load balancer) ──► EC2 / ECSFor dynamic content, set short TTLs or use cache policies that respect Cache-Control headers from your application.
API Gateway Origin
Section titled “API Gateway Origin”CloudFront ──► API Gateway ──► LambdaAdds edge caching and custom domain to your API. Useful for reducing API Gateway costs (cached responses don’t invoke Lambda).
Multiple Origins
Section titled “Multiple Origins”Route different URL patterns to different origins:
/api/* → API Gateway (dynamic)/images/* → S3 bucket (static)/* → ALB (web application)Cache Behaviors
Section titled “Cache Behaviors”Cache behaviors match URL patterns and define how CloudFront handles requests.
Default Behavior
Section titled “Default Behavior”Every distribution has a default behavior (/*) that catches all requests not matched by other behaviors.
Path-Based Behaviors
Section titled “Path-Based Behaviors”Priority Path Pattern Origin TTL Cache Policy1 /api/* API Gateway 0 No caching (forward all)2 /static/* S3 bucket 86400 Cache everything (1 day)3 /images/* S3 bucket 604800 Cache images (7 days)default /* ALB 300 Cache with headers (5 min)Cache Policy Settings
Section titled “Cache Policy Settings”| Setting | What It Controls |
|---|---|
| TTL | Minimum, maximum, and default TTL (seconds) |
| Cache key | What determines if a request is a cache hit: headers, query strings, cookies |
| Compression | Gzip/Brotli compression for text content |
Important: Including headers, query strings, or cookies in the cache key reduces cache hit rates because different combinations create different cache entries. Only include what actually changes the response.
Common Cache Policies
Section titled “Common Cache Policies”| Pattern | Headers in Key | Query Strings | Cookies | TTL |
|---|---|---|---|---|
| Static assets | None | None | None | 1–30 days |
| Dynamic pages | Accept-Language | All | Session cookie | 0–5 min |
| API responses | Authorization | All | None | 0 (no caching) |
| Images | None | None | None | 7–30 days |
HTTPS and Certificates
Section titled “HTTPS and Certificates”CloudFront provides free HTTPS with AWS Certificate Manager (ACM):
# Request a certificate (must be in us-east-1 for CloudFront)aws acm request-certificate \ --domain-name cdn.example.com \ --validation-method DNS \ --region us-east-1
# Validate via DNS (add the CNAME record ACM provides)| Setting | Options |
|---|---|
| Viewer protocol | HTTP and HTTPS, Redirect HTTP to HTTPS, HTTPS only |
| Origin protocol | HTTP only, HTTPS only, Match viewer |
| SSL certificate | Default CloudFront cert (*.cloudfront.net), or custom cert from ACM |
| Security policy | TLS version minimum (TLSv1.2 recommended) |
Always use Redirect HTTP to HTTPS for the viewer and HTTPS only for the origin when possible.
For certificate lifecycle, rotation, and attaching ACM to other services (ALB, API Gateway), see TLS and Certificates.
Custom Domain Names
Section titled “Custom Domain Names”cdn.example.com ──Route 53 alias──► CloudFront distribution ──► Origins- Request an ACM certificate for
cdn.example.com(inus-east-1). - Add
cdn.example.comas an alternate domain name (CNAME) on the distribution. - Create a Route 53 alias record pointing
cdn.example.comto the distribution.
Cache Invalidation
Section titled “Cache Invalidation”When you update content at the origin, cached copies at edge locations still serve the old version until the TTL expires. Invalidation forces CloudFront to re-fetch from the origin.
# Invalidate specific pathsaws cloudfront create-invalidation --distribution-id E1ABC2DEF3GH \ --paths "/index.html" "/css/*"
# Invalidate everythingaws cloudfront create-invalidation --distribution-id E1ABC2DEF3GH \ --paths "/*"- First 1,000 invalidation paths per month are free; $0.005 per path after that.
- Invalidation takes 1–5 minutes to propagate to all edge locations.
Better approach: Use versioned file names (app.v2.js, style.abc123.css) with long TTLs. No invalidation needed — new file name = new cache entry. Most build tools (Webpack, Vite) do this automatically.
CloudFront Functions and Lambda@Edge
Section titled “CloudFront Functions and Lambda@Edge”Run code at the edge for request/response manipulation:
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Runtime | JavaScript (lightweight) | Node.js, Python |
| Execution time | < 1ms | Up to 30 seconds |
| Triggers | Viewer request/response | Viewer + origin request/response |
| Network access | No | Yes |
| Cost | Very low | Higher |
| Use case | URL rewrites, header manipulation, simple redirects | Auth, A/B testing, dynamic content at edge |
CloudFront Function Example (URL Rewrite)
Section titled “CloudFront Function Example (URL Rewrite)”function handler(event) { var request = event.request; var uri = request.uri;
// Add index.html for directory requests (SPA support) if (uri.endsWith('/')) { request.uri += 'index.html'; } else if (!uri.includes('.')) { request.uri += '/index.html'; }
return request;}Lambda@Edge Example (Auth Check)
Section titled “Lambda@Edge Example (Auth Check)”exports.handler = async (event) => { const request = event.Records[0].cf.request; const headers = request.headers;
const token = headers.authorization?.[0]?.value; if (!token || !isValidToken(token)) { return { status: '401', body: 'Unauthorized', }; }
return request; // continue to origin};Common Patterns
Section titled “Common Patterns”Static Website with S3
Section titled “Static Website with S3”User ──► CloudFront (HTTPS) ──► S3 bucket (private, OAC) │ └── CloudFront Function: SPA URL rewriteFull-Stack Application
Section titled “Full-Stack Application”User ──► CloudFront ──► /api/* ──► ALB ──► ECS ──► /static/* ──► S3 ──► /* ──► S3 (SPA index.html)API Acceleration
Section titled “API Acceleration”User (distant region) ──► CloudFront edge ──► API Gateway ──► LambdaEven without caching, CloudFront reduces latency via optimized AWS backbone routing and persistent connections to the origin.
Monitoring
Section titled “Monitoring”| Metric | What It Shows |
|---|---|
Requests | Total requests (hit + miss) |
BytesDownloaded | Data transferred to viewers |
CacheHitRate | Percentage of requests served from cache |
4xxErrorRate | Client errors (404, 403) |
5xxErrorRate | Origin errors |
Access logs can be sent to S3 for detailed analysis (client IP, request path, cache status, response time).
Key Takeaways
Section titled “Key Takeaways”- CloudFront caches content at 450+ edge locations worldwide — reducing latency and origin load.
- Use Origin Access Control to keep S3 buckets private while serving content through CloudFront.
- Set long TTLs for static assets and use versioned file names instead of invalidation.
- Use cache behaviors to route different URL patterns to different origins with different caching rules.
- CloudFront Functions handle simple edge logic (rewrites, redirects); Lambda@Edge handles complex logic (auth, dynamic content).
- Always use HTTPS with a free ACM certificate.