What Is Amazon CloudFront and How Does It Speed Delivery?
Amazon CloudFront explained: distributions, origins, cache behaviors, Origin Shield, OAC for S3, HTTPS, WAF, edge functions, monitoring and cost controls.
Amazon CloudFront is AWS's content delivery network. It serves your website, APIs, video and downloads from edge locations close to users, caches what can be cached, and sends the rest back to your origin over the AWS network. The result is lower latency, less load on your servers and a single place to add HTTPS, WAF rules and edge logic.
This is the overview post in our CloudFront series. It explains the building blocks and how they improve delivery, then points to the detailed guides for SSL and custom domains, S3 integration, invalidation and monitoring. CloudFront is one of the services in the AWS services DevOps engineers use daily.
Key takeaways
- A CloudFront distribution sits in front of one or more origins (S3, a load balancer, EC2, API Gateway, MediaPackage, or any HTTP server) and gets a
*.cloudfront.netdomain name. - Cache behaviors match URL path patterns and decide which origin to use and how to cache. Cache policies control the cache key and TTLs.
- Requests that miss the edge cache can go through regional edge caches and, optionally, Origin Shield before reaching the origin, which raises the cache hit ratio.
- For S3 origins, use Origin Access Control (OAC) so the bucket stays private. OAC is the recommended replacement for the older Origin Access Identity.
- HTTPS with a custom domain needs an ACM certificate in the US East (N. Virginia) Region.
- CloudFront includes AWS Shield Standard and integrates with AWS WAF, and you can run code at the edge with CloudFront Functions or Lambda@Edge.
How CloudFront improves delivery
Without a CDN, every user request travels across the public internet to one origin region. Users far from that region pay for the distance on every request, and the origin handles every request itself. CloudFront changes four things.
| Problem | What CloudFront does | Effect |
|---|---|---|
| Distance to the origin | DNS routes each user to a nearby edge location, where TLS is terminated and cached objects are served | Lower time to first byte for static and cacheable content |
| Repeated requests for the same object | Edge caches and regional edge caches keep copies for the configured TTL | Fewer origin requests and less origin bandwidth |
| Slow paths for dynamic requests | Uncached requests travel from the edge to the origin over the AWS network, with persistent connections to the origin | Faster API and dynamic page responses even with no caching |
| Security at the front door | Shield Standard, optional AWS WAF, TLS policies, geo restrictions, signed URLs and cookies | Filtering happens before traffic reaches your servers |
AWS publishes the current list of edge locations and regional edge caches on the CloudFront features page. The network grows regularly, so check that page rather than relying on a number in a blog post.
Core building blocks
Distribution
The top-level resource. It has a domain name, optional alternate domain names (CNAMEs), a TLS certificate, a price class, logging settings, an optional WAF web ACL, and one or more origins and cache behaviors.
Origins and origin groups
An origin is where CloudFront fetches content. Common choices are an S3 bucket, an Application Load Balancer, an API Gateway endpoint, or a custom HTTP server. An origin group pairs a primary and secondary origin, so CloudFront retries the secondary when the primary returns configured error codes. That gives you origin failover for reads.
Cache behaviors
Each behavior has a path pattern such as /api/* or /static/*, plus a default behavior (*). A behavior sets the target origin, allowed HTTP methods, viewer protocol policy (for example redirect HTTP to HTTPS), compression, and the attached policies and functions.
Policies
- Cache policy: which headers, cookies and query strings form the cache key, plus minimum, default and maximum TTL. AWS provides managed policies such as CachingOptimized and CachingDisabled.
- Origin request policy: which extra values are forwarded to the origin without being part of the cache key.
- Response headers policy: adds headers to responses, such as CORS or security headers like Strict-Transport-Security.
Keeping the cache key small is the single biggest lever on hit ratio. Every header or cookie you add to the key splits the cache into more variants.
The request path
- The user's browser resolves your domain, which points (through a Route 53 alias or CNAME) to the distribution.
- DNS returns an edge location close to the user, and the browser opens a TLS connection there.
- CloudFront matches the URL to a cache behavior and runs any viewer request function.
- If the object is in the edge cache and still fresh, CloudFront returns it.
- On a miss, the edge asks a regional edge cache. If Origin Shield is enabled, the request then goes to the Origin Shield location for that origin.
- Only if all those layers miss does CloudFront contact the origin. The response is cached on the way back according to the cache policy and the origin's Cache-Control headers.
Caching with Cache-Control
CloudFront honours Cache-Control and Expires headers from the origin within the minimum and maximum TTL bounds of the cache policy. A practical pattern for web apps:
- Fingerprinted static assets (
app.3f9c1a.js):Cache-Control: public, max-age=31536000, immutable. A new deploy produces new file names, so you never need to invalidate them. - HTML entry pages: a short
max-ageorno-cacheso users pick up new releases quickly. - Personalized API responses: CachingDisabled policy, or a cache key that includes only the parameters that change the response.
When you do need to remove content before its TTL ends, use an invalidation. How paths, wildcards and costs work is explained in How CloudFront Cache Invalidation Works.
aws cloudfront create-invalidation \
--distribution-id E1234567890ABC \
--paths "/index.html" "/images/*"
CloudFront in front of S3
Serving a static site or file downloads from S3 through CloudFront is the most common setup. Keep the bucket private, enable Origin Access Control on the origin, and add a bucket policy that allows the cloudfront.amazonaws.com service principal to read objects only when the request comes from your distribution (using the AWS:SourceArn condition). AWS recommends OAC over the legacy Origin Access Identity because it supports SSE-KMS encrypted objects and all Regions.
Full steps, the bucket policy and signed URLs are in How to Integrate S3 with CloudFront for Secure File Distribution and How S3 Is Used in a CDN with CloudFront.
HTTPS and custom domains
To serve www.example.com from CloudFront you add it as an alternate domain name and attach a certificate that covers it. Certificates from AWS Certificate Manager must be requested or imported in US East (N. Virginia), us-east-1, to be used with CloudFront. You also choose a security policy that sets the minimum TLS version and ciphers for viewers. The step-by-step guide is How to Configure CloudFront with SSL and Custom Domains.
Security features
| Feature | Purpose |
|---|---|
| AWS Shield Standard | Included protection against common network and transport layer DDoS attacks |
| AWS WAF | Web ACL rules for SQL injection, cross-site scripting, rate limiting, bot control and IP lists, evaluated at the edge |
| Origin Access Control | Keeps S3 and other supported origins private to the distribution |
| Signed URLs and signed cookies | Time-limited access to private content |
| Geographic restrictions | Allow or block viewers by country |
| Field-level encryption | Encrypts specific POST form fields at the edge so only the intended backend can read them |
| Viewer protocol policy and TLS security policy | Force HTTPS and set minimum TLS versions |
For a load balancer origin, also stop users from bypassing CloudFront. Common approaches are the AWS-managed prefix list for CloudFront in the ALB security group, plus a custom secret header that the ALB checks, or CloudFront VPC origins for private ALBs and EC2 instances.
Running code at the edge
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Runtime | Lightweight JavaScript | Node.js and Python |
| Triggers | Viewer request, viewer response | Viewer and origin request and response |
| Network or body access | No | Yes |
| Typical uses | URL rewrites and redirects, header changes, simple auth token checks, cache key normalization | Calling other services, origin selection, image transformation, longer logic |
A small CloudFront Function that adds index.html to directory paths for a static site:
function handler(event) {
var request = event.request;
var uri = request.uri;
if (uri.endsWith('/')) {
request.uri += 'index.html';
} else if (!uri.includes('.')) {
request.uri += '/index.html';
}
return request;
}
CloudFront also offers a KeyValueStore that functions can read, which is handy for redirect tables you want to change without redeploying code.
Monitoring and logging
- Default CloudWatch metrics per distribution: requests, bytes downloaded and uploaded, 4xx and 5xx error rates. Additional metrics, including cache hit rate and origin latency, can be enabled for a fee.
- Standard logs (access logs) delivered to S3 or other destinations, and real-time logs through Kinesis Data Streams.
- Reports in the console for cache statistics, popular objects, top referrers and viewers.
Dashboards and alarms for these are covered in How to Monitor CloudFront Edge Locations and Request Metrics.
Defining a distribution as code
Treat the distribution like any other infrastructure. A trimmed Terraform example for an S3 origin with OAC:
resource "aws_cloudfront_origin_access_control" "site" {
name = "site-oac"
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
resource "aws_cloudfront_distribution" "site" {
enabled = true
default_root_object = "index.html"
aliases = ["www.example.com"]
origin {
domain_name = aws_s3_bucket.site.bucket_regional_domain_name
origin_id = "s3-site"
origin_access_control_id = aws_cloudfront_origin_access_control.site.id
}
default_cache_behavior {
target_origin_id = "s3-site"
viewer_protocol_policy = "redirect-to-https"
allowed_methods = ["GET", "HEAD"]
cached_methods = ["GET", "HEAD"]
cache_policy_id = data.aws_cloudfront_cache_policy.optimized.id
compress = true
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
acm_certificate_arn = aws_acm_certificate.site.arn
ssl_support_method = "sni-only"
minimum_protocol_version = "TLSv1.2_2021"
}
}
The ACM certificate resource must use a provider configured for us-east-1.
Cost controls
CloudFront charges mainly for data transfer out to viewers and for requests, with extra charges for features such as invalidations beyond the free allowance, functions, real-time logs and additional metrics. Data transfer from AWS origins to CloudFront is not charged. Ways to keep the bill predictable:
- Raise the cache hit ratio with smaller cache keys and long TTLs on versioned assets.
- Choose a price class that excludes regions where you have few users, if slightly higher latency there is acceptable.
- Turn on compression for text content.
- Use versioned file names instead of frequent wildcard invalidations.
Check the official CloudFront pricing page for current rates and any plan options, since pricing changes over time.
When CloudFront fits and when it does not
CloudFront fits public websites and SPAs, APIs with users in many locations, large file and software downloads, and video streaming. It adds less value for internal-only applications reached over a private network, or for workloads where every response is unique and users sit next to the origin region. Other CDNs such as Akamai, Cloudflare and Fastly solve the same problem; if you are comparing them for interviews, see Akamai interview questions.
Learn AWS delivery hands-on
CloudFront, S3, Route 53 and ACM come up together in architecture questions on the AWS Solutions Architect Associate exam. Our AWS Solutions Architect Associate training covers them with labs, in Kharadi, Pune and live online.
Frequently asked questions
What is Amazon CloudFront used for?
CloudFront is a CDN that delivers websites, APIs, video and file downloads from edge locations near users. It caches content, speeds up uncached requests over the AWS network, and adds HTTPS and security controls in front of your origin.
Does CloudFront help with dynamic content?
Yes. Even uncached requests benefit, because TLS is terminated near the user and the request travels to the origin over the AWS network using persistent connections.
What is the difference between OAC and OAI?
Both restrict an S3 bucket so only CloudFront can read it. Origin Access Control is the newer, recommended option and supports SSE-KMS encrypted objects and all AWS Regions. Origin Access Identity is the legacy method.
Which Region must the ACM certificate be in for CloudFront?
US East (N. Virginia), us-east-1. Certificates in other Regions cannot be attached to a distribution.
What is Origin Shield?
An optional extra caching layer in front of your origin. All regional edge caches route misses through one Origin Shield location, which raises the hit ratio and reduces origin load.
When should I use CloudFront Functions instead of Lambda@Edge?
Use CloudFront Functions for short, high-volume viewer request and response tasks such as redirects, rewrites and header changes. Use Lambda@Edge when you need network access, the request body, origin triggers or longer processing.
How do I clear cached content in CloudFront?
Create an invalidation for specific paths or wildcards, or better, use versioned file names so new content gets new URLs and no invalidation is needed.
Is CloudFront protected against DDoS attacks?
Every distribution includes AWS Shield Standard. You can add AWS WAF rules, including rate-based rules, and subscribe to Shield Advanced for more protection and response support.
Official references
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0