Prev Next

Cloud / Amazon CloudFront Interview questions

Last updated

1. What is Amazon CloudFront? 2. What is a CDN, and why use CloudFront for it? 3. What are CloudFront edge locations? 4. What is an origin in CloudFront? 5. What are CloudFront distributions? 6. What are CloudFront cache behaviors? 7. What is a CloudFront invalidation? 8. What are signed URLs in CloudFront? 9. What are signed cookies in CloudFront? 10. What is Origin Access Control (OAC) in CloudFront? 11. What are CloudFront Functions? 12. What is Lambda@Edge? 13. What is the CloudFront cache key? 14. What are CloudFront price classes? 15. Define TTL in CloudFront caching? 16. Describe how CloudFront handles HTTPS certificates? 17. List the HTTP methods CloudFront supports? 18. How do you use custom error pages in CloudFront? 19. What is a CloudFront distribution's domain name? 20. How do you use Amazon S3 as a CloudFront origin? 21. What is the difference between CloudFront and an Application Load Balancer? 22. How does CloudFront cache invalidation compare to versioned URLs, and when should you use each? 23. Why should you use Origin Access Control instead of Origin Access Identity? 24. How does CloudFront decide which cache behavior applies to a request? 25. What is the difference between CloudFront Functions and Lambda@Edge? 26. When should you choose Lambda@Edge over CloudFront Functions? 27. How can you optimize CloudFront's cache hit ratio? 28. Explain the request lifecycle when a viewer requests an object through CloudFront? 29. How does CloudFront handle query string and header-based caching? 30. Why doesn't CloudFront cache POST requests by default? 31. What happens when an origin returns an error to CloudFront? 32. How do you troubleshoot a low cache hit ratio in CloudFront? 33. Explain the internal working of CloudFront's regional edge caches? 34. How does CloudFront integrate with AWS WAF? 35. What is the difference between CloudFront and Amazon S3 Transfer Acceleration? 36. Why should you use field-level encryption in CloudFront? 37. How does CloudFront support real-time logs? 38. When would you choose a custom origin over an S3 origin? 39. Explain the execution flow of Lambda@Edge across its four trigger points? 40. How can you optimize CloudFront costs? 41. Why is Origin Shield useful in a CloudFront architecture? 42. What is the difference between CloudFront's price classes, and how do you choose one? 43. How does CloudFront handle HTTP/2 and HTTP/3? 44. Explain the lifecycle of a TLS handshake in CloudFront with a custom domain? 45. How do you troubleshoot a 403 error from CloudFront on an S3 origin? 46. Why should you enable origin failover in CloudFront? 47. How does path pattern precedence work in CloudFront cache behaviors? 48. What is the difference between edge locations and regional edge caches? 49. How can you secure a CloudFront distribution end-to-end? 50. Explain how CloudFront supports multi-region origin failover and disaster recovery?

1. What is Amazon CloudFront?

Amazon CloudFront is AWS's content delivery network (CDN) service. It caches and serves static and dynamic content - HTML, CSS, JavaScript, images, video, and API responses - from a global network of edge locations so requests don't have to travel all the way back to the origin server.

CloudFront sits in front of an origin, which can be an S3 bucket, an EC2 instance, an Application Load Balancer, or any custom HTTP server. It integrates natively with services like S3, ACM, Route 53, Lambda@Edge, and AWS WAF.

Typical use cases include accelerating static websites, streaming video, speeding up API responses, and adding a security layer in front of an application.

Take quiz
CloudFront is best described as:
AWS's content delivery network (CDN)
A relational database service
A container orchestration service
A CloudFront origin can be:
Only an S3 bucket
Only an EC2 instance
An S3 bucket, EC2/ALB, or any custom HTTP server

2. What is a CDN, and why use CloudFront for it?

A content delivery network (CDN) is a geographically distributed set of servers that cache copies of content close to end users, cutting down the network distance - and therefore latency - between a viewer and the content they're requesting.

CloudFront is AWS's CDN. Reasons teams pick it over a third-party CDN include tight integration with S3, EC2, Lambda, and ACM; a global network of edge locations; pay-as-you-go pricing; built-in DDoS protection through AWS Shield Standard at no extra cost; and the ability to run custom logic at the edge with CloudFront Functions and Lambda@Edge.

For workloads already living in AWS, CloudFront also avoids extra egress hops to a third-party CDN's own infrastructure.

Take quiz
A CDN primarily reduces:
Storage costs only
Network distance/latency between viewers and content
The number of DNS records needed
A reason to choose CloudFront over a third-party CDN is:
Tight integration with S3, EC2, Lambda, and ACM
It requires a separate AWS account
It doesn't support HTTPS

3. What are CloudFront edge locations?

Edge locations (also called points of presence, or POPs) are the physical data centers CloudFront uses to cache content near viewers. There are hundreds spread across the globe, and they are separate from AWS Regions and Availability Zones.

When a viewer makes a request, DNS routes it to the edge location that offers the lowest latency. If the requested object is already cached there, CloudFront serves it immediately - a cache hit. If not, CloudFront looks further upstream (a regional edge cache, then the origin) before returning and caching the response.

Because edge locations have finite storage, less-popular objects can get evicted to make room for more frequently requested ones.

Take quiz
CloudFront edge locations are:
The same as AWS Availability Zones
Only located in the US
Physical PoPs separate from AWS Regions/AZs
If content isn't cached at an edge location, CloudFront:
Immediately returns an error
Checks further upstream (regional edge cache, then origin)
Deletes the distribution

4. What is an origin in CloudFront?

An origin is the source CloudFront pulls content from when it can't serve a request out of cache. Every cache behavior in a distribution points to exactly one origin (or an origin group for failover).

CloudFront supports two origin types:

  • S3 origin - an S3 bucket accessed through its REST API endpoint (recommended, supports Origin Access Control) or, less commonly, its static website hosting endpoint.
  • Custom origin - any HTTP server, such as an EC2 instance, an Application Load Balancer, an on-premises server, or another CDN, reachable over HTTP or HTTPS.

A single distribution can define multiple origins and route different path patterns to each one via its cache behaviors.

Take quiz
The two CloudFront origin types are:
S3 origin and custom origin
Only Lambda origins
Database origin and file origin
A single distribution can:
Only ever use one origin, period
Never use more than one cache behavior
Define multiple origins routed by path pattern

5. What are CloudFront distributions?

A distribution is the configuration object that ties everything about a CDN deployment together: which origin(s) to use, which domain names it responds to, which TLS certificate to present, which cache behaviors apply to which paths, and settings like price class, logging, and WAF association.

Each distribution gets a default domain name like d111111abcdef8.cloudfront.net, and you can attach one or more custom alternate domain names (CNAMEs) backed by an ACM certificate.

Older CloudFront generations also supported a separate "RTMP" streaming distribution type; that has been retired, and today everything is a single distribution type built around HTTP/HTTPS delivery.

Take quiz
A CloudFront distribution's default domain looks like:
www.example.com automatically
something.cloudfront.net
an IP address only
RTMP streaming distributions are:
Retired - CloudFront now uses one distribution type
Still the recommended distribution type
Only available in Price Class 100

6. What are CloudFront cache behaviors?

A cache behavior is a rule inside a distribution that maps a URL path pattern (like /images/* or /api/*) to a specific origin and a specific set of settings - allowed HTTP methods, cache policy, origin request policy, whether viewers must use HTTPS, and which edge functions run.

A distribution always has one default cache behavior (path pattern *) plus any number of additional behaviors you define. CloudFront evaluates behaviors top-to-bottom and uses the first one whose path pattern matches; the default behavior is always the fallback.

This lets one distribution serve, for example, static assets from S3 and API traffic from an ALB, each with its own caching rules.

Take quiz
A cache behavior maps a path pattern to:
A billing account
A DNS zone
A specific origin and settings
CloudFront evaluates cache behaviors:
In random order
Top-to-bottom, first match wins
By most specific pattern first automatically

7. What is a CloudFront invalidation?

An invalidation removes an object from CloudFront's edge caches before its TTL naturally expires, forcing the next request for that path to go back to the origin for a fresh copy.

You submit invalidations by exact path (/images/logo.png) or wildcard (/images/*). AWS gives a monthly allotment of free invalidation paths; beyond that, each path is billed.

Invalidations aren't instant everywhere at once, and because of the per-path cost, teams handling frequent updates often prefer cache-busting with versioned filenames or query strings instead of invalidating.

Take quiz
An invalidation:
Removes an object from edge caches before TTL expires
Permanently deletes the origin object
Only works on video files
A common alternative to frequent invalidation is:
Disabling caching entirely
Switching price classes
Versioned filenames or query strings

8. What are signed URLs in CloudFront?

Signed URLs restrict access to an individual file by embedding a policy and cryptographic signature directly in the URL's query string. CloudFront validates the signature and policy (expiration time, and optionally IP range) before serving the object.

They're generated using a trusted key group tied to a public/private key you manage. The private key signs URLs server-side; CloudFront verifies them with the corresponding public key.

Signed URLs suit granting time-limited access to specific files - like a paid video or a private download - handed out individually, rather than through a shared client using cookies.

Take quiz
Signed URLs restrict access by:
Blocking an entire country
Embedding a policy and signature in the query string
Requiring a paid AWS Support plan
Signed URLs suit:
Granting time-limited access to specific individual files
Caching static images longer
Load balancing across Regions

9. What are signed cookies in CloudFront?

Signed cookies achieve the same goal as signed URLs - restricting access to private content - but apply to multiple files at once without modifying every URL.

CloudFront sets three cookies - CloudFront-Policy, CloudFront-Signature, and CloudFront-Key-Pair-Id - in the viewer's browser after they authenticate. Every subsequent request carries the cookies, and CloudFront validates them the same way it validates a signed URL's query parameters.

Signed cookies suit scenarios like a subscription video site where a logged-in user should browse many private assets without regenerating a signed URL for each one.

Take quiz
Signed cookies differ from signed URLs by:
Being slower to validate
Only working over HTTP
Applying to multiple files without modifying each URL
The three CloudFront signed cookies include:
Session-Id, Auth-Token, User-Agent
CloudFront-Policy, CloudFront-Signature, CloudFront-Key-Pair-Id
Cache-Control, ETag, Expires

10. What is Origin Access Control (OAC) in CloudFront?

Origin Access Control (OAC) lets a CloudFront distribution be the only path into a private S3 bucket. CloudFront signs every request to the bucket using AWS Signature Version 4 (SigV4), and the bucket policy accepts requests only from that distribution.

OAC is the current recommended approach, replacing the older Origin Access Identity (OAI). It supports SSE-KMS encrypted buckets, works in every AWS Region, and covers all S3 operations, not just GET.

Setup means creating an OAC resource, attaching it to the S3 origin, and updating the bucket policy to allow the cloudfront.amazonaws.com service principal scoped to that distribution's ARN, while blocking other public access.

Take quiz
OAC signs requests to S3 using:
AWS Signature Version 4 (SigV4)
Basic auth
No signing at all
Compared to OAI, OAC:
Doesn't support encrypted buckets
Is only available in us-east-1
Supports SSE-KMS and works in every Region

11. What are CloudFront Functions?

CloudFront Functions are lightweight pieces of JavaScript that run directly at CloudFront edge locations, on every request, with sub-millisecond execution time.

They only run on the viewer request and viewer response events, can't access the network, the file system, or a request body, and are capped at a small code size. Typical uses include normalizing the cache key, rewriting URLs, redirecting requests, and simple header-based authorization checks.

Because they're so cheap and fast, CloudFront Functions are the default choice for edge logic unless a task genuinely needs more compute or external connectivity.

Take quiz
CloudFront Functions run on:
Origin request and origin response events
Viewer request and viewer response events
A dedicated EC2 instance
CloudFront Functions cannot:
Access the network or file system
Manipulate simple headers
Rewrite a URL

12. What is Lambda@Edge?

Lambda@Edge lets you run Node.js or Python Lambda functions at AWS's edge network, triggered by any of four CloudFront events: viewer request, origin request, origin response, and viewer response.

Compared to CloudFront Functions, Lambda@Edge functions have real compute behind them - they can call external APIs, read from a database, manipulate a request body, and use third-party packages - at the cost of higher latency and higher per-invocation price.

Functions on the viewer events can run up to 5 seconds; functions on the origin events, which only fire on a cache miss, can run up to 30 seconds. You must author and deploy Lambda@Edge functions from the us-east-1 Region.

Take quiz
Lambda@Edge functions must be authored/deployed from:
Any Region you choose
The Region closest to the viewer
us-east-1
Lambda@Edge on origin events can run up to:
1ms
30 seconds
5 seconds

13. What is the CloudFront cache key?

The cache key is the set of request attributes CloudFront uses to decide whether two requests should be treated as "the same object" for caching. At minimum it always includes the request's domain name and URL path.

Beyond that, a cache policy controls whether specific query strings, headers, or cookies are folded into the key. Including more attributes creates more distinct cache entries but lowers your cache hit ratio if those attributes vary a lot without actually changing the response.

A common mistake is including a header or query string in the cache key "just in case," which fragments the cache unnecessarily.

Take quiz
The cache key always includes at minimum:
Domain name and URL path
The full request body
The viewer's IP address
Including more attributes in the cache key generally:
Always improves hit ratio
Has no effect on caching
Can lower hit ratio if those attributes vary a lot

14. What are CloudFront price classes?

A price class controls which subset of CloudFront's global edge locations can serve your distribution's content, which affects both cost and the latency viewers in different regions experience.

Price Class Coverage
Price Class All All edge locations worldwide - best performance, highest cost.
Price Class 200 Most regions, excluding the priciest edge locations.
Price Class 100 Only the lowest-cost regions - typically US, Canada, and Europe.

Viewers outside the selected regions are still served - just from the nearest included edge location - so this is a cost/performance trade-off, not an access restriction.

Take quiz
Price Class 100 covers:
All edge locations worldwide
Only the lowest-cost regions like US/Canada/Europe
Only South America
Viewers outside a selected price class's regions:
Are still served, just from a farther edge location
Cannot access the content at all
Are redirected to a different distribution

15. Define TTL in CloudFront caching?

TTL (Time To Live) is how long CloudFront keeps an object in an edge cache before treating it as stale and re-checking with the origin.

TTL can come from the origin's own Cache-Control or Expires headers, or be set explicitly in a cache policy using three values: minimum TTL, maximum TTL, and default TTL (used when the origin sends no caching headers at all).

A short TTL keeps content fresher but sends more requests to the origin; a long TTL improves cache hit ratio but risks serving stale content, unless you plan to invalidate or version the URL when content changes.

Take quiz
Default TTL applies when:
Every single request, regardless of headers
Only during an invalidation
The origin sends no caching headers at all
A shorter TTL generally:
Improves cache hit ratio
Keeps content fresher but increases origin requests
Has no trade-offs

16. Describe how CloudFront handles HTTPS certificates?

Every distribution can serve HTTPS out of the box using its default *.cloudfront.net domain with a certificate CloudFront manages for you.

To serve HTTPS on your own domain, you attach a certificate from AWS Certificate Manager (ACM), issued in us-east-1 regardless of where your other resources live, and associate it with your alternate domain names. CloudFront presents this certificate using Server Name Indication (SNI) by default, at no extra cost; a legacy dedicated-IP custom SSL option exists for the rare client that doesn't support SNI.

The viewer protocol policy on each cache behavior decides whether HTTP is allowed, redirected, or rejected, and a separate origin protocol policy controls how CloudFront talks to the origin.

Take quiz
CloudFront presents a custom domain's certificate using:
SNI by default
A shared IP with no certificate matching
FTP-based validation
ACM certificates for CloudFront must be issued in:
Any Region
eu-west-1 only
us-east-1, regardless of other resource Regions

17. List the HTTP methods CloudFront supports?

CloudFront can forward the full standard set of HTTP methods to an origin: GET, HEAD, OPTIONS, PUT, POST, PATCH, and DELETE.

Each cache behavior has an "allowed methods" setting with two common options:

  • GET, HEAD - read-only distributions, such as static websites or media delivery.
  • GET, HEAD, OPTIONS, PUT, POST, PATCH, DELETE - needed when CloudFront sits in front of a full API or application.

Separately, "cached methods" is narrower - CloudFront only ever caches responses to GET, HEAD, and optionally OPTIONS. Responses to the other methods are always passed straight through and never cached.

Take quiz
CloudFront only ever caches responses to:
All methods equally
GET, HEAD, and optionally OPTIONS
POST and DELETE only
PUT, POST, PATCH, and DELETE responses are:
Always passed through and never cached
Always cached at the edge
Blocked entirely by CloudFront

18. How do you use custom error pages in CloudFront?

Custom error pages let CloudFront return a branded, friendly response instead of a raw origin error, and optionally cache that response briefly to shield an unhealthy origin from repeated hits.

In the distribution's error pages settings, you map specific HTTP status codes (403, 404, 500, 502, and so on) to a replacement object - often a static HTML page in S3 - along with the status code CloudFront should return to the viewer and how long to cache that error response.

This is also useful for single-page applications: mapping a 403/404 from the origin to /index.html with a 200 response code lets client-side routing take over.

Take quiz
Custom error pages map:
IP addresses to countries
Cache keys to TTLs
HTTP status codes to a replacement object
For single-page apps, a common pattern is:
Disabling all error handling
Mapping 403/404 to /index.html with a 200 response
Blocking all 4xx responses

19. What is a CloudFront distribution's domain name?

Every distribution is automatically assigned a unique default domain name like d123456abcdef.cloudfront.net, which works immediately with no extra DNS setup.

Most production setups instead front the distribution with one or more alternate domain names (CNAMEs) pointed at it via a Route 53 alias record or a standard CNAME. Using an alternate domain name requires an ACM certificate covering that domain to be attached.

A given alternate domain name can only be associated with one distribution at a time across an account, since CloudFront uses it to route incoming requests to the right distribution.

Take quiz
An alternate domain name (CNAME) can be associated with:
Only one distribution at a time across an account
Multiple distributions simultaneously
No distribution, only S3 buckets
Using a custom domain name on a distribution requires:
No certificate at all
A dedicated EC2 instance
An ACM certificate covering that domain

20. How do you use Amazon S3 as a CloudFront origin?

The standard setup points CloudFront at the bucket's REST API endpoint, protected with Origin Access Control so the bucket stays fully private and is only reachable through CloudFront.

A less common alternative uses the bucket's static website hosting endpoint, which supports features like index documents and redirect rules but only serves over HTTP and can't be locked down with OAC - the bucket has to allow public reads.

For most workloads the REST API endpoint plus OAC is the better default: it keeps the bucket private, supports HTTPS end-to-end, and works with features like SSE-KMS encryption.

Take quiz
The recommended way to use S3 as an origin is:
The static website hosting endpoint with public access
The REST API endpoint secured with OAC
FTP access to the bucket
The S3 static website endpoint, unlike the REST API endpoint:
Only serves over HTTP and requires public reads
Supports OAC and SSE-KMS
Is the AWS-recommended default

21. What is the difference between CloudFront and an Application Load Balancer?

These two services solve different problems and are often used together rather than as substitutes.

CloudFront Application Load Balancer
Global CDN - caches content at edge locations worldwide. Regional service - distributes traffic across targets within a Region/AZs.
Reduces latency and origin load through caching. Does not cache; every request reaches a backend target.
Terminates TLS at the edge, close to the viewer. Terminates TLS at the load balancer in a Region.
Can run edge logic (CloudFront Functions, Lambda@Edge). Routes based on path/host rules to target groups.

A very common architecture puts CloudFront in front of an ALB: CloudFront caches what it can and forwards everything else to the ALB, which load-balances across EC2 instances, ECS tasks, or Lambda functions.

Take quiz
Unlike an ALB, CloudFront:
Never terminates TLS
Only works within one Availability Zone
Caches content at global edge locations
A common architecture combines them by:
Never using them together
Putting CloudFront in front of an ALB
Using ALB to cache CloudFront's responses

22. How does CloudFront cache invalidation compare to versioned URLs, and when should you use each?

Invalidation tells CloudFront to drop a specific cached path across edge locations so the next request re-fetches it from the origin. It requires no change to how clients reference the file, but each invalidation path beyond the monthly free allotment is billed, and propagation isn't instantaneous.

Versioned URLs instead give every new version of a file a unique name or query string - app.v2.js or app.js?v=2 - so old and new versions simply live as different cache entries with no invalidation needed.

Versioning scales better for frequent deploys and is effectively free, so it's preferred for build artifacts like JS/CSS bundles. Invalidation still earns its place for content you can't easily rename, or for emergency takedowns.

Take quiz
Versioned URLs avoid invalidation by:
Giving each new version a unique name/query string
Disabling caching site-wide
Increasing the TTL to infinity
Invalidation still makes sense for:
Every single deploy of JS/CSS bundles
Objects that never change
A fixed, hardcoded path needing an emergency takedown

23. Why should you use Origin Access Control instead of Origin Access Identity?

Origin Access Identity (OAI) was CloudFront's original mechanism for locking an S3 bucket to a distribution, but it has real limitations: it can't sign every S3 API operation with SigV4, doesn't support SSE-KMS-encrypted buckets, and isn't available in every Region.

Origin Access Control (OAC) replaces it and closes those gaps - full SigV4 signing, SSE-KMS support, every AWS Region, and additional origin types beyond plain S3, such as AWS Elemental MediaStore.

AWS now recommends OAC for all new distributions, since it gives finer-grained IAM control over exactly which distribution, and which actions, a bucket policy trusts.

Take quiz
A limitation of OAI compared to OAC is:
OAI supports every Region and SSE-KMS
OAI doesn't support SSE-KMS-encrypted buckets in the same way
OAI is faster to configure
AWS currently recommends:
OAC for all new distributions
OAI for all new distributions
Neither OAC nor OAI

24. How does CloudFront decide which cache behavior applies to a request?

CloudFront evaluates a distribution's cache behaviors in the exact order they're listed and applies the first path pattern that matches - there's no automatic "most specific wins" logic, so ordering is part of your configuration.

Path patterns can use wildcards (* and ?) - for example, /images/*.jpg or /api/*. The default cache behavior, with path pattern *, always exists and is always evaluated last, acting as the catch-all.

A practical implication: if a broad pattern like /api/* is placed above a narrower one like /api/v2/*, the narrower rule never gets reached.

Take quiz
CloudFront applies the cache behavior that is:
Most specific, regardless of list order
Randomly selected each time
The first one in list order that matches
The default cache behavior (path pattern *) is always:
Evaluated first
Evaluated last, as the catch-all
Ignored if other behaviors exist

25. What is the difference between CloudFront Functions and Lambda@Edge?

CloudFront Functions Lambda@Edge
Purpose-built JavaScript runtime (ES5.1 subset). Full Node.js or Python runtime.
Viewer request and viewer response events only. Viewer request/response and origin request/response events.
Sub-millisecond execution; no network or file access. Up to 5s (viewer events) or 30s (origin events); network/package access allowed.
10 KB code size limit. Standard Lambda deployment package limits.
Lower cost per invocation. Higher cost per invocation.

Both let you run code at the edge, but they trade off differently: CloudFront Functions optimize for the cheapest, fastest execution on every request; Lambda@Edge trades latency and cost for real compute and access to the origin-facing events Functions can't reach.

Take quiz
CloudFront Functions run a:
Purpose-built JavaScript runtime (ES5.1 subset)
Full Node.js runtime
Python 3 runtime
Lambda@Edge, unlike CloudFront Functions, can run on:
Only viewer request events
No events at all
Origin request and origin response events too

26. When should you choose Lambda@Edge over CloudFront Functions?

Reach for Lambda@Edge whenever a task needs something CloudFront Functions structurally can't do:

  • Running on an origin request or origin response event - choosing an origin dynamically, or rewriting a response body based on origin headers.
  • Calling an external API or database, such as validating a session token against DynamoDB.
  • Reading or transforming a request body - CloudFront Functions can't access it at all.
  • Using third-party packages for tasks like image resizing or complex JWT validation.
  • Needing more compute or memory than the Functions runtime allows.

If none of those apply and the logic is simple string/header manipulation on every request, CloudFront Functions is almost always the cheaper, lower-latency choice.

Take quiz
Lambda@Edge is the right choice when you need to:
Do simple string manipulation on every request cheaply
Call an external API or database
Avoid all network calls entirely
If logic is simple and needs to run on every request at minimum cost, prefer:
CloudFront Functions
Lambda@Edge
Neither - use only the origin

27. How can you optimize CloudFront's cache hit ratio?

Improving cache hit ratio mostly comes down to making the cache key as narrow as it can be while still being correct, and giving objects room to actually stay cached.

  1. Forward only the query strings, headers, and cookies the origin actually varies its response on - not "all" by default.
  2. Set sensible Cache-Control headers or TTLs so objects live long enough to be reused.
  3. Enable Origin Shield so cache misses across edge locations converge on one place before hitting the origin.
  4. Normalize URLs and query string ordering with a CloudFront Function.
  5. Enable compression so cached objects are stored and served efficiently.
  6. Avoid cache-busting query strings on content that hasn't actually changed.

Monitor progress with the CloudFront cache statistics report, which breaks hit ratio down by status code and path.

Take quiz
A key way to improve hit ratio is:
Forwarding all query strings and headers by default
Disabling TTLs entirely
Narrowing the cache key to only what the origin actually varies on
Origin Shield helps hit ratio by:
Increasing the number of edge locations
Consolidating cache misses across edge locations into one origin request
Encrypting cached objects

28. Explain the request lifecycle when a viewer requests an object through CloudFront?

A viewer request moves through a predictable sequence of hops, with up to four possible points where edge functions can intervene.

sequenceDiagram
    participant V as Viewer
    participant E as Edge Location
    participant R as Regional Edge Cache
    participant O as Origin
    V->>E: HTTP request
    Note over E: CloudFront Function / Lambda@Edge (viewer request)
    alt Cache hit at edge
        E-->>V: Cached response
    else Cache miss
        E->>R: Forward request
        alt Cache hit at regional cache
            R-->>E: Cached response
        else Cache miss
            Note over E,O: Lambda@Edge (origin request)
            R->>O: Forward to origin
            O-->>R: Origin response
            Note over E,O: Lambda@Edge (origin response)
            R-->>E: Response, cached
        end
        Note over E: CloudFront Function / Lambda@Edge (viewer response)
        E-->>V: Response
    end

On a cache hit, the edge location returns the cached object directly with no origin round trip. On a cache miss, the request climbs to the regional edge cache and, if still not found, to the origin, with the response cached on the way back down.

Take quiz
On a cache hit, the response is served:
Directly from the edge location, no origin round trip
Always from the origin regardless of cache state
Only after a Lambda@Edge call to the origin
Lambda@Edge origin-request functions run:
On every single request, cached or not
Only on the viewer response
Only on a cache miss, before contacting the origin

29. How does CloudFront handle query string and header-based caching?

By default, a distribution using the default cache policy ignores query strings and most headers when forming the cache key - two URLs differing only by ?ref=email would be treated as the same cached object.

A cache policy lets you change that per cache behavior across three dimensions: query strings (none, an allow-list, all-except, or all), headers (none or an allow-list), and cookies (the same options). Whichever you include gets folded into the cache key.

This is essential for pages that vary by a query string, like currency, but including a noisy value - a timestamp or session ID - fragments the cache and tanks hit ratio.

Take quiz
By default (no custom cache policy), CloudFront:
Includes all query strings in the cache key
Ignores most query strings and headers in the cache key
Caches nothing at all
Including a unique-per-request value like a session ID in the cache key:
Fragments the cache and lowers hit ratio
Improves hit ratio
Has no effect

30. Why doesn't CloudFront cache POST requests by default?

HTTP's own semantics are the root reason: POST is defined for submitting data that changes state on the server, and its response is generally specific to that one submission, not something an unrelated request should reuse.

CloudFront's "cached methods" setting reflects this - it only ever caches responses to GET, HEAD, and optionally OPTIONS, even if POST is included in "allowed methods" so it can reach the origin at all. A POST always passes through and its response is delivered but never stored at the edge.

The same logic applies to PUT, PATCH, and DELETE - allowed through when needed, but non-cacheable by design.

Take quiz
CloudFront's cached methods only ever include:
POST and PUT
All seven HTTP methods
GET, HEAD, and optionally OPTIONS
A POST request through CloudFront is:
Never forwarded to the origin
Forwarded to the origin but its response is never cached
Always cached for 24 hours

31. What happens when an origin returns an error to CloudFront?

When the origin responds with an error status, CloudFront's behavior depends on how the distribution's custom error responses are configured for that status code.

If a custom error response is defined, CloudFront can serve a replacement object instead of passing the raw error through, and cache that replacement for a configurable error caching minimum TTL, protecting a struggling origin from repeated retries.

If an origin group is configured for failover, specific status codes (commonly 500, 502, 503, 504, and optionally 403/404) trigger CloudFront to retry against the secondary origin instead of returning the error immediately.

Take quiz
Custom error responses let CloudFront:
Serve a replacement object and cache it for a configurable TTL
Ignore all origin errors silently
Delete the origin automatically
Origin failover with an origin group retries against the secondary when:
Every single request is made
The viewer requests it explicitly
A qualifying error status code is returned by the primary

32. How do you troubleshoot a low cache hit ratio in CloudFront?

Start with the CloudFront cache statistics report, which shows hit ratio trends and lets you drill into which paths or status codes drive misses.

  1. Check the cache policy - an overly broad set of forwarded query strings, headers, or cookies fragments the cache key.
  2. Inspect the origin's Cache-Control/Expires headers for no-store, no-cache, or a very short max-age.
  3. Look for cache-busting patterns, like a timestamp embedded in the URL by the client.
  4. Confirm TTLs on the cache policy aren't set too low.
  5. Enable Origin Shield if many edge locations independently miss on the same popular object.
  6. Use real-time or standard access logs to see the actual x-edge-result-type per request.

Change one variable at a time and re-check the statistics report, since cache key and TTL changes interact.

Take quiz
A good first troubleshooting step is:
Deleting the distribution
Reviewing the CloudFront cache statistics report
Switching to a different AWS Region
A likely cause of a fragmented cache key is:
An overly broad set of forwarded query strings/headers/cookies
A very long default TTL
Using Origin Shield

33. Explain the internal working of CloudFront's regional edge caches?

Regional edge caches sit in the request path between the global edge locations that serve viewers directly and your origin. They're deployed in a smaller number of AWS Regions and each has a much larger cache than any individual edge location.

On a cache miss at an edge location, CloudFront checks the nearest regional edge cache before going to the origin. Because regional edge caches hold more objects for longer, they absorb "long-tail" content that has fallen out of a smaller edge location's cache but is still occasionally requested.

Not everything flows through them: dynamic content and non-cacheable methods like PUT, POST, PATCH, and DELETE go straight from the edge location to the origin, bypassing the regional edge cache layer entirely, since there's nothing useful to cache there.

Take quiz
Regional edge caches, compared to edge locations, are:
Smaller and more numerous
Only used for video streaming
Fewer in number with larger cache capacity
Content that bypasses regional edge caches entirely includes:
Popular static images
Dynamic content and non-cacheable methods like POST
All GET requests

34. How does CloudFront integrate with AWS WAF?

You attach an AWS WAF web ACL directly to a CloudFront distribution, and every request is evaluated against that web ACL's rules at the edge, before it reaches your origin or consumes cache capacity for a blocked request.

A web ACL combines your own custom rules (rate-based rules, string/regex matches against headers or the URI, IP set matches) with AWS Managed Rule Groups covering things like the OWASP Top 10 and known bad bots.

WAF and CloudFront's own geo-restriction feature overlap in purpose but work differently: geo-restriction is a simple allow/deny list by country baked into the distribution, while WAF's geo-match rules combine with other conditions for more nuanced blocking.

Take quiz
An AWS WAF web ACL attached to CloudFront evaluates requests:
At the edge, before reaching the origin
After they reach the origin
Only once per day
AWS Managed Rule Groups can help protect against:
Only DDoS at the network layer
Billing overages
Patterns like the OWASP Top 10 and known bad bots

35. What is the difference between CloudFront and Amazon S3 Transfer Acceleration?

CloudFront S3 Transfer Acceleration
General-purpose CDN - caches and repeatedly serves content to many viewers. Speeds up a single upload or download to/from an S3 bucket.
Best for content requested many times by many users. Best for large, one-off file transfers over long distances.
Adds caching, TLS termination, WAF, and edge compute. Just routes traffic onto AWS's backbone sooner.

Both use CloudFront's edge network to get traffic onto AWS's backbone quickly, but they solve different problems: CloudFront repeatedly serves cached content to end users, while Transfer Acceleration speeds up individual PUT/GET operations that wouldn't benefit from caching at all.

Take quiz
S3 Transfer Acceleration is best suited for:
Serving cached content to many repeat viewers
Speeding up a single large upload/download to/from S3
Running edge compute logic
Both CloudFront and S3 Transfer Acceleration:
Use AWS's edge network to get traffic onto the backbone quickly
Are the exact same service under a different name
Require Lambda@Edge to function

36. Why should you use field-level encryption in CloudFront?

Field-level encryption adds an extra layer of protection for specific sensitive fields in an HTTPS POST body - like a credit card number - so the value stays encrypted even after it leaves CloudFront and travels through your own application stack.

You configure which fields to encrypt and upload a public key; CloudFront encrypts those fields as the request passes through, while everything else stays in plaintext. Only a system holding the matching private key can decrypt the protected fields.

This limits exposure: even components inside your own infrastructure that don't need to see the raw value - load balancers, application servers, logs - never get a plaintext copy of it.

Take quiz
Field-level encryption protects:
The entire HTTP request equally
Only the response headers
Specific sensitive fields in a POST body
Only systems holding the matching ___ can decrypt protected fields:
Public key
Private key
CloudFront distribution ID

37. How does CloudFront support real-time logs?

Real-time logs stream log records for a distribution to an Amazon Kinesis Data Stream within seconds of each request, compared to CloudFront's standard access logs, which are batched and delivered to S3 with a noticeably longer delay.

You configure a real-time log config per cache behavior, choosing a sampling rate and exactly which fields to include - edge location, cache result, response time, status code, and more.

Because the data lands in Kinesis, you can attach it to a Lambda consumer or Kinesis Data Firehose to build near-live dashboards or alerting - useful for catching a traffic spike or an error surge minutes sooner than batched logs allow.

Take quiz
Real-time logs stream data to:
Amazon Kinesis Data Streams within seconds
An S3 bucket with a long delay
Amazon RDS
You can configure real-time logs with:
A fixed 100% sampling rate only, no options
No configuration at all
A chosen sampling rate and specific fields to include

38. When would you choose a custom origin over an S3 origin?

Choose a custom origin whenever content genuinely needs to be generated or processed rather than just stored and served, or when it doesn't live in S3 at all.

  • The origin is an application server - EC2, an ALB, ECS, or a container platform - producing dynamic, per-request responses.
  • You need CloudFront to forward custom headers or a request body to logic running on that server.
  • The content lives outside AWS entirely - on-premises or another cloud provider.
  • You need full control over response headers, status codes, or business logic a static file store can't provide.

An S3 origin remains the better fit for static assets - images, video, downloadable files, a prebuilt app bundle - that just need to be stored durably and handed back unchanged.

Take quiz
A custom origin fits best when content is:
Static and unchanging
Dynamically generated per request by an application server
Only ever images
S3 origins remain the better fit for:
Static assets like images and prebuilt app bundles
Dynamic API responses
Real-time chat messages

39. Explain the execution flow of Lambda@Edge across its four trigger points?

Lambda@Edge can attach a function to any of four points in the request/response cycle, and each point suits a different job.

flowchart LR
    A["Viewer Request"] -->|auth, redirects, A/B routing| B["Cache Check"]
    B -->|miss| C["Origin Request"]
    C -->|choose origin, add headers| D[Origin]
    D --> E["Origin Response"]
    E -->|inject headers, transform body| F["Cache Store"]
    F --> G["Viewer Response"]
    B -->|hit| G
    G -->|final header tweaks, cookies| H[Viewer]

Viewer request functions run on every request before the cache is checked, commonly for authentication or routing. Origin request functions run only on a cache miss, right before CloudFront contacts the origin, and are used to choose between origins or add origin-specific headers.

Origin response functions run right after the origin replies, before the object is cached, for modifying a body or injecting cache-control headers. Viewer response functions run on every request, cached or not, for final cookie or header adjustments.

Take quiz
Origin-request Lambda@Edge functions typically handle:
Final viewer-facing cookie tweaks
Nothing - they can't modify anything
Choosing between origins or adding origin-specific headers
Viewer-response functions run:
Only on a cache miss
On every request, cached or not, right before returning to the viewer
Only when Lambda@Edge fails

40. How can you optimize CloudFront costs?

CloudFront cost comes primarily from data transfer out, requests, and any invalidations/edge functions used, so optimization touches several levers.

  1. Pick the narrowest price class that still covers your actual audience instead of defaulting to Price Class All.
  2. Push TTLs as high as freshness requirements allow to reduce origin fetches.
  3. Enable compression to transfer fewer bytes per response.
  4. Replace frequent invalidations with versioned file names.
  5. Use Origin Shield where the origin is expensive to run - it costs a little more per request but can cut origin compute and egress costs.
  6. Prefer CloudFront Functions over Lambda@Edge for simple edge logic.
  7. For large, predictable usage, evaluate a committed-use discount option rather than pure on-demand pricing.

Reviewing the AWS Cost Explorer breakdown by usage type regularly is the fastest way to see which lever actually moves the needle for a given workload.

Take quiz
A cost-saving lever for CloudFront is:
Choosing the narrowest price class that covers your audience
Always using Price Class All regardless of audience
Disabling compression
For simple edge logic, choosing ___ over Lambda@Edge typically reduces cost:
A second CloudFront distribution
AWS Shield Advanced
CloudFront Functions

41. Why is Origin Shield useful in a CloudFront architecture?

Origin Shield adds one more caching layer, placed in a single AWS Region you choose, that sits between all of your regional edge caches and the origin itself.

Without it, a popular object simultaneously missing from caches on multiple continents can trigger several near-identical requests to the origin at once. Origin Shield consolidates those into a single request, since every regional edge cache checks Origin Shield first on a miss, rather than going straight to the origin.

This is most valuable when the origin is slow or expensive to serve from - dynamic rendering, on-the-fly transcoding, or a backend that's easy to overload - since it directly reduces duplicate load reaching that origin, at the cost of a small additional per-request charge and a bit of extra latency on a true cache miss.

Take quiz
Origin Shield sits:
Between the viewer and the edge location
Between regional edge caches and the origin
Inside the origin server itself
Origin Shield is most valuable when:
The origin is slow or expensive to serve from
The origin is cheap and infinitely scalable
There is only one edge location globally

42. What is the difference between CloudFront's price classes, and how do you choose one?

All three price classes deliver content globally - the difference is which edge locations are eligible to serve your distribution, which shapes both your bill and how close the "nearest" edge location actually is for viewers outside the cheaper tiers.

Price Class 100 fits an audience concentrated in North America and Europe, where paying for worldwide coverage would pay for capacity nobody uses. Price Class 200 adds most of the rest of the world except the costliest regions - a reasonable middle ground for an internationally used product. Price Class All is worth it when you have meaningful traffic from every region, including South America, or when consistent low latency everywhere is a hard requirement, such as a global live-streaming platform.

Because price class is a per-distribution setting, a multi-tenant platform can mix classes - Price Class All for a public marketing site, Price Class 100 for an internal admin tool - to match spend to where it actually matters.

Take quiz
Price Class 100 fits an audience concentrated in:
South America only
Every country equally
North America and Europe
Price class can be set:
Only once for an entire AWS account
Per distribution, allowing different classes for different sites
Only by AWS Support

43. How does CloudFront handle HTTP/2 and HTTP/3?

CloudFront supports HTTP/1.1, HTTP/2, and HTTP/3 between the viewer and the edge location; you enable which versions a distribution accepts, and CloudFront negotiates the best one the client supports.

HTTP/2 multiplexes multiple requests over a single TCP connection, cutting the connection-setup overhead that hurt HTTP/1.1 when a page needed many small assets. HTTP/3 goes further by running over QUIC (built on UDP instead of TCP), avoiding TCP head-of-line blocking and recovering faster from packet loss - a meaningful improvement on mobile and other lossy networks.

Enabling HTTP/3 doesn't change how CloudFront talks to your origin - that connection uses whatever protocol the origin supports - it only affects the viewer-facing hop, and older clients simply fall back to HTTP/1.1 automatically.

Take quiz
HTTP/3 runs over:
QUIC, built on UDP
TCP, just like HTTP/2
A dedicated fiber protocol
Enabling HTTP/3 affects:
Only the CloudFront-to-origin connection
Neither hop
Only the viewer-facing hop to the edge location

44. Explain the lifecycle of a TLS handshake in CloudFront with a custom domain?

When a viewer connects to CloudFront over a custom domain, the TLS handshake happens at the edge location, and a second, independent handshake can happen between CloudFront and the origin.

sequenceDiagram
    participant V as Viewer
    participant E as Edge Location
    participant O as Origin
    V->>E: ClientHello (SNI: www.example.com)
    Note over E: Match SNI to ACM cert for that domain
    E-->>V: ServerHello + certificate
    V->>E: Key exchange, Finished
    Note over V,E: TLS session established
    E->>O: New TLS handshake (if origin protocol policy = HTTPS)
    O-->>E: Certificate, key exchange
    Note over E,O: Separate TLS session to origin

The viewer-facing handshake uses SNI to pick the right certificate when a single edge location serves many distributions with different domains - CloudFront reads the hostname in ClientHello and presents the matching ACM certificate.

The edge-to-origin leg is a separate TLS session governed by the distribution's origin protocol policy, and it needs its own valid certificate on the origin side if that policy requires HTTPS.

Take quiz
CloudFront uses SNI to:
Encrypt the request body
Match the requested hostname to the right ACM certificate
Choose a price class
The edge-to-origin TLS handshake is:
A separate TLS session governed by the origin protocol policy
The exact same session as the viewer-to-edge handshake
Never required

45. How do you troubleshoot a 403 error from CloudFront on an S3 origin?

A 403 from an S3-backed distribution almost always traces back to a permissions mismatch between CloudFront and the bucket, rather than a CloudFront bug.

  1. Confirm the bucket policy allows the cloudfront.amazonaws.com service principal, scoped to your distribution's ARN - a common mistake is leaving an old OAI-style policy after switching to OAC.
  2. Check that S3 Block Public Access settings aren't conflicting with the intended access path.
  3. Verify the origin path on the distribution actually points at where the objects live in the bucket.
  4. Rule out AWS WAF blocking the request if a web ACL is attached - WAF-blocked requests also surface as 403s.
  5. Confirm the requested object exists; S3 can return 403 instead of 404 for missing objects when the caller lacks s3:ListBucket permission.

S3 server access logs and CloudFront's own logs, cross-referenced by timestamp, usually pinpoint which of these it is quickly.

Take quiz
A common cause of a 403 from an S3 origin is:
Too high a TTL
Using HTTP/3
The bucket policy not trusting the CloudFront distribution's ARN
S3 can return 403 instead of 404 for a missing object when:
The object is cached at the edge
The caller lacks s3:ListBucket permission
Origin Shield is disabled

46. Why should you enable origin failover in CloudFront?

Origin failover uses an origin group - a primary origin plus a secondary - so CloudFront can automatically retry a failed request against the secondary instead of surfacing the error to the viewer.

You configure which HTTP status codes count as a failure worth failing over on, typically 500, 502, 503, and 504, and optionally 403/404. CloudFront tries the primary first for every request; only on a qualifying failure does it retry the secondary.

This matters for availability because CloudFront itself has no built-in health checking that proactively takes a bad origin out of rotation the way a load balancer does - failover here is reactive, triggered per request by an actual error. It's a cheap way to add resilience against a full origin outage or a bad deployment, without a separate DNS failover mechanism.

Take quiz
Origin failover requires configuring:
An origin group with a primary and secondary origin
A price class change
A new ACM certificate
CloudFront's failover behavior is:
Proactive, with continuous health checks like a load balancer
Based on a fixed daily schedule
Reactive, triggered per request by a qualifying error

47. How does path pattern precedence work in CloudFront cache behaviors?

CloudFront always checks a request's URL path against cache behaviors in list order and stops at the first pattern that matches - there's no automatic "most specific wins" logic.

Order Path Pattern Effect
1 /api/v2/* Matches first, routes newer API traffic to its own origin/policy.
2 /api/* Catches remaining API traffic not matched above.
3 /images/* Routes static images to an S3 origin.
4 (default) * Fallback for everything else.

If /api/* had been listed above /api/v2/*, every request under /api/v2/ would match the broader rule first and the more specific one would never fire - a subtle bug that shows up as "wrong cache policy applied to some API version."

Take quiz
If a broad pattern is listed above a narrower one, the narrower rule:
Always still applies first
May never be reached
Overrides the broad rule automatically
The default cache behavior's path pattern is:
*
/api/*
/default/*

48. What is the difference between edge locations and regional edge caches?

Edge Locations Regional Edge Caches
Hundreds worldwide, closest to viewers. A smaller number, deployed in select AWS Regions.
Smaller cache per location; evicts less-popular objects sooner. Larger cache; holds "long-tail" objects longer.
First point of contact for every viewer request. Consulted only on a cache miss at the edge location.
Serves cached responses directly to viewers. Never talks to viewers directly - sits between edge and origin.

The practical difference shows up in request flow: dynamic content and non-cacheable methods skip the regional edge cache entirely and go straight from the edge location to the origin, since there's no benefit caching them at an intermediate layer they'll never reuse.

Both layers exist for the same underlying goal - reducing round trips to the origin - just at different distances from the viewer and with different cache sizes.

Take quiz
Regional edge caches are consulted:
On every single viewer request
Never, they are purely informational
Only on a cache miss at the edge location
Which layer talks directly to viewers?
Only regional edge caches
Only edge locations
Both equally

49. How can you secure a CloudFront distribution end-to-end?

Securing a CloudFront distribution end-to-end means treating it as a stack of independent controls, not a single setting to flip.

  1. Lock down the origin - Origin Access Control for an S3 origin, or a security group/firewall restricted to CloudFront's traffic for a custom origin.
  2. Enforce HTTPS on both legs - a viewer protocol policy that redirects or requires HTTPS, and an HTTPS-only origin protocol policy.
  3. Attach AWS WAF with managed rule groups and rate-based rules to filter malicious requests before they reach your origin.
  4. Use signed URLs or signed cookies for content that shouldn't be publicly downloadable.
  5. Add field-level encryption for sensitive form fields that need to stay encrypted past the edge.
  6. Rely on AWS Shield Standard (automatic) for baseline DDoS protection, and consider Shield Advanced for critical distributions.
  7. Restrict by geography with CloudFront geo-restriction if content is only licensed for certain countries.

None of these substitutes for the others - a distribution with WAF but a public S3 bucket is still fully exposed through direct bucket access.

Take quiz
Even with WAF attached, a distribution remains exposed if:
The origin S3 bucket is still publicly accessible directly
HTTPS is enforced
Signed URLs are used
Shield Standard for baseline DDoS protection is:
An opt-in paid add-on
Only available with Shield Advanced
Automatic and included

50. Explain how CloudFront supports multi-region origin failover and disaster recovery?

CloudFront supports disaster recovery patterns by combining origin groups for automatic failover with multi-Region origins underneath them, so a Regional outage doesn't have to mean a full outage for viewers.

flowchart TD
    V["Viewer Request"] --> CF["CloudFront Edge"]
    CF --> OG["Origin Group"]
    OG -->|primary| P["Primary Origin - Region A"]
    P -->|healthy| CF
    P -->|error status matches failover criteria| S["Secondary Origin - Region B"]
    S --> CF

The typical setup replicates data to both Regions - S3 Cross-Region Replication for object storage, or an active-passive/active-active application deployment behind an ALB in each Region - and configures the origin group so a qualifying failure (a 5xx, or a timeout) at the primary automatically routes that request to the secondary.

Because failover happens per request at the CloudFront layer rather than through DNS, there's no DNS propagation delay to wait out - typically the slowest part of a traditional multi-region failover design. The trade-off is that failover is reactive - it only engages once CloudFront sees a qualifying error - so it doesn't substitute for active health monitoring on the origins themselves.

Take quiz
CloudFront-layer failover, compared to DNS-based failover:
Requires waiting for DNS propagation
Has no DNS propagation delay since failover happens per request
Is slower in every case
Origin group failover is:
Reactive, engaging only after a qualifying error from the primary
Proactive, monitoring origin health continuously
Unrelated to error status codes
«
»

Comments & Discussions