skip to content

CloudFront

CloudFront is the AWS CDN: distributions, origins, cache behaviors, TLS, and signed URLs for private content. You learn it as the edge layer in front of S3 and your load balancer, where caching decisions cut both latency and egress cost.

part ofAWSoverview, primer and where to startread it →
on this pageshow

explore

questions

17

In a CloudFront distribution, what is the difference between an origin and a cache behavior, and how does CloudFront decide which origin serves an incoming request?

level: juniorimportance: must knowfreq 70%

answer

  1. two lists: backends and routing rules
  2. path pattern picks the origin
  3. order matters, first match wins
  4. default behavior is the catch-all
  5. one distribution, several backends

basics

~20 s

An origin is a backend CloudFront fetches from: an S3 bucket, a load balancer, any HTTP server. A cache behavior maps a URL path pattern to one origin. CloudFront tests behaviors in their configured order and falls back to the default behavior.

solid answer

~50 s

A distribution holds two separate lists. **Origins** are the backends: each has an id, a domain name (an S3 bucket, an ALB, an EC2 host, any reachable HTTP server) and connection settings such as the origin protocol policy, an optional origin path and custom headers. **Cache behaviors** are the routing layer: each has a path pattern, a `TargetOriginId` naming the origin it sends matching requests to, and its own handling settings — viewer protocol policy, allowed HTTP methods, cache policy, origin request policy, function associations. When a request reaches an edge location, CloudFront walks the ordered cache behaviors and uses the *first* whose path pattern matches; if none match, the default cache behavior (path pattern `*`) handles it. Origins say what the backends are; behaviors say which backend a path goes to and on what terms. That split is what lets one domain front several backends.

code

json · 23 lines
json
{
  "Origins": {
    "Quantity": 2,
    "Items": [
      { "Id": "spa-bucket", "DomainName": "app-assets.s3.eu-west-1.amazonaws.com" },
      { "Id": "api-alb", "DomainName": "api-alb-123.eu-west-1.elb.amazonaws.com" }
    ]
  },
  "CacheBehaviors": {
    "Quantity": 1,
    "Items": [
      {
        "PathPattern": "/api/*",
        "TargetOriginId": "api-alb",
        "ViewerProtocolPolicy": "redirect-to-https"
      }
    ]
  },
  "DefaultCacheBehavior": {
    "TargetOriginId": "spa-bucket",
    "ViewerProtocolPolicy": "redirect-to-https"
  }
}

go deeper

for a junior

Be able to say plainly that origins are the backends and cache behaviors route path patterns to them, and that the default behavior catches whatever nothing else matched.

for a middle

Explain the precedence order and that the first matching pattern wins, and name the settings that live per behavior — allowed methods, viewer protocol policy, cache and origin request policies.

for a senior

Show you design with the split: one hostname fronting static and dynamic backends, methods and timeouts tuned per behavior, and awareness that a mis-ordered pattern silently shadows the rule below it.

for a principal

Own the question of how many distributions an estate should have — behavior sprawl in one distribution versus per-service distributions, and what each choice costs in change blast radius and ownership boundaries.

## Two lists, not one A CloudFront distribution is a configuration document containing two independent lists: `Origins`, and `CacheBehaviors` plus exactly one `DefaultCacheBehavior`. Grasping that they are separate is most of what this question tests — an engineer who believes a distribution has *an* origin (singular) cannot design anything past a single static site. ## Origins: the backends An origin is a place CloudFront can fetch from. Each entry carries an `Id` you choose, a `DomainName`, and per-origin settings. The main flavours: - **S3 bucket origin** — the bucket's REST endpoint (`my-bucket.s3.eu-west-1.amazonaws.com`). CloudFront treats this specially and can sign requests to it with Origin Access Control. - **Custom origin** — any HTTP(S) endpoint: an Application Load Balancer, an EC2 instance, an API Gateway endpoint, a Lambda function URL, a server in your own data centre, or even an S3 bucket configured as a static *website* endpoint (that variant is a custom origin, not a bucket origin, because it speaks plain HTTP and is public). - **VPC origin** — a private ALB, NLB or EC2 instance inside your VPC, reached without exposing it to the internet. - **Origin group** — a primary/secondary pair used as a behavior's target for failover. Per-origin settings include the origin protocol policy (`http-only`, `https-only`, `match-viewer`), an origin path prefix that CloudFront prepends before forwarding, custom headers CloudFront injects on every origin request, and — for custom origins only — connection and read timeouts and retry counts. ## Cache behaviors: the routing table Each cache behavior is a rule. Its `PathPattern` is matched against the request path with `*` and `?` wildcards — for example `/api/*`, `/static/*`, `*.jpg`. Matching is **case-sensitive** and there is no regular-expression support; you cannot match on the query string or on a header here. The critical mechanic is ordering. Behaviors are an ordered list with an explicit precedence, CloudFront evaluates them from the top, and the **first** match wins — later, more specific patterns never get a chance. Put `/api/v2/*` above `/api/*`, not below it. The default cache behavior is implicit last and its pattern is `*`; every distribution has one and you cannot delete it. Besides the target origin, each behavior owns: - `ViewerProtocolPolicy` — `allow-all`, `redirect-to-https`, or `https-only`. - `AllowedMethods` — GET/HEAD, plus OPTIONS, plus the write methods. A behavior pointing at an S3 bucket origin normally allows only reads; an API behavior needs POST, PUT, PATCH and DELETE. - A cache policy and an origin request policy, which decide what is cached and what is forwarded. - Optional response headers policy and edge function associations. ```json { "Origins": [ { "Id": "spa-bucket", "DomainName": "app-assets.s3.eu-west-1.amazonaws.com" }, { "Id": "api-alb", "DomainName": "api-alb-123.eu-west-1.elb.amazonaws.com" } ], "CacheBehaviors": [ { "PathPattern": "/api/*", "TargetOriginId": "api-alb" } ], "DefaultCacheBehavior": { "TargetOriginId": "spa-bucket" } } ``` ## Why the split matters Because routing is per-behavior, one distribution and one certificate can serve a static front end and a dynamic API under the same hostname, each with its own methods, caching and origin. It also means a mistake is per-behavior: an API behavior that inherits the default's read-only method set will reject every POST with 403, and a `/static/*` behavior placed below a `*`-like pattern will simply never fire. ## Common confusions An origin is not a target group and CloudFront does not load-balance across origins — if you want several backends behind one behavior, put a load balancer in front and make that the origin, or use an origin group for failover only. And origins are shared: several behaviors may point at the same origin id with completely different settings.

  • You add a behavior for `/api/v2/*` below an existing `/api/*` behavior and it never seems to take effect. Why?
    CloudFront evaluates cache behaviors in their configured precedence order and stops at the first path pattern that matches. `/api/*` already matches `/api/v2/anything`, so the more specific rule below it is unreachable. Move `/api/v2/*` above `/api/*`. The rule of thumb is most-specific-first, with the default `*` behavior always last.
  • What is the practical difference between using an S3 bucket origin and pointing CloudFront at the same bucket's static website endpoint?
    The bucket endpoint is an S3 REST origin: CloudFront can sign requests with Origin Access Control, so the bucket stays private. The website endpoint is a plain HTTP custom origin: it requires public access and cannot be locked to CloudFront, but it does provide S3's own index-document and redirect handling. Private content means the bucket origin.
  • Can one cache behavior send requests to more than one origin?
    No. A behavior names exactly one `TargetOriginId`. The only multi-backend construct is an origin group, which is a primary/secondary pair for failover, not load balancing. To spread traffic across several instances, put an ALB or NLB in front of them and make the load balancer the origin.

saying these in an interview costs you the question

  • Thinks a distribution can only have one origin
  • Assumes CloudFront load-balances requests across origins
  • Believes the longest matching path pattern wins
  • Thinks path patterns support regular expressions
  • Confuses an origin with an ALB target group

context

open as a page

In CloudFront, what decides the cache key for a request, and what happens to a query string, cookie or header that is named in neither the cache policy nor the origin request policy attached to the cache behavior?

level: middleimportance: must knowfreq 65%

basics

~20 s

CloudFront's cache key is the distribution, the matched cache behavior and exactly the query strings, headers and cookies named in the attached cache policy. Values named in neither policy are stripped, so the origin never sees them at all.

open as a page

How do you configure a CloudFront distribution and an S3 bucket so the bucket's objects are readable only through the distribution, and what does Origin Access Control (OAC) do that the legacy Origin Access Identity (OAI) does not?

level: middleimportance: must knowfreq 66%

basics

~20 s

Use the bucket's REST endpoint as the origin, keep Block Public Access on, and attach an Origin Access Control so CloudFront signs each origin request with SigV4; the bucket then grants read only to the CloudFront service principal for that distribution. OAC, unlike OAI, works with SSE-KMS objects and non-GET methods.

open as a page

CloudFront supports both CloudFront Functions and Lambda@Edge. Which trigger points can each hook into, and how would you choose between them for a given piece of edge logic?

level: middleimportance: must knowfreq 66%

basics

~20 s

CloudFront Functions run only on viewer request and viewer response, in a tiny sandboxed JavaScript runtime with no network access — ideal for header and URI rewrites. Lambda@Edge also hooks origin request and origin response, and can call other services.

open as a page

In Amazon CloudFront, when would you protect private content with signed URLs versus signed cookies, and what does a trusted key group have to do with either?

level: middleimportance: must knowfreq 62%

basics

~20 s

CloudFront signed URLs authorize one object each and change the URL; signed cookies authorize many objects and leave URLs unchanged. Both are verified by CloudFront against the public keys in the trusted key group attached to that cache behavior.

open as a page

Your CI pipeline creates a CloudFront invalidation for /* after every deploy, and the team deploys dozens of times a day. What problems does that create, and what would you do instead?

level: seniorimportance: must knowfreq 60%

basics

~20 s

Invalidating /* dumps the entire edge cache on every deploy, so the origin absorbs a burst of misses and users see uncached latency; frequent wildcard invalidations also queue against concurrency quotas. Ship content-hashed filenames and invalidate only the unversioned entry documents.

open as a page

In CloudFront, what does creating an invalidation for the path /index.html actually do, and how does it differ from simply letting that object's TTL expire?

level: juniorimportance: should knowfreq 58%

basics

~20 s

A CloudFront invalidation asks every edge cache to drop its copy of the named paths, so the next request fetches from the origin. TTL expiry does the same thing passively, one edge at a time, when the object ages out.

open as a page

You are adding cdn.example.com to a CloudFront distribution as an alternate domain name, but the ACM certificate you issued in eu-west-1 does not appear in the certificate list. Why, and what do you do about it?

level: juniorimportance: should knowfreq 42%

basics

~10 s

ACM certificates are Regional, and CloudFront reads viewer certificates only from us-east-1 (N. Virginia). Request or import the certificate again in us-east-1, covering cdn.example.com, then select it on the distribution.

open as a page

A CloudFront cache policy sets Minimum TTL to 3600, Default TTL to 86400 and Maximum TTL to 31536000. The origin returns Cache-Control: no-cache on an HTML page, yet viewers keep getting an hour-old copy. Explain how CloudFront combines its own TTL settings with the origin's caching headers.

level: middleimportance: should knowfreq 50%

basics

~20 s

CloudFront clamps the origin's declared lifetime between the cache policy's Minimum and Maximum TTL, and uses Default TTL only when the origin declares nothing. A Minimum TTL above zero therefore overrides the origin's no-cache and pins the object for at least that long.

open as a page

You must serve a single-page app's static files from an S3 bucket and its JSON API from an Application Load Balancer, both under https://app.example.com. How do you shape the CloudFront distribution, and what does putting them on one domain buy you?

level: middleimportance: should knowfreq 58%

basics

~20 s

Define two origins on one distribution: the S3 bucket and the ALB. Give the default cache behavior the bucket, add an ordered /api/* behavior targeting the ALB with write methods allowed and caching off. One hostname means one certificate, same-origin requests and no CORS.

open as a page

Your CloudFront distribution uses an internet-facing Application Load Balancer as its origin, so anyone who discovers the ALB's DNS name can call it directly and bypass the CDN. How do you make the ALB accept traffic only from your distribution?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Combine two controls: restrict the ALB's security group to the AWS-managed CloudFront origin-facing prefix list, and have CloudFront inject a secret custom origin header that an ALB listener rule requires, with the default rule returning 403. Alternatively make the ALB private and use a CloudFront VPC origin.

open as a page

How do you put AWS WAF and AWS Shield in front of an Amazon CloudFront distribution, and what does each of them actually protect you from?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Create an AWS WAF web ACL with CloudFront scope (managed from us-east-1) and associate it with the distribution; it filters application-layer requests at the edge. Shield Standard protects network and transport layer floods automatically; Shield Advanced adds paid response support and cost protection.

open as a page

For a subscription streaming service, how would you decide between enforcing entitlement with CloudFront signed cookies at the edge and having every media request authorized by your own API?

level: principalimportance: should knowfreq 28%

basics

~20 s

Edge enforcement trades revocation and audit granularity for cache efficiency and latency. Authorize once at your API, issue short-lived signed cookies, and keep per-request checks at the origin only where an immediate decision genuinely matters.

open as a page

In a CloudFront cache policy, what do the EnableAcceptEncodingGzip and EnableAcceptEncodingBrotli settings do, and why are they preferable to listing Accept-Encoding in the policy's header list?

level: middleimportance: nice to knowfreq 28%

basics

~20 s

Those settings make CloudFront normalize the viewer's Accept-Encoding down to gzip, br or nothing before using it in the cache key and the origin request, so a URL holds a few compressed variants instead of one per raw header string.

open as a page

What does a CloudFront origin group with origin failover actually do, and which requests and failure modes does it not cover?

level: seniorimportance: nice to knowfreq 28%

basics

~20 s

An origin group pairs a primary and a secondary origin: when the primary returns one of the configured failover status codes, or the connection fails or times out, CloudFront retries that same request against the secondary. It covers only GET, HEAD and OPTIONS, and it is a per-request retry, not a health check.

open as a page

CloudFront offers a built-in geographic restriction setting and AWS WAF offers a geo match rule. What can each do that the other cannot, and what would you tell a stakeholder who calls either one a compliance guarantee?

level: seniorimportance: nice to knowfreq 34%

basics

~20 s

CloudFront geo restriction is a free country allowlist or blocklist applied to the whole distribution. A WAF geo match rule is per-rule, combinable with path and rate conditions, and costs WAF pricing. Both infer country from IP address, so neither is authoritative.

open as a page