Amazon CloudFront
medium 25 minCloudFront is the content delivery network of AWS.
Video lesson · Chapter 1 of 5
The release file travels from Dublin to Tokyo
CloudFront in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
Amazon CloudFront is the content delivery network of AWS. You describe what to deliver in a distribution: the servers that hold the content, called origins, and rules called cache behaviors that say which URL goes to which origin and how long copies may be kept.
When someone requests a URL, DNS leads them to an edge location that can serve them well. If the edge has a copy, it answers. If not, the request goes to a larger regional cache, perhaps to one last shared cache called Origin Shield, and only then to the origin.
Why it exists
The distance between a person and your server costs time on every request, and popular files cost your server the same work again and again. Copies near people fix both. The general ideas are on the CDN page; here we look at how this product does it.
Teams on AWS choose it because it fits the rest: private S3 buckets, load balancers, certificates, the AWS firewall, and no transfer charge between AWS origins and CloudFront.
A short history
18 November 2008
CloudFront opens in beta, as a way to deliver files stored in S3.
July 2017
Lambda@Edge becomes generally available: Node.js functions run on four events of a request.
May 2021
CloudFront Functions arrives, with light JavaScript that runs at the edge locations themselves.
August 2022
HTTP/3 becomes available for viewers.
November 2025
Flat-rate plans appear beside pay-as-you-go, including a free plan.
Words to know
- Distribution
- One CloudFront configuration with its own domain name.
- Origin
- Where the content comes from: S3, a load balancer, or any HTTP server.
- Cache behavior
- Rules for one path pattern: origin, methods, policies, functions.
- Edge location, or PoP
- The place that talks to the viewer.
- Regional edge cache
- A larger cache between edge locations and origins.
- Origin Shield
- One extra cache layer, in one Region, that all other caches go through.
- Cache policy
- The TTL limits and the parts of the cache key.
- OAC
- Origin access control: CloudFront signs its requests so a bucket can stay private.
How it works
Step through the idea, or press Play.
DNS picks an edge location. Usually the nearest in latency
Understand it
Start here
Fruit carts and barns
Fruit is sold from small carts on every corner. A cart holds only what people on that corner like. Behind the carts is a regional barn with more, and far away are the farms. Nobody walks to the farm for an apple.
Each step back is slower and has more choice. A good cart answers most people.
Why
What it is for
Global speed
AWS lists more than 750 PoPs in over 100 cities, 15 regional edge caches and over 1,140 embedded PoPs inside internet providers.
Security at the edge
Shield Standard against DDoS, AWS WAF, geographic restriction, signed URLs.
Edge compute
CloudFront Functions for small work, Lambda@Edge for larger work.
Cost control
No transfer charge from AWS origins to CloudFront. Price classes, Origin Shield and flat-rate plans.
Fits AWS
S3, load balancers, API Gateway, media services, Route 53, ACM certificates, IAM.
Visibility
Access logs, real-time logs, CloudWatch metrics and the X-Cache header.
It carries static files, whole sites, API calls, video segments, large downloads and WebSocket or gRPC connections. Requests that cannot be cached still gain: TLS ends nearby, connections to the origin are reused, and long distances are crossed on the AWS network.
Path
Three cache layers before the origin
Edge, regional cache, Origin Shield, origins
- 1
Resolve the name
DNS returns the address of an edge location that can serve this viewer, typically the nearest in latency. This is the normal mode; fixed anycast addresses exist as a special option for allow lists.
- 2
TLS
The edge uses your certificate, which must be in ACM in
us-east-1. Viewers may use HTTP/1.1, HTTP/2 or HTTP/3 and TLS up to 1.3. - 3
WAF and viewer functions
AWS WAF rules decide first. Then a viewer-request function may rewrite, redirect or refuse.
- 4
Match a behavior
Path patterns are checked in order; the first match wins. The default behavior
*is last. - 5
Edge cache
The cache policy builds the key. A fresh copy is returned.
- 6
Regional edge cache
Larger, so less popular objects stay longer. Uncacheable and write requests skip it.
- 7
Origin Shield
If enabled, all layers fetch through one Region, so one request per object reaches the origin.
- 8
Origin, then back
The response is stored in each layer and compressed if allowed. Origin-response and viewer-response functions may change it.
A request that misses twice
What reaches the origin
Rules
Behaviors: one URL space, many origins
A typical distribution
| Order | Pattern | Origin | Caching |
|---|---|---|---|
| 0 | /api/* | Load balancer | CachingDisabled, all methods |
| 1 | /media/* | S3 bucket | Signed URLs, one day |
| 2 | /static/* | S3 bucket | CachingOptimized, versioned names |
| Last | * (default) | Load balancer | Short TTL for HTML |
/static/* came after a broader pattern, it would never be used.Which rule, which cache?
Each behavior chooses the origin or origin group, allowed methods, viewer protocol, cache policy, what is forwarded to the origin, compression, signing and functions. The cache policy controls the key; an origin request policy may forward more to the origin without splitting the cache.
Cache
Keys and TTLs
By default the key is the distribution's domain and the path. Add a header, cookie or query string only if the response truly depends on it. Adding User-Agent creates thousands of versions of the same file.
How long, and with what key?
TTL rules
| Case | Result |
|---|---|
| No cache header, common policy | Default TTL, 24 hours in CachingOptimized |
max-age or s-maxage from the origin | Used, kept between the minimum and maximum TTL |
no-store or private, minimum TTL 0 | Not cached |
no-store, minimum TTL above 0 | Cached anyway for the minimum TTL |
| Error response | 10 seconds by default (error caching minimum TTL) |
stale-while-revalidate, stale-if-error | Old copy may be served meanwhile |
Shield
When Origin Shield pays
Turn it on
- Viewers in many regions
- Origins that work hard per request, such as packaging or image resizing
- Little origin capacity, or a second CDN in front of the same origin
- After deployments, when many misses arrive together
Skip it
- Content that cannot be cached
- Viewers in one region near the origin
- gRPC: those requests bypass it
- When the extra charge is more than the origin work saved
Choose the AWS Region with the lowest latency to the origin; for an origin in AWS that is its own Region, or the nearest one offered. A full miss pays one hop more.
Change
Getting new content out
| Method | How | Know this |
|---|---|---|
| Versioned file name | main.3f9a.js | Works in browsers too, no charge, easy rollback |
| Invalidate paths | /images/* | First 1,000 paths a month are free; a wildcard counts as one path |
| Invalidate by tag | #product:42 | Needs CacheTagConfig and a tag header from the origin |
| Short TTL | max-age=30 | Simple; costs hits |
Code
Two kinds of edge functions
Where functions sit on the way in
CloudFront Functions and Lambda@Edge
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Runs on | Viewer request and response | All four events |
| Language | JavaScript | Node.js, Python |
| Time | Under a millisecond | Up to 30 seconds |
| Memory | 2 MB | 128 MB viewer events; up to 10 GB origin events |
| Code size | 10 KB | 50 MB compressed |
| Network | One call per run, to an origin of the same distribution, 1 second | Any destination |
| Request body, files | No | Yes |
| Built-in data | KeyValueStore | None |
| Deployed from | CloudFront | A numbered version in us-east-1 |
function handler(event) { var request = event.request; if (request.uri.endsWith("/")) { request.uri += "index.html"; } else if (!request.uri.split("/").pop().includes(".")) { request.uri += "/index.html"; } return request;}Failure
Origin failover
Origin group
An origin group has a primary and a secondary. You choose the status codes that mean failure: 403, 404, 429, 500, 502, 503, 504. Failover applies to GET, HEAD and OPTIONS only, per request, with no health checks in between. A POST is never repeated for you.
How long before it gives up on connecting
Security
Private content and private origins
| Layer | Stops | Note |
|---|---|---|
| Shield Standard | Network floods | Included. Shield Advanced is a paid service with a response team |
| AWS WAF | Injection, bad bots, high rates | Runs before the cache |
| Geographic restriction | Whole countries | Allow list or block list |
| Signed URL | Links without permission | One file; has an end time |
| Signed cookies | The same, for many files | Streaming, whole folders; URLs stay unchanged |
| OAC | Reading the bucket directly | Replaces OAI; supports SSE-KMS and all Regions |
| TLS policy | Old protocols | Minimum version per distribution |
The gates in order
Run
Operate it: metrics, errors, cost
Read the signs
| Sign | Usual cause | Do |
|---|---|---|
| Miss from cloudfront, always | Key too wide, TTL 0, cookies in key | Trim the cache policy |
| 403 from S3 | Bucket policy or OAC, or a missing key without list permission | Check the policy for this distribution |
| 502 | TLS or name problem with the origin | Certificate and host name |
| 504 | Origin slow or blocked | Firewall, timeout, slow work |
| Old content | Long TTL or browser copy | Versioned names |
| Certificate not offered | It is in another Region | Request it in us-east-1 |
Quotas and promises: the service level agreement is 99.9% a month, with credits below that. Cost depends on data out, requests, region, functions, invalidations and shield, or on a flat-rate plan without overage charges. Model the mix before you decide; check the pricing page for today's numbers.
HTTP/3 is a setting on the distribution, with no code change. QUIC avoids head-of-line blocking between streams, resumes quickly and survives a change of network; browsers fall back when UDP is blocked. Details: HTTP/2 and HTTP/3.
Decide
When to choose it
Choose it when
- Origins are in AWS
- Static sites, images, downloads from S3
- APIs and pages with short TTLs
- HLS or DASH video
- Private content with signatures
- WAF, Shield and IAM are already yours
- Small edge logic without servers
Think again when
- Everything is personal and uncacheable
- All users sit beside the origin
- You want no dependence on AWS
- You need purges worldwide in fractions of a second
- Even an edge hit is too slow
- The team wants a simpler bill than usage pricing (or look at the flat-rate plans)
Compared with others
| Network | Closest in | Differs in | Choose it for |
|---|---|---|---|
| Cloudflare | Cache, WAF, edge code, HTTP/3 | Anycast routing; purge under 150 ms median; not tied to one cloud | Origins anywhere, quick start |
| Fastly | Cache, edge code, logs | VCL configuration, fast purge | Fine control of caching |
| Akamai | Reach, security | More sites, enterprise sales | Very large media |
| Google Cloud CDN | Cache, anycast | Part of Google's load balancer | Origins in Google Cloud |
| Azure Front Door | Cache, WAF, routing | Microsoft's successor to Azure CDN classic, which retires on 30 September 2027 | Origins in Azure |
Resources: Oac: Type: AWS::CloudFront::OriginAccessControl Properties: OriginAccessControlConfig: Name: site-oac OriginAccessControlOriginType: s3 SigningBehavior: always SigningProtocol: sigv4 Distribution: Type: AWS::CloudFront::Distribution Properties: DistributionConfig: Enabled: true HttpVersion: http2and3 DefaultRootObject: index.html Origins: - Id: site DomainName: !GetAtt Bucket.RegionalDomainName OriginAccessControlId: !GetAtt Oac.Id S3OriginConfig: OriginAccessIdentity: "" # empty: OAC is used instead DefaultCacheBehavior: TargetOriginId: site ViewerProtocolPolicy: redirect-to-https Compress: true CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6 # CachingOptimizedSummary
The whole topic in one minute.
A distribution routes URL patterns to origins. Requests fall through edge, regional cache and optional Origin Shield, and each layer answers when it can. Cache key and TTL decide the hit ratio; versioned file names make most invalidations unnecessary.
CloudFront Functions do small work on every request, Lambda@Edge does larger work. Origin groups retry a failed read on a second origin, OAC keeps buckets private and signed URLs keep content private. Choose it when the origins are in AWS.
- A distribution holds origins and ordered behaviors; first match wins.
- Edge, regional cache, Origin Shield: each layer removes misses.
- Keep cache keys small and the minimum TTL at 0 for personal data.
- Version names first, invalidate by path or tag second.
- Functions for small work on every request, Lambda@Edge for larger work.
- Origin groups repeat reads only; shorten the connection timeout.
- OAC for private buckets, signed URLs or cookies for private content.
Sources
- AWS: how CloudFront delivers content
- AWS: CloudFront features and locations
- AWS: CloudFront Functions and Lambda@Edge compared
- AWS: origin failover
- AWS: Origin Shield
- AWS: how long content stays in the cache
- AWS: invalidating by cache tags
- AWS: restrict access to an S3 origin
- AWS: HTTP/3 for CloudFront
- AWS: CloudFront quotas