
Amazon CloudFrontAuthorCloudBrum editorial teamLast reviewedReading time~12 minLevelBeginner to advanced
Amazon Web Services · Networking · Content delivery network and edge compute
CloudFront is the AWS content delivery network: copies of your pages, images and API answers kept in hundreds of edge locations, so a visitor gets them from somewhere close. You create a distribution, point it at an origin such as an S3 bucket, a load balancer or any web server, and decide what is cached and for how long. Done well, it makes a site quicker and takes load off the origin. Done carelessly, it serves stale pages or caches something private. Since late 2025 you can also pay a flat monthly price instead of by the gigabyte.
On this page (17 sections)
Mind map: Amazon CloudFront at a glance
Free to share. The downloaded image includes the CloudBrum link.
Key features (summary)
- Edge locations and regional cachesA request goes to a nearby edge location. On a miss it travels through a regional edge cache before it reaches your origin, so popular objects are fetched from the origin far less often than they are served.
- Many kinds of originAn S3 bucket, an Application or Network Load Balancer, API Gateway, a Lambda function URL, a media service or any web server on the internet. VPC origins let CloudFront reach load balancers and instances in a private subnet.
- Cache policies you can reuseA cache policy says what makes two requests the same (headers, cookies, query strings) and how long to keep the object. AWS ships managed policies such as CachingOptimized and CachingDisabled, and you can write your own.
- Private originsOrigin access control makes CloudFront sign its requests to S3 and to Lambda function URLs, so the origin can refuse everyone else. It replaces the older origin access identity.
- Code at the edgeCloudFront Functions run short JavaScript in under a millisecond for URL rewrites, redirects and header changes. Lambda@Edge runs Node.js or Python for heavier work and can call other services.
- Private contentSigned URLs and signed cookies, built on key groups, let only authorised users fetch a file for a limited time. Geographic restrictions and field-level encryption are available too.
- Protection at the edgeShield Standard absorbs common network attacks at no charge. AWS WAF attaches to a distribution for rate limits, bot control and managed rules, and ACM issues free certificates for your domain.
- Two ways to payPay-as-you-go bills data transfer and requests, with an always-free allowance. The flat-rate plans bundle delivery with WAF, DDoS protection and DNS for a fixed monthly price, which AWS describes as having no overage charges.
Basic concepts
- Distribution
- The CloudFront configuration that you point a domain at. It holds the origins, the behaviors, the certificate, the logging and the security settings, and it has its own *.cloudfront.net name.
- Edge location and regional edge cache
- An edge location is where viewers connect. A regional edge cache is a larger cache layer behind several edge locations that holds objects longer.
- Origin
- The server that has the original content. CloudFront asks it only when an object isn’t cached or has expired.
- Cache behavior
- A rule that matches a path pattern, such as /assets/*, and says which origin, cache policy, protocols and functions apply. The default behavior handles everything else.
- Cache policy
- Defines the cache key (which headers, cookies and query strings count) and the minimum, default and maximum time to live.
- Origin request policy
- Defines what CloudFront forwards to the origin on a miss, separately from the cache key, so you can send a header without caching per value of it.
- Response headers policy
- Adds headers to every response, such as security headers and CORS rules, without code.
- Invalidation
- A request to remove objects from the edge caches before their TTL ends. The first 1,000 paths a month in an account are free, and extra paths cost a small fixed fee.
- Origin access control (OAC)
- Lets CloudFront authenticate to S3 with signed requests, so the bucket can be fully private.
- Viewer protocol policy
- Whether viewers may use HTTP, are redirected to HTTPS, or may only use HTTPS.
- Signed URL and key group
- A URL with an expiry and a signature made by a private key that you hold. CloudFront checks it with the public key in a key group.
- CloudFront Functions and Lambda@Edge
- Two ways to run code on requests and responses. Functions are fast and limited, and Lambda@Edge is slower to start and much more capable.
- Origin Shield
- An optional extra cache layer in one chosen Region that all misses pass through, which cuts the load on the origin further.
How to create & configure it
Put a private S3 site behind CloudFront with the AWS CLI
- Decide what can be cachedStatic files, images, scripts and public API answers can. Anything personal, or anything that must be exact to the second, needs a short TTL or no caching.
- Keep the origin privateCreate the bucket with all public access blocked, and use origin access control so that only CloudFront can read it.
- Create the distribution with safe defaultsRedirect HTTP to HTTPS, turn on compression, use the CachingOptimized managed policy, allow HTTP/3 and choose a price class that matches where your viewers are.
- Allow only this distributionAdd a bucket policy that lets the CloudFront service read objects when AWS:SourceArn is this distribution’s ARN.
- Add behaviors per pathGive /assets/ a long TTL and /api/ a policy that forwards what the API needs, or no caching at all.
- Attach your domain and certificateRequest the certificate in ACM in us-east-1, add the domain as an alternate domain name, and point DNS at the distribution.
- Version your filesPut a content hash in file names such as app.3f9c1a.js, so a release needs no invalidation. Invalidate only the entry pages.
- Turn on protection and logsAttach a web ACL for rate limits and bad bots where needed, and send logs somewhere you can read.
- Watch the numbersAlarm on 5xxErrorRate and TotalErrorRate, and look at the cache hit ratio after each change to a cache policy.
Tip: a single-page app on S3 needs error mapping. With origin access control and no list permission, S3 answers 403 for a path that doesn’t exist, so map 403 and 404 to /index.html with status 200 in the distribution’s custom error responses. The CLI and Terraform tabs both include it. See the code references.
Common issues after configuration
| Symptom | Likely cause | What to check / fix |
|---|---|---|
| Visitors see the old version after a release | The edge still holds a copy that hasn’t expired, or the HTML has a long TTL | Version asset file names, give HTML a short TTL, and invalidate the entry pages after each release. |
| AccessDenied or 403 from an S3 origin | Origin access control isn’t attached, the bucket policy names the wrong distribution, or a KMS-encrypted bucket doesn’t allow CloudFront in its key policy | Check the OAC on the origin, the AWS:SourceArn in the bucket policy and, for SSE-KMS, the key policy. |
| 502 Bad Gateway | CloudFront can’t set up a TLS connection to the origin: the certificate doesn’t match the host name, or the protocol and ciphers don’t overlap | Use an origin certificate for the exact host name that CloudFront connects to, and align the origin protocol policy. |
| 504 Gateway Timeout | The origin took longer than the origin response timeout, or couldn’t be reached | Raise the timeout if the origin is really slow, otherwise fix the origin, and check that its security group allows CloudFront. |
| Every request is a miss | The cache key includes cookies, headers or query strings that differ per request, or the origin sends Cache-Control: no-store or private | Trim the cache policy to what changes the answer, and fix the origin’s cache headers. |
| One visitor was served another visitor’s page | A personalised response was cached because the cache key doesn’t include the cookie or header that personalises it | Don’t cache that path, or add the identifying cookie or header to the cache key, and send Cache-Control: private from the origin. |
| The custom domain gives a certificate error | The certificate isn’t in us-east-1, doesn’t cover the host name, or the domain isn’t listed as an alternate domain name | Request or import the certificate in us-east-1, include the name, and add it to the distribution. |
| A page refresh on an app route returns 403 or 404 | S3 has no object at that path, and the app expects index.html | Add custom error responses for 403 and 404 that return /index.html with status 200. |
| CORS errors on fonts or API calls | The Origin header isn’t forwarded, so the origin’s CORS answer is cached for the wrong origin, or no CORS headers are set | Forward Origin through an origin request policy, include it in the cache key where it matters, and add CORS headers. |
| A change to the distribution doesn’t show yet | A configuration change needs a few minutes to reach every edge location | Wait until the distribution status says Deployed. Test with a staging distribution through continuous deployment. |
| The bill is higher than expected | More data transfer or requests than planned, large uncompressed files, Lambda@Edge invocations, WAF rules or real-time logs | Break the bill down by usage type, turn on compression, cache more, and compare pay-as-you-go with a flat-rate plan. |
Use cases: when and where to use it
Good fit
- Websites and single-page apps whose files can be cached close to visitors
- Downloads, software updates and video that serve many viewers from the same objects
- APIs where some GET answers can be cached for seconds and the rest passes through
- Applications that want one entry point with TLS, WAF rules and DDoS protection in front of several origins
- Private content with expiring links, such as paid downloads
- Teams that want a predictable monthly price for delivery and security (flat-rate plans)
Consider something else
- Routing traffic between Regions with fixed IP addresses and no caching → AWS Global Accelerator
- Distributing HTTP requests between servers inside a Region → Elastic Load Balancing
- DNS answers, health checks and routing policies → Amazon Route 53
- File sharing for static websites only, without a CDN → Amazon S3 website hosting
- Streaming and video packaging at scale → AWS Elemental MediaPackage with CloudFront
- The same job on other clouds → compare Azure Front Door and Cloud CDN
Pros: why consider it?
Why teams choose it
- Fast delivery from a large global network, with HTTP/3 and TLS 1.3
- Takes load and bandwidth off the origin
- Origin access control keeps S3 and function URLs private
- Reusable cache, request and response header policies
- WAF, Shield Standard and free ACM certificates fit in naturally
- Flat-rate plans and an always-free allowance make small sites cheap
Trade-offs to weigh
- Cache behaviour is subtle, and a wrong cache key can serve stale or private content
- Configuration changes take minutes to deploy
- The ACM certificate for a custom domain must live in us-east-1
- Invalidation is a blunt tool, and wildcard paths aren’t cheaper
- Costs have several parts: data transfer, requests, functions, logs and WAF
- Debugging means reading headers and logs from the edge, not just the origin
Common threats, vulnerabilities & risks
| Risk | Severity | Why it matters | Mitigation |
|---|---|---|---|
| Public origin bucket | High | If the bucket is world-readable, people can bypass CloudFront and its protections, and your cost controls. | Block public access, use origin access control and a bucket policy tied to the distribution’s ARN. |
| Caching personal content | High | A cached personalised response can be handed to someone else, which is a data leak. | Keep authenticated paths out of the cache or include the identity in the cache key, and test with two accounts. |
| Allowing plain HTTP | High | Viewers on HTTP are open to interception and tampering. | Use redirect-to-https or https-only, set a minimum TLS version and add security headers. |
| Unprotected origin behind the edge | Medium | An origin that accepts traffic from anywhere can be attacked directly, skipping WAF and caching. | Allow only CloudFront (VPC origins, the managed prefix list or a secret header) and keep the origin private. |
| Signing keys handled carelessly | Medium | A leaked private key lets anyone create valid signed URLs. | Keep the key in a secrets service, rotate key groups, and use short expiry times. |
| Overlong TTL on HTML | Medium | A broken page can stay at the edge for hours, even after you fix the origin. | Keep HTML TTLs short, version assets, and know how to invalidate quickly. |
| Edge code without limits | Medium | A bug in a function runs on every request, so an error spreads to all viewers at once. | Test with the built-in test tool, deploy through continuous deployment and watch error rates. |
| No logs | Low–Med | Without logs you can’t see who fetched what, or why a block happened. | Enable standard logging to S3 or CloudWatch, and keep them for the period your rules require. |
| Runaway costs from abuse | Low–Med | Bots and hotlinking can pull a lot of data through your distribution. | Add WAF rate rules, restrict hotlinking with a referrer or signed URLs, and set a budget alert. |
Performance optimisation
- Give assets long TTLs and versioned names, so repeat visits are served from the browser cache or the edge.
- Keep the cache key small: forward only the headers, cookies and query strings that change the response.
- Turn on compression (Brotli and gzip), so text files travel at a fraction of their size.
- Use HTTP/3 and keep the price class matched to where your viewers are.
- Enable Origin Shield for origins that are slow or costly to hit, so misses from all edge locations collapse into one request.
- Use CloudFront Functions for short rewrites and redirects, and keep Lambda@Edge for work that needs it.
- Set origin keep-alive and timeouts sensibly, and put the origin in a Region close to the largest audience.
- Cache short-lived API answers for a few seconds, which absorbs bursts without showing old data for long.
Reduce monthly cost
FinOps is the habit of managing cloud spend together with engineering. These are the FinOps checks that matter most for Amazon CloudFront.
- Use the always-free allowance (1 TB and 10 million requests a month) for small sites, and compare it with the free flat-rate plan.
- Compare pay-as-you-go with flat-rate plans for each site. Predictable, busy sites can be cheaper on a plan.
- Pick a price class that excludes the most expensive regions if your viewers aren’t there.
- Compress text responses and size images properly, since you pay by the byte.
- Raise cache hit ratio, so fewer requests reach the origin and the extra regional fetches are avoided.
- Use versioned file names instead of invalidation. The first 1,000 invalidation paths a month are free, and more are billed per path.
- Prefer CloudFront Functions to Lambda@Edge where they are enough, since they cost much less per request.
- Remember that data transfer from AWS origins to CloudFront is free, so S3 and load balancer origins don’t add transfer charges for the fetch.
- Sample or limit real-time logs, and keep standard logs only as long as you need them.
- Add WAF rate limits and a budget alert to catch abusive traffic early.
Figures here come from AWS's pricing page and published guides, read in October 2026. Rates vary by region and sources show launch prices, so confirm on the live page (see Pricing).
Security optimisation
- Use origin access control for S3 and Lambda function URLs, and a VPC origin for private load balancers and instances.
- Redirect to HTTPS only, pick the newest security policy for the viewer certificate and add a response headers policy for HSTS and other headers.
- Attach AWS WAF with rate rules, managed rule groups and bot control where the application needs them.
- Protect private downloads with signed URLs or cookies, short expiry times and key groups that you rotate.
- Allow only CloudFront IP ranges (the managed prefix list) or VPC origins on the origin side.
- Enable standard logging and, where useful, real-time logs, and send them to a bucket with restricted access.
- Restrict who can change distributions, and alert on UpdateDistribution and DeleteDistribution.
- Use field-level encryption or keep sensitive fields out of the request path for forms that carry card data.
- Use geographic restrictions where law or licence requires them.
- Review Security Hub and AWS Config findings for distributions without WAF, logging or HTTPS.
Governance & compliance
Guardrails
- A shared Terraform module for distributions that sets HTTPS-only, a minimum TLS version, logging, a web ACL and tags
- A service control policy or IAM boundary that limits who can create or edit distributions and cache policies
- A naming standard for origins and behaviors, with a note of what is cacheable on each path
- A release checklist that covers versioned assets, HTML TTLs and the invalidation of entry pages
Continuous checks (AWS Config, Security Hub and your own scripts)
- A scheduled script that lists distributions that allow HTTP, have no web ACL or have logging off (the C# tab does this)
- AWS Config rules and Security Hub controls for CloudFront, where your standard includes them
- Alarms on 5xxErrorRate, TotalErrorRate and origin latency
- A CloudTrail alert for changes to distributions, cache policies and key groups
- A monthly report of cost by distribution and usage type
AWS CloudTrail records who changed distributions and policies, AWS Config keeps the configuration history, Security Hub reports on settings, and AWS Artifact holds compliance reports. AWS runs the edge network and the service. Origins, cache rules, certificates, access to private content and what you put in logs are yours.
Reduce carbon footprint
- Raise the cache hit ratio, so the origin serves fewer requests.
- Serve Brotli or gzip for text and resize images, which cuts the bytes sent.
- Use Brotli, modern image formats and HTTP/3 to cut transfer.
- Remove unused distributions and behaviors, and stop logging that nobody reads.
- Origins can sit in a Region with a cleaner power grid, provided data rules and latency allow it.
- The AWS carbon tool reports per account and does not list CloudFront on its own, so quote no CloudFront figure.
Pricing
Purchase options
Pay-as-you-go Per GB out and per 10,000 requests
Rates depend on the viewer’s region and the volume. Always free each month: 1 TB of data transfer out and 10 million HTTP or HTTPS requests.
Flat-rate plans From $0 to $1,000 a month
Free, Pro $15, Business $200 and Premium $1,000 a month. Launched in November 2025. Each plan bundles delivery with WAF, DDoS protection, DNS and logs ingestion, with a monthly allowance of requests and data and no overage charges.
Edge compute Per request
CloudFront Functions are billed per invocation, with a free allowance. Lambda@Edge is billed by requests and duration, at a higher price.
Extras Invalidations, logs, certificates
The first 1,000 invalidation paths a month are free, then a fixed fee per path. Real-time logs, Origin Shield and dedicated IPs are charged separately. ACM certificates are free.
What you actually pay for
- Data transfer out to viewers and requests, or a flat monthly plan
- CloudFront Functions and Lambda@Edge invocations
- Invalidation paths beyond 1,000 a month
- Origin Shield requests, real-time logs and any dedicated IP addresses
- AWS WAF, if you don’t use a plan that bundles it
AWS lists the always-free allowance and the flat-rate plan allowances on its pricing page, and rates differ by region. See the official Amazon CloudFront pricing page and the AWS Pricing Calculator.
Important code references
A static site: a private S3 bucket, an origin access control, a distribution that redirects to HTTPS, compresses and uses the managed CachingOptimized policy, a bucket policy tied to that one distribution, an invalidation and an error-rate check. The CLI tab builds it; Terraform describes the same resources. The Python tab invalidates paths and waits for the result, and creates an expiring signed URL; the C# tab audits every distribution for HTTP access, a missing web ACL, no logging and the old origin access identity. Replace the bucket name and Region with your own.
# Placeholders: replace the bucket name with your own. CloudFront is global, and its API and metrics live in us-east-1.
REGION=us-east-1
BUCKET=cb-site-demo-$RANDOM
ACCOUNT=$(aws sts get-caller-identity --query Account --output text)
# 1. A private bucket for the site, and one page to serve. Nothing is public: only CloudFront will be allowed in.
aws s3api create-bucket --bucket $BUCKET --region $REGION
aws s3api put-public-access-block --bucket $BUCKET \
--public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true
echo '<h1>Hello from the edge</h1>' > index.html
aws s3 cp index.html s3://$BUCKET/index.html --content-type text/html --cache-control "public, max-age=300"
# 2. Origin access control: CloudFront signs its requests to S3, so the bucket can stay private.
OAC_ID=$(aws cloudfront create-origin-access-control --origin-access-control-config \
Name=$BUCKET-oac,OriginAccessControlOriginType=s3,SigningBehavior=always,SigningProtocol=sigv4 \
--query OriginAccessControl.Id --output text)
# 3. The distribution. HTTP is redirected to HTTPS, responses are compressed, and the managed CachingOptimized policy
# (658327ea-...) sets the cache key and TTLs. 403 and 404 from S3 return index.html, which a single-page app needs.
cat > distribution.json <<JSON
{
"CallerReference": "$BUCKET", "Comment": "static site", "Enabled": true, "DefaultRootObject": "index.html",
"PriceClass": "PriceClass_100", "HttpVersion": "http2and3", "IsIPV6Enabled": true,
"Origins": {"Quantity": 1, "Items": [{"Id": "s3-site", "DomainName": "$BUCKET.s3.$REGION.amazonaws.com",
"OriginAccessControlId": "$OAC_ID", "S3OriginConfig": {"OriginAccessIdentity": ""}}]},
"DefaultCacheBehavior": {"TargetOriginId": "s3-site", "ViewerProtocolPolicy": "redirect-to-https", "Compress": true,
"CachePolicyId": "658327ea-f89d-4fab-a63d-7e88639e58f6",
"AllowedMethods": {"Quantity": 2, "Items": ["GET", "HEAD"], "CachedMethods": {"Quantity": 2, "Items": ["GET", "HEAD"]}}},
"CustomErrorResponses": {"Quantity": 2, "Items": [
{"ErrorCode": 403, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10},
{"ErrorCode": 404, "ResponsePagePath": "/index.html", "ResponseCode": "200", "ErrorCachingMinTTL": 10}]}
}
JSON
DIST_ID=$(aws cloudfront create-distribution --distribution-config file://distribution.json --query Distribution.Id --output text)
# 4. Let this one distribution, and nothing else, read the bucket.
cat > bucket-policy.json <<JSON
{"Version": "2012-10-17", "Statement": [{"Effect": "Allow", "Principal": {"Service": "cloudfront.amazonaws.com"},
"Action": "s3:GetObject", "Resource": "arn:aws:s3:::$BUCKET/*",
"Condition": {"StringEquals": {"AWS:SourceArn": "arn:aws:cloudfront::$ACCOUNT:distribution/$DIST_ID"}}}]}
JSON
aws s3api put-bucket-policy --bucket $BUCKET --policy file://bucket-policy.json
# 5. Wait for the deployment, then request the page twice. The first answer says Miss from cloudfront, the second Hit.
aws cloudfront wait distribution-deployed --id $DIST_ID
DOMAIN=$(aws cloudfront get-distribution --id $DIST_ID --query Distribution.DomainName --output text)
curl -sI https://$DOMAIN/ | grep -i -E "^(HTTP|x-cache|age)"
curl -sI https://$DOMAIN/ | grep -i -E "^(HTTP|x-cache|age)"
# 6. After a release, clear the changed pages from the edge caches. The first 1,000 paths a month are free.
aws cloudfront create-invalidation --distribution-id $DIST_ID --paths "/index.html" "/assets/*"
# 7. Edge error rate over the last hour. CloudFront metrics are published in us-east-1 with the Region dimension Global.
aws cloudwatch get-metric-statistics --region us-east-1 --namespace AWS/CloudFront --metric-name 5xxErrorRate \
--dimensions Name=DistributionId,Value=$DIST_ID Name=Region,Value=Global --statistics Average --period 300 \
--start-time $(date -u -d '-1 hour' +%FT%TZ) --end-time $(date -u +%FT%TZ)
# Placeholders: pass in your own bucket name. CloudFront certificates and metrics live in us-east-1.
variable "bucket_name" {
type = string
}
provider "aws" {
region = "us-east-1"
}
data "aws_cloudfront_cache_policy" "optimized" {
name = "Managed-CachingOptimized"
}
data "aws_cloudfront_response_headers_policy" "security" {
name = "Managed-SecurityHeadersPolicy"
}
resource "aws_s3_bucket" "site" {
bucket = var.bucket_name
}
resource "aws_s3_bucket_public_access_block" "site" {
bucket = aws_s3_bucket.site.id
block_public_acls = true
ignore_public_acls = true
block_public_policy = true
restrict_public_buckets = true
}
resource "aws_cloudfront_origin_access_control" "site" {
name = "${var.bucket_name}-oac"
origin_access_control_origin_type = "s3"
signing_behavior = "always"
signing_protocol = "sigv4"
}
resource "aws_cloudfront_distribution" "site" {
enabled = true
is_ipv6_enabled = true
http_version = "http2and3"
price_class = "PriceClass_100"
default_root_object = "index.html"
origin {
origin_id = "s3-site"
domain_name = aws_s3_bucket.site.bucket_regional_domain_name
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"]
compress = true
cache_policy_id = data.aws_cloudfront_cache_policy.optimized.id
response_headers_policy_id = data.aws_cloudfront_response_headers_policy.security.id
}
# S3 answers 403 for a missing key when the caller can't list the bucket, which a single-page app sees on every deep link.
custom_error_response {
error_code = 403
response_code = 200
response_page_path = "/index.html"
error_caching_min_ttl = 10
}
custom_error_response {
error_code = 404
response_code = 200
response_page_path = "/index.html"
error_caching_min_ttl = 10
}
restrictions {
geo_restriction {
restriction_type = "none"
}
}
viewer_certificate {
cloudfront_default_certificate = true # use an ACM certificate (in us-east-1) for your own domain
}
}
data "aws_iam_policy_document" "site" {
statement {
actions = ["s3:GetObject"]
resources = ["${aws_s3_bucket.site.arn}/*"]
principals {
type = "Service"
identifiers = ["cloudfront.amazonaws.com"]
}
condition {
test = "StringEquals"
variable = "AWS:SourceArn"
values = [aws_cloudfront_distribution.site.arn]
}
}
}
resource "aws_s3_bucket_policy" "site" {
bucket = aws_s3_bucket.site.id
policy = data.aws_iam_policy_document.site.json
}
output "domain_name" {
value = aws_cloudfront_distribution.site.domain_name
}
# pip install boto3 cryptography
# Invalidates paths and waits until it is done, and makes a signed URL that stops working after a few minutes.
import datetime as dt
import time
import boto3
from botocore.signers import CloudFrontSigner
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
cloudfront = boto3.client("cloudfront") # the API is global
def invalidate(distribution_id, paths, wait=True):
"""Removes the paths from the edge caches. The caller reference only has to be unique, and the first 1,000 paths a month are free."""
reply = cloudfront.create_invalidation(
DistributionId=distribution_id,
InvalidationBatch={"Paths": {"Quantity": len(paths), "Items": paths}, "CallerReference": "release-%d" % time.time()},
)
invalidation_id = reply["Invalidation"]["Id"]
if wait:
cloudfront.get_waiter("invalidation_completed").wait(DistributionId=distribution_id, Id=invalidation_id)
return invalidation_id
def signed_url(url, key_pair_id, private_key_pem, minutes=10):
"""A URL that CloudFront accepts until it expires. key_pair_id is the ID of the public key in the distribution's key group."""
private_key = serialization.load_pem_private_key(private_key_pem, password=None)
def rsa_signer(message):
return private_key.sign(message, padding.PKCS1v15(), hashes.SHA1()) # CloudFront's canned policy uses RSA with SHA-1
expires = dt.datetime.now(dt.timezone.utc) + dt.timedelta(minutes=minutes)
return CloudFrontSigner(key_pair_id, rsa_signer).generate_presigned_url(url, date_less_than=expires)
if __name__ == "__main__":
distribution = cloudfront.list_distributions()["DistributionList"].get("Items", [])[0]
print("invalidation:", invalidate(distribution["Id"], ["/index.html", "/assets/*"], wait=False))
// dotnet add package AWSSDK.CloudFront
// Audits every distribution: HTTP allowed, no web ACL, logging off, and S3 origins that still use the old origin access identity.
using Amazon.CloudFront;
using Amazon.CloudFront.Model;
using var cloudfront = new AmazonCloudFrontClient();
int problems = 0;
string? marker = null;
do
{
var page = await cloudfront.ListDistributionsAsync(new ListDistributionsRequest { Marker = marker });
foreach (DistributionSummary summary in page.DistributionList.Items ?? new List<DistributionSummary>())
{
DistributionConfig config = (await cloudfront.GetDistributionConfigAsync(new GetDistributionConfigRequest { Id = summary.Id })).DistributionConfig;
string name = summary.Aliases.Items?.FirstOrDefault() ?? summary.DomainName;
if (config.DefaultCacheBehavior.ViewerProtocolPolicy == ViewerProtocolPolicy.AllowAll)
{
Console.WriteLine($"{name}: plain HTTP is allowed (viewer protocol policy allow-all)");
problems++;
}
if (string.IsNullOrEmpty(config.WebACLId))
{
Console.WriteLine($"{name}: no web ACL is attached");
problems++;
}
if (config.Logging?.Enabled != true)
{
Console.WriteLine($"{name}: standard logging is off");
problems++;
}
foreach (Origin origin in config.Origins.Items.Where(o => !string.IsNullOrEmpty(o.S3OriginConfig?.OriginAccessIdentity)))
{
Console.WriteLine($"{name}: origin {origin.Id} uses the old origin access identity, so move it to origin access control");
problems++;
}
}
marker = page.DistributionList.IsTruncated == true ? page.DistributionList.NextMarker : null;
} while (marker != null);
Console.WriteLine(problems == 0 ? "No problems found." : $"{problems} problem(s) found.");
return problems == 0 ? 0 : 1;
Best videos to explore
Videos picked for this service. Each one is labelled with its source, opens on YouTube if you prefer, and loads only when you press play.
Interview questions
BasicWhat is Amazon CloudFront?
It’s AWS’s content delivery network. You create a distribution that points at an origin, such as an S3 bucket or a web server, and CloudFront serves copies of your content from edge locations close to the visitor. That makes pages load faster and keeps most requests away from the origin.
BasicWhat is the difference between an origin and a distribution?
The origin is the server that holds the original content. The distribution is the CloudFront configuration in front of it: the domain, the behaviors that decide caching and protocols, the certificate and the security settings. One distribution can have several origins, chosen by path.
BasicHow do you keep an S3 bucket private but still serve it through CloudFront?
Block all public access on the bucket, create an origin access control, attach it to the S3 origin, and add a bucket policy that allows s3:GetObject for the CloudFront service when AWS:SourceArn matches the distribution. People can then reach the files only through CloudFront.
IntermediateWhat makes up the cache key, and why does it matter?
The cache key decides which requests count as the same object. By default it is the URL path, and a cache policy can add query strings, headers and cookies. A key that is too wide splits the cache into many near-identical copies and gives a low hit ratio, while one that is too narrow can serve the wrong content to the wrong person. Keep it to what changes the response.
IntermediateHow do you deploy a new version of a website without waiting for caches to expire?
Give assets content-hashed file names so a new release uses new URLs, and keep the HTML short-lived. Then invalidate only the entry pages, such as /index.html. Invalidation works but is slow and, beyond the free paths each month, costs money, so it is for exceptions and not the main method.
IntermediateWhen do you choose CloudFront Functions and when Lambda@Edge?
Use CloudFront Functions for short, fast tasks on viewer requests and responses, such as URL rewrites, redirects, header changes and simple token checks. Choose Lambda@Edge when you need more time and memory, network calls, other languages or origin-side events. Functions cost much less and start in well under a millisecond.
AdvancedHow would you protect an origin that sits behind CloudFront?
Make the origin unreachable except through CloudFront. For S3 use origin access control. For a load balancer or instance use a VPC origin in a private subnet, or allow only the CloudFront managed prefix list plus a secret header that CloudFront adds. Add WAF at the distribution, so attacks are filtered before the origin sees them.
AdvancedHow would you serve private content to paying users only?
Make the files private, then issue signed URLs or signed cookies from your application after it checks the user’s entitlement. Trusted key groups hold the public keys, and your server holds the private key. Use short expiry times, restrict by path, rotate keys and combine with logs to catch sharing of links.
AdvancedWhat do you look at when the cache hit ratio is low?
First the cache key: forwarded cookies, headers or query strings that vary per request split the cache. Then the origin’s Cache-Control headers, since no-store or a zero TTL stops caching, and the policy’s minimum and maximum TTL. Check for per-user query strings or tracking parameters, normalise them in a function and use Origin Shield for origins with many misses.
AdvancedHow would you decide between pay-as-you-go and a flat-rate plan?
Estimate monthly data transfer, requests and the security features you need from the logs of the last few months. A plan bundles delivery with WAF, DDoS protection and DNS for a fixed price with allowances, so it favours steady, busy sites that would use WAF anyway. Pay-as-you-go suits spiky or very large workloads and the always-free allowance on tiny sites. You can mix both across distributions, so test on one site first.
Similar or alternative services on other clouds
| Capability | AWS | Azure | Google Cloud |
|---|---|---|---|
| Service | Amazon CloudFront | Azure Front Door | Cloud CDN with an Application Load Balancer |
| What it is | A CDN with edge compute | A CDN plus a global HTTP(S) load balancer and WAF | A cache switched on for a load balancer backend |
| Origins | S3, load balancers, API Gateway, VPC origins, any HTTP server | Storage, App Service, any public origin, Private Link origins (Premium) | Cloud Storage buckets, backend services, external origins through an internet NEG |
| Caching control | Cache policies and behaviors per path | Route caching settings and rule sets | Cache modes, TTLs and cache keys on the backend |
| Code at the edge | CloudFront Functions and Lambda@Edge | Rules engine for rewrites, redirects and headers | Service Extensions on the load balancer |
| Web firewall | AWS WAF | Front Door WAF | Cloud Armor |
| Private origin | Origin access control, VPC origins | Private Link origins (Premium) | Backends inside the VPC behind the load balancer |
| Certificates | Free ACM certificates, in us-east-1 | Managed certificates for custom domains | Google-managed certificates on the load balancer |
| How you are billed | Data out and requests, or a flat-rate plan | Base fee per profile, plus data and requests | Cache egress, cache fill and lookups, plus the load balancer |
Typical origins are Amazon S3 and Amazon API Gateway, and load balancers from Elastic Load Balancing. Metrics and alarms live in Amazon CloudWatch, and code at the edge can be written with AWS Lambda as Lambda@Edge.
Did you find this article helpful?
Your answer helps us improve this page for the next reader.
Sources and further reading
CloudBrum wrote this page in its own words, using the provider’s public documentation listed below as the reference. Features, limits, names and prices change, so confirm anything that matters on the provider’s own pages before you decide.
- What is Amazon CloudFront?Amazon Web Services
- Control the cache key with a cache policyAmazon Web Services
- Restrict access to an Amazon S3 originAmazon Web Services
- Invalidate files to remove contentAmazon Web Services
- Serve private content with signed URLs and signed cookiesAmazon Web Services
- Customize at the edge with functionsAmazon Web Services
- CloudFront flat-rate pricing plansAmazon Web Services
- Restrictions on edge functionsAmazon Web Services
- Amazon CloudFront pricingAmazon Web Services
- Terraform AWS provider: aws_cloudfront_distributionHashiCorp
