Amazon CloudFront
Distributions, origins and behaviors, cache keys and hit ratio, signed access, origin failover, edge functions and the limits the exam asks about.
Exam tasks: 2.3 (secure content delivery), 2.5 and 3.3 (performance), 1.4, 2.6 (cost)
The decision: can the response be cached, and if not, can the connection still be accelerated? Then how do you keep the origin reachable only through CloudFront, and who may fetch the content?
CloudFront is a global CDN. It serves cached copies from edge locations, and for uncached or dynamic requests it carries the connection over the AWS backbone to the origin, with persistent connections.
Distribution anatomy
| Part | What it does |
|---|---|
| Origin | Where content lives: S3, an ALB or NLB, an EC2 or custom HTTP server, a Lambda function URL, and VPC origins for private load balancers and instances |
| Behavior | A path pattern (/api/*, default *) with its own origin, cache policy, allowed methods, viewer protocol policy and function associations |
| Origin group | A primary and a secondary origin. CloudFront fails over on chosen status codes such as 500, 502, 503 and 504 or on connection failure, for GET, HEAD and OPTIONS |
| Cache policy | What forms the cache key and the TTL range |
| Origin request policy | What CloudFront forwards to the origin without adding it to the key |
| Response headers policy | Adds CORS and security headers on the way out |
- Viewer protocol policy can redirect HTTP to HTTPS. Origin protocol policy controls the second hop.
- A custom domain needs an ACM certificate in us-east-1 and a CNAME or an alias record in Route 53.
- Static assets and APIs often share one distribution, using separate behaviors for
/static/*and/api/*.
Securing content and origins
| Need | Use |
|---|---|
| Only CloudFront may read an S3 bucket | Origin access control (OAC) with a bucket policy for the distribution. OAI is the older mechanism |
| Only CloudFront may reach an ALB | A VPC origin with a private ALB, or a secret custom header the ALB checks, plus the CloudFront managed prefix list in the security group |
| Paid or private files | Signed URLs for one file or clients without cookie support, signed cookies for many files. Use a trusted key group |
| Protect sensitive form fields | Field-level encryption encrypts chosen POST fields at the edge with your public key, so only the holder of the private key reads them |
| Block countries | Geographic restrictions (allow or deny list). For finer rules use WAF geo match |
| Block exploits and bots | AWS WAF on the distribution. Shield Standard is included, and Shield Advanced is optional |
| Serve over TLS | A viewer security policy sets the minimum TLS version |
Signed URL versus S3 presigned URL
A CloudFront signed URL is checked at the edge with a key group. An S3 presigned URL is checked by S3 and bypasses CloudFront's cache. A question about restricting a cached download to subscribers wants the CloudFront signed URL or cookie, with OAC on the bucket.
Cache keys and the hit ratio
A cache hit happens only when a new request produces the same cache key as a cached object that hasn't expired. Every header, cookie or query string in the key multiplies the number of variants and cuts the hit ratio.
Cache policy vs origin request policy
| Cache policy | Origin request policy | |
|---|---|---|
| Controls | What's in the cache key, and the min, default and max TTL | What CloudFront forwards to the origin |
| Affects hit ratio | Yes, directly | No |
| Use it for | Values that really change the response, such as lang | Values the origin needs but that don't change the cached object, such as a tracking header |
Anything in the cache key is also sent to the origin. The origin request policy adds values without adding them to the key.
Raising the hit ratio
- Include only what varies the response. Allowlist the two query strings that matter instead of all query
strings. Don't put
User-Agent,Authorizationor session cookies in the key for shared content. - Normalize. Turn on Gzip and Brotli in the cache policy so CloudFront normalizes
Accept-Encoding, rather than caching one copy per browser's header string. Use CloudFront Functions to lowercase or sort query strings. - Device-based variants: use the
CloudFront-Is-Mobile-Viewerstyle headers (a few values) instead of the rawUser-Agent(thousands of values). - TTLs. Have the origin send
Cache-Control: max-ageors-maxage. The policy's minimum and maximum TTLs bound what the origin asks for. - Versioned file names (
app.3f9c.js) with long TTLs beat invalidations for deployments. Invalidation is for mistakes, not the release process. - Origin Shield adds one central caching layer in a Regional edge cache in front of the origin. All edge locations fetch through it, so the origin sees one request per object instead of one per Regional edge cache. Use it for global audiences, multi-CDN setups or a fragile origin.
- Monitor with the CloudFront cache statistics reports and the
CacheHitRatemetric (with additional metrics turned on).
Forwarding all headers
"Forward all headers to the origin" through the cache key means almost every request is a miss. If the origin needs headers, send them with an origin request policy and keep the cache key small.
Exam signal
"Origin is overloaded even though CloudFront is in front" points to the cache key (too many headers, cookies or query strings), short TTLs, or missing Origin Shield. Adding more origin servers is rarely the intended answer.
Edge compute: Functions and Lambda@Edge
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Runtime | JavaScript | Node.js, Python |
| Triggers | Viewer request, viewer response | Viewer and origin request and response |
| Execution time | Under a millisecond | Up to 5 s (viewer), 30 s (origin) |
| Network calls and body access | No | Yes |
| Scale and cost | Millions of requests per second, lowest cost | Lower scale, higher cost |
| Runs at | Every edge location | Regional edge caches |
| Typical uses | Header rewrites, URL redirects, cache-key normalization, JWT validation, A/B cookies | Auth that calls a service, dynamic origin selection, image resizing, body inspection |
- Lambda@Edge functions are created in us-east-1 and replicated globally. Versions only, no
$LATEST. - CloudFront Functions can read small config from CloudFront KeyValueStore without redeploying.
Exam signal
Anything that only touches headers, cookies or the URL at high volume is CloudFront Functions. Anything that needs an origin-side trigger, network access, the body, or more than a millisecond of work is Lambda@Edge.
Operations
- Invalidations remove cached objects before their TTL. Prefer versioned file names, and keep invalidation for mistakes.
- Continuous deployment lets you test a configuration change on a staging distribution that takes a slice of real traffic before you promote it.
- Logs: standard logs go to S3 with delay, and real-time logs stream to Kinesis Data Streams within seconds.
- Cost: a smaller price class lowers cost at the price of fewer edge locations. Data transfer out to the internet from CloudFront costs less than from an origin, and traffic from the origin to CloudFront is free.
Scenarios
A new name is a new cache key, so the new version is fetched immediately and old versions expire on their own, while the cache hit ratio stays high. A zero minimum TTL loses most of the cache benefit. Removing CloudFront loses the CDN. Invalidating everything works but is slow, can cost money at scale and drops the hit ratio.
Signed cookies authorize many files without changing URLs, and OAC makes CloudFront the only path to the bucket. Presigned S3 URLs would bypass the CDN and need one per file. A public bucket has no access control. Field-level encryption protects form fields, not downloads.
Related
- Caching: CloudFront as one layer among API Gateway, DAX and ElastiCache.
- Private S3 access: OAC and the other ways to serve a private bucket.
- DDoS and edge security: WAF and Shield on the distribution.
Further reading
Private access to S3 content
S3 presigned URLs, CloudFront signed URLs and signed cookies, origin access control, S3 Access Points, Multi-Region Access Points and Block Public Access.
Amazon API Gateway
REST, HTTP and WebSocket APIs compared, integrations, authorizers, throttling, stages and canaries, caching, private APIs and custom domains.