Understanding CloudFront Distributions, Origins and Cache Behaviours
This lesson introduces how Amazon CloudFront delivers content: edge locations and regional edge caches, distributions, origins, cache behaviours, which responses are cached and how CloudFront is priced. The later lessons in this module build on these ideas.
Learning outcomes
After completing this lesson, you will be able to:
- Describe how CloudFront serves a cache hit and a cache miss.
- Explain what a distribution contains, and what a custom domain name requires.
- Distinguish S3 origins, custom origins and origin groups.
- Explain how cache behaviours are matched to requests and which settings they control.
- Identify which responses CloudFront caches and the components of its pricing.
How CloudFront serves a request
Amazon CloudFront is a content delivery network (CDN): a global set of servers that sit between users, called viewers, and the servers that hold the content, called origins. CloudFront runs in hundreds of edge locations worldwide, backed by a smaller number of larger regional edge caches. A request passes through them as follows.
- DNS directs the viewer to an edge location that offers low latency for that viewer.
- The edge location looks for the object in its cache. If it is there and still fresh, a cache hit, CloudFront returns it immediately.
- On a cache miss, the edge location asks the regional edge cache, which may already hold the object.
- If neither has it, CloudFront fetches the object from the origin over the AWS network, returns it to the viewer and caches it for later requests.
Serving from the cache reduces latency for viewers and load on the origin. Even content that cannot be cached, such as API responses, benefits: the HTTPS connection is established close to the viewer, and the request then travels over AWS's network on connections that CloudFront keeps open to the origin. Every distribution is also protected by AWS Shield Standard, and AWS WAF can be attached to it.
Distributions
A distribution is the CloudFront configuration for one website or application. It lists the origins, the cache behaviours that decide how requests are handled, and settings that apply to the whole distribution. CloudFront is a global service, so a distribution is not created in a Region, and its configuration is deployed to every edge location; changes take a few minutes to propagate.
Each distribution has a domain name such as d111111abcdef8.cloudfront.net. To serve it under the application's own name, such as www.example.com, the distribution lists that name as an alternate domain name and uses an AWS Certificate Manager certificate that covers it, which must be requested in the US East (N. Virginia) Region. A DNS record, such as a Route 53 alias record, then points the name at the distribution. Other distribution-wide settings include the price class, which can exclude the most expensive edge locations to reduce cost, the default root object, such as index.html, and access logging.
Origins
An origin is where CloudFront fetches content that is not in its cache. A distribution can have several, and the main kinds are described below.
Amazon S3 buckets
An S3 bucket is the usual origin for static files, such as images, style sheets and the files of a single-page application. With origin access control, the bucket stays private and accepts requests only from the distribution, as Securing Content with Origin Access Control, Signed URLs and HTTPS explains.
Custom origins
Any HTTP server can be a custom origin: an Application Load Balancer, an API Gateway API, a Lambda function URL, an EC2 instance or a server outside AWS. CloudFront connects to it over HTTP or HTTPS as configured, and it can add custom headers to each origin request, for example a secret header that the origin checks to reject requests that bypass CloudFront.
Origin groups
An origin group pairs a primary and a secondary origin. If the primary returns one of the chosen error status codes or cannot be reached, CloudFront retries the request on the secondary, which provides failover for GET, HEAD and OPTIONS requests. The following table summarises the origin types.
| Origin | Typical content | Notes |
|---|---|---|
| S3 bucket | Static files | Keep the bucket private with origin access control |
| Custom origin | Dynamic pages and APIs | ALB, API Gateway, function URL, EC2 or any HTTP server |
| Origin group | Content that needs failover | Retries reads on a secondary origin |
Cache behaviours
A cache behaviour applies a set of rules to requests whose path matches a pattern, such as /api/* or *.jpg. Every distribution has a default behaviour, with the pattern *, which is always evaluated last and handles requests that match no other behaviour. CloudFront checks the other behaviours in their configured order and uses the first match, so specific patterns, such as /api/public/*, must come before general ones, such as /api/*.
Each behaviour chooses the origin for its requests and configures how they are handled. Its main settings are described in the following list.
- Viewer protocol policy: allow HTTP and HTTPS, redirect HTTP to HTTPS, or accept HTTPS only.
- Allowed HTTP methods:
GETandHEAD; those plusOPTIONS; or all seven methods, includingPOST,PUTandDELETE. CloudFront caches only responses toGETandHEAD, and optionallyOPTIONS, and forwards the others to the origin. - Cache policy and origin request policy: what forms the cache key, how long objects are cached and what is forwarded to the origin, as Improving Cache Hit Ratios with CloudFront Cache Policies explains.
- Function associations: CloudFront Functions or Lambda@Edge code that runs on requests or responses.
- Restrict viewer access: require signed URLs or signed cookies for the content.
Behaviours let one distribution serve a whole application, with different settings for static files and for API calls, as the worked example below shows.
What CloudFront caches
CloudFront caches a response for the time that its cache policy and the origin's Cache-Control header allow, as the cache policies lesson explains. Some responses are never cached: those to methods other than GET, HEAD and optionally OPTIONS, and those whose Cache-Control header contains no-store or private. Error responses, such as a 404, are cached for a short time, 10 seconds by default, so that a failing origin is not overwhelmed by repeated requests; custom error responses can change that time and return a friendly error page.
Static assets with versioned file names can be cached for a long time, while personalised or rapidly changing responses usually use a behaviour with caching disabled. Updating a cached object before it expires requires an invalidation or a new file name.
How CloudFront is priced
With pay-as-you-go pricing, CloudFront charges for data transferred out to viewers, which varies by geographic area, and for the number of HTTP and HTTPS requests. Data transferred from AWS origins, such as S3 or an Application Load Balancer, to CloudFront is not charged, so serving S3 content through CloudFront is often cheaper than serving it directly. The first 1,000 invalidation paths each month are free, and the price class setting reduces cost by using fewer edge locations. AWS also offers flat-rate monthly plans that combine CloudFront with AWS WAF and other features.
One distribution for a web application and its API
A team hosts a single-page application in a private S3 bucket and its API in API Gateway. They want one domain, app.example.com, for both, so that the browser never makes cross-origin requests. The distribution has two origins and the following behaviours, listed in the order CloudFront evaluates them.
| Path pattern | Origin | Allowed methods | Caching |
|---|---|---|---|
/api/* | API Gateway (custom origin) | All seven | Disabled; headers, query strings and cookies forwarded |
/assets/* | S3 bucket with origin access control | GET, HEAD | Long TTL; file names are versioned |
* (default) | S3 bucket with origin access control | GET, HEAD | Short TTL for index.html |
After launch, page loads work but every form submission fails with 403 from CloudFront. The /api/* behaviour had been created with the default allowed methods, GET and HEAD, so CloudFront rejected the POST requests before they reached API Gateway. Changing the behaviour to allow all seven methods fixed the problem. Later, the team added a cached /api/catalogue/* behaviour for product data. It had no effect until it was moved above /api/*, because CloudFront uses the first pattern that matches.
A distribution has an /api/* behaviour followed by an /api/public/* behaviour. Why is the second behaviour never used, and how is it fixed?
Show answer
CloudFront uses the first behaviour whose path pattern matches, and /api/* matches every /api/public/ path. Moving /api/public/* above /api/* makes it match first.
Exam Tips
Remember for the exam
- CloudFront serves cache hits from edge locations, checks regional edge caches on a miss, and fetches from the origin only when neither has the object.
- A distribution is global; its alternate domain names need an ACM certificate in US East (N. Virginia) and a DNS record such as a Route 53 alias.
- Origins are S3 buckets (private with origin access control) or custom HTTP origins such as an ALB, API Gateway or a function URL; origin groups add failover for reads.
- Cache behaviours match path patterns in order and the first match wins; the default
*behaviour is always evaluated last and catches the rest. - Only
GET,HEADand optionallyOPTIONSresponses are cached; a behaviour must allow all methods before it can forwardPOST,PUTorDELETE. - Data transfer from AWS origins to CloudFront is free, and the price class reduces cost by limiting edge locations.