CloudFront: Content Delivery Network
When users access your application from around the world, network distance adds latency. Amazon CloudFront is a content delivery network (CDN) that caches your content at edge locations worldwide, dramatically reducing load times for users everywhere. In this lesson, we'll explore how CloudFront works and how to use it effectively.
What You'll Learn
By the end of this lesson, you'll understand how CDNs work, CloudFront's global edge network, how to create distributions, configure caching, and secure your content with HTTPS and access controls.
What is a CDN?
A Content Delivery Network is a globally distributed network of servers that cache content closer to end users.
Without a CDN
User in Sydney
│
│ 200ms+ latency
▼
Server in Virginia
With a CDN
User in Sydney
│
│ 20ms latency
▼
Edge Location in Sydney ◄── Cached from Origin
Benefits of CDNs
- Lower latency - Content served from nearby edge locations
- Reduced origin load - Edge locations cache content
- Better availability - Distribute load across many servers
- DDoS protection - Absorb attacks at the edge
- HTTPS - Free SSL/TLS certificates
What is CloudFront?
Amazon CloudFront is AWS's global CDN service. It integrates deeply with other AWS services and supports:
- Static content (images, CSS, JavaScript)
- Dynamic content (API responses)
- Video streaming (live and on-demand)
- WebSocket connections
CloudFront Global Network
CloudFront operates from 450+ Points of Presence (PoPs) in 90+ cities across 47 countries. These include:
- Edge locations - Cache and serve content
- Regional edge caches - Larger caches between edge and origin
When a user requests content:
- Request goes to nearest edge location
- If cached (hit) → return immediately
- If not cached (miss) → fetch from regional cache or origin
- Cache the content for future requests
Core Concepts
Distributions
A distribution is a CloudFront configuration that tells CloudFront how to distribute your content.
Two types:
- Web distributions - HTTP/HTTPS content (most common)
- RTMP distributions - Adobe Flash media (legacy, rarely used)
Origins
An origin is where CloudFront fetches original content:
| Origin Type | Example |
|---|---|
| S3 bucket | Static website files |
| Custom origin (HTTP) | EC2, ALB, API Gateway |
| MediaStore | Video streaming |
| MediaPackage | Live video |
You can have multiple origins in one distribution.
Behaviors
Behaviors define how CloudFront handles requests for different paths:
| Path Pattern | Origin | Cache Settings |
|---|---|---|
| /api/* | API Gateway | No cache |
| /images/* | S3 bucket | Cache 1 day |
| /* (default) | S3 bucket | Cache 1 hour |
Creating a CloudFront Distribution
Let's create a distribution for an S3-hosted static website.
Step 1: Prepare S3 Bucket
Ensure your S3 bucket has static website hosting enabled (or will be used as CloudFront origin).
Step 2: Create Distribution
- Go to CloudFront console
- Click "Create distribution"
Step 3: Configure Origin
- Origin domain: Select your S3 bucket
- Origin access:
- "Origin access control settings" (recommended)
- Create new OAC
- Origin path: Leave empty (or specify subfolder)
Step 4: Configure Default Behavior
- Viewer protocol policy: "Redirect HTTP to HTTPS"
- Allowed HTTP methods: GET, HEAD (for static content)
- Cache policy: CachingOptimized (or create custom)
- Origin request policy: Depends on your needs
Step 5: Configure Settings
- Price class: Choose based on where your users are
- All edge locations (best performance, highest cost)
- North America and Europe only
- North America, Europe, Asia
- Default root object: index.html (for websites)
- Standard logging: Optional, logs to S3
Step 6: Create Distribution
Click "Create distribution" - deployment takes 5-10 minutes.
Step 7: Update S3 Bucket Policy
CloudFront will provide a bucket policy. Add it to your S3 bucket to allow CloudFront access:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "cloudfront.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your-bucket/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::123456789:distribution/EDFDVBD6EXAMPLE"
}
}
}
]
}
Custom Domain Names
By default, CloudFront provides a domain like:
d123456abcdef.cloudfront.net
For custom domains:
Step 1: Request SSL Certificate
- Go to AWS Certificate Manager (ACM)
- Request a certificate in us-east-1 (required for CloudFront)
- Enter your domain name(s)
- Validate via DNS or email
Step 2: Configure CloudFront
- Edit distribution
- Alternate domain names (CNAMEs): Add your domain
- Custom SSL certificate: Select your ACM certificate
- Save changes
Step 3: Update DNS
Add a CNAME or ALIAS record pointing to your CloudFront domain:
www.example.com → d123456abcdef.cloudfront.net
Caching Strategies
Effective caching is key to CloudFront performance.
Cache Key
The cache key determines what makes a request unique:
- URL path
- Query strings (configurable)
- Headers (configurable)
- Cookies (configurable)
Cache Control Headers
Your origin controls caching with headers:
Cache-Control: max-age=86400 # Cache for 1 day
Cache-Control: no-cache # Always revalidate
Cache-Control: no-store # Never cache
TTL Settings
CloudFront has three TTL settings:
- Minimum TTL: Override shorter cache-control values
- Maximum TTL: Cap on how long to cache
- Default TTL: When origin doesn't specify
Cache Policies
Use AWS managed policies or create custom ones:
| Policy | Use Case |
|---|---|
| CachingOptimized | Static content, long TTL |
| CachingDisabled | Dynamic content, no caching |
| CachingOptimizedForUncompressedObjects | Large, uncompressed files |
Cache Invalidation
When you need to remove cached content:
Create Invalidation
- Go to distribution → Invalidations
- Create invalidation
- Enter paths:
/images/logo.png- Specific file/images/*- All files in path/*- Everything (costly)
Invalidation Costs
- First 1,000 paths/month: Free
- After: $0.005 per path
Best Practice: Versioning
Instead of invalidating, use versioned filenames:
/js/app-v1.2.3.js
/css/style-abc123.css
Update references when content changes. Old versions naturally expire.
Securing Content
Origin Access Control (OAC)
Prevent direct S3 access, forcing requests through CloudFront:
- Create OAC in CloudFront
- Apply to S3 origin
- Update S3 bucket policy
- Block public access on S3 bucket
Signed URLs and Cookies
Restrict access to specific users:
Signed URLs - For individual files:
import boto3
from botocore.signers import CloudFrontSigner
# Create signed URL valid for 1 hour
signed_url = cloudfront_signer.generate_presigned_url(
url='https://d123.cloudfront.net/private/video.mp4',
date_less_than=datetime.now() + timedelta(hours=1)
)
Signed Cookies - For multiple files (streaming, member areas):
Set-Cookie: CloudFront-Policy=...
Set-Cookie: CloudFront-Signature=...
Set-Cookie: CloudFront-Key-Pair-Id=...
Geo Restrictions
Block or allow access by country:
- Edit distribution
- Geographic restrictions
- Choose allowlist or blocklist
- Select countries
Use cases: Licensing restrictions, compliance, localization.
WAF Integration
Add AWS WAF for additional protection:
- Block malicious requests
- Rate limiting
- SQL injection protection
- Custom rules
CloudFront Functions
Run lightweight code at the edge for request/response manipulation:
Use Cases
- URL rewrites and redirects
- Header manipulation
- A/B testing
- JWT validation
Example: Add Security Headers
function handler(event) {
var response = event.response;
var headers = response.headers;
headers['strict-transport-security'] = {
value: 'max-age=31536000; includeSubdomains'
};
headers['x-content-type-options'] = { value: 'nosniff' };
headers['x-frame-options'] = { value: 'DENY' };
return response;
}
CloudFront Functions vs Lambda@Edge
| Feature | CloudFront Functions | Lambda@Edge |
|---|---|---|
| Runtime | JavaScript only | Node.js, Python |
| Execution time | < 1 ms | Up to 30 seconds |
| Memory | 2 MB | Up to 10 GB |
| Network access | No | Yes |
| Cost | Lower | Higher |
| Use case | Simple transforms | Complex logic |
Monitoring and Logging
Standard Logs
Log every request to S3:
- Includes: timestamp, client IP, path, status, bytes, latency
- Delivered within minutes to hours
- Useful for detailed analysis
Real-time Logs
Stream logs to Kinesis Data Streams for real-time analysis:
- Choose which fields to include
- Specify sampling rate
- Analyze with Kinesis, Lambda, or third-party tools
CloudWatch Metrics
Key metrics to monitor:
- Requests - Total request count
- BytesDownloaded - Data transferred
- 4xxErrorRate - Client errors
- 5xxErrorRate - Origin errors
- CacheHitRate - Percentage served from cache
CloudFront Pricing
Pay for:
- Data transfer out to internet (varies by region)
- HTTP/HTTPS requests (varies by region)
- Invalidation requests (after free tier)
- Functions (per invocation/compute time)
Free Tier
- 1 TB data transfer out/month
- 10 million HTTP/HTTPS requests/month
- 2 million CloudFront Function invocations/month
Key Takeaways
- CloudFront is a global CDN that caches content at edge locations worldwide
- Distributions define how content is distributed from origins to users
- Origins can be S3, EC2, ALB, API Gateway, or any HTTP server
- Behaviors configure caching and handling for different URL patterns
- Cache invalidation removes content before it expires; versioning is often better
- OAC prevents direct origin access, improving security
- Signed URLs/cookies restrict content to authorized users
- CloudFront Functions run lightweight code at the edge
What's Next
Now that your content is delivered globally through CloudFront, users need to find it. In the next lesson, we'll explore Route 53 - AWS's DNS service that routes users to your applications.

