Explain it simply
The edge, in plain words
Imagine your shop has only one warehouse, in Virginia, and every customer in Yangon, Mandalay and Bangkok waits for each parcel to cross the world. CloudFront is like opening small storerooms in hundreds of cities. The first customer in a city still waits for the item to arrive from the main warehouse, but everyone after that gets a copy from the local storeroom within milliseconds.
AWS WAF is the guard standing at every storeroom door. It checks each visitor against a list of rules — known attack patterns, too many visits from one address, requests from countries you do not serve — and turns away anyone who fails.
AWS Shield is the flood wall around the whole building. It absorbs huge waves of junk traffic (DDoS attacks) so that neither the guard nor the shelves are ever overwhelmed. In this lesson you build all three layers, one at a time.
Problem → Why → Solution
The trouble with a public S3 website
In AWS Fundamentals you hosted a static site straight from an S3 website endpoint. It works, but look at what it took: you switched off Block Public Access, attached a bucket policy that lets the whole internet read every object, and accepted plain HTTP on the website endpoint. Every request, whether from Yangon or Frankfurt, travels all the way to a single region.
Now put that site behind a marketing campaign. Far-away users pay hundreds of milliseconds of latency per request, every page view is a billable S3 GET plus data transfer, and one bot hammering /index.html thousands of times per second goes straight to your bucket. There is no place to say 'block this IP' or 'allow only 2,000 requests per five minutes per client'.
# The AWS Fundamentals way: a public bucket website (not for production)
BUCKET=shop-site-111122223333
aws s3api delete-public-access-block --bucket "$BUCKET"
aws s3api put-bucket-policy --bucket "$BUCKET" --policy file://public-read.json
aws s3 website "s3://$BUCKET" --index-document index.html --error-document error.html
# Result: http://shop-site-111122223333.s3-website-us-east-1.amazonaws.com
# HTTP only, one region, every object world-readable, no rate limitingWhy this breaks at scale
The origin is exposed directly: there is no cache to absorb load, no edge to terminate HTTPS close to the user, and no inspection layer between the internet and your data. Because the bucket is public, anyone can also bypass whatever you put in front of it later. The fix is to make the bucket private again, put CloudFront in front, let only that one distribution read the bucket, and attach WAF rules at the edge.
How CloudFront, OAC, WAF and Shield fit together
CloudFront is a content delivery network made of hundreds of edge locations plus a layer of regional edge caches that sit between those edges and your origin. A viewer reaches the nearest edge through DNS. If the edge holds a copy (a cache hit) it answers immediately; on a miss it asks the regional edge cache, and only if that misses too does the request travel to the origin.
How CloudFront tells one cached object from another is called the cache key.
- Cache key
- The set of values that identifies one cached object: by default the domain and URL path, plus any headers, cookies or query strings the cache policy adds. Every value you add splits the cache into more pieces and lowers the hit ratio.
A distribution contains cache behaviors. Each behavior matches a path pattern (/api/*, /assets/*, the default *) and has its own origin, viewer protocol policy, function associations and two policies. The cache policy decides what goes into the cache key and the TTLs (minimum, default, maximum). The origin request policy decides which extra headers, cookies and query strings are forwarded to the origin without becoming part of the cache key. That split lets an API receive the headers it needs without destroying your hit ratio.
Origin Access Control (OAC) makes CloudFront sign every request to the origin with SigV4. The bucket policy then allows only the cloudfront.amazonaws.com service principal, pinned to your distribution's ARN with an AWS:SourceArn condition. The bucket stays fully private with Block Public Access switched on. OAC replaces the legacy Origin Access Identity (OAI) and also supports objects encrypted with SSE-KMS.
An AWS WAF web ACL attached to the distribution inspects every request at the edge, before the cache is consulted. Rules run in priority order and stop at the first terminating action (Allow, Block, CAPTCHA or Challenge); Count only records a match and moves on. AWS-maintained managed rule groups cover OWASP-style attacks, bad inputs and IP reputation, while a rate-based rule limits how fast any single client can send requests.
Shield Standard is always on for every customer at no extra charge and absorbs layer 3/4 attacks such as SYN floods and UDP reflection. Shield Advanced is the paid tier, covered in a later section.
REQUEST PATH THROUGH THE EDGE
-----------------------------
Viewer (Yangon) Edge location (Singapore)
| +-------------------------------------+
| HTTPS request | 1. AWS WAF web ACL (priority order) |
+---------------> | 2. CloudFront Function (viewer req) |
| 3. Cache lookup by cache key |
+------------------+------------------+
| miss
v
+-------------------------------------+
| Regional edge cache |
+------------------+------------------+
| miss, signed with SigV4 (OAC)
v
+-------------------------------------+
| Private S3 bucket (us-east-1) |
| Block Public Access = ON |
+-------------------------------------+
Shield Standard: always-on L3/L4 DDoS protection at every edge- Viewer -> nearest edge
- WAF web ACL checks rules
- Cache key lookup: hit or miss
- Miss: fetch origin, signed by OAC
- Store for TTL, return response
The smaller the cache key, the higher the hit ratio and the quieter your origin. WAF runs before the cache, so even a request that would be a cache hit can be blocked.
The OAC bucket policy pattern
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowCloudFrontServicePrincipalReadOnly",
"Effect": "Allow",
"Principal": { "Service": "cloudfront.amazonaws.com" },
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::shop-site-111122223333/*",
"Condition": {
"StringEquals": {
"AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/E2QWRUHAPOMQZL"
}
}
}
]
}The principal is the CloudFront service, and the AWS:SourceArn condition narrows it to this one distribution. Without that condition, any CloudFront distribution in any account could read your bucket. Note that the only action granted is s3:GetObject.
A complete distribution: private origin, OAC and WAF
The CloudFormation template below builds a private bucket, an OAC, a viewer-request CloudFront Function, a WAF web ACL with a managed rule group (in count mode) and a rate-based rule (in block mode), and the distribution that ties them together. CloudFormation itself is covered in depth in the next chapter, so for now focus on how the resources reference each other.
Deploy this stack in us-east-1
A web ACL used with CloudFront (Scope: CLOUDFRONT) can only be created in us-east-1 (N. Virginia), so deploy this whole stack there. The bucket itself could live in any region.
AWSTemplateFormatVersion: "2010-09-09"
Description: Private S3 origin behind CloudFront with OAC and an AWS WAF web ACL
Parameters:
RateLimit:
Type: Number
Default: 1000
Description: Max requests per client IP in each 5-minute window
Resources:
SiteBucket:
Type: AWS::S3::Bucket
Properties:
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
SiteOAC:
Type: AWS::CloudFront::OriginAccessControl
Properties:
OriginAccessControlConfig:
Name: !Sub "${AWS::StackName}-oac"
OriginAccessControlOriginType: s3
SigningBehavior: always
SigningProtocol: sigv4
IndexRewriteFunction:
Type: AWS::CloudFront::Function
Properties:
Name: !Sub "${AWS::StackName}-index-rewrite"
AutoPublish: true
FunctionConfig:
Comment: Append index.html to directory-style URLs
Runtime: cloudfront-js-2.0
FunctionCode: |
function handler(event) {
var request = event.request;
if (request.uri.endsWith('/')) {
request.uri += 'index.html';
}
return request;
}
EdgeWebAcl:
Type: AWS::WAFv2::WebACL
Properties:
Name: !Sub "${AWS::StackName}-edge-acl"
Scope: CLOUDFRONT
DefaultAction:
Allow: {}
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: edge-acl
Rules:
- Name: aws-common-rules
Priority: 0
OverrideAction:
Count: {}
Statement:
ManagedRuleGroupStatement:
VendorName: AWS
Name: AWSManagedRulesCommonRuleSet
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: aws-common-rules
- Name: rate-limit-per-ip
Priority: 1
Action:
Block: {}
Statement:
RateBasedStatement:
Limit: !Ref RateLimit
AggregateKeyType: IP
VisibilityConfig:
SampledRequestsEnabled: true
CloudWatchMetricsEnabled: true
MetricName: rate-limit-per-ip
Distribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Enabled: true
Comment: shop static site
DefaultRootObject: index.html
HttpVersion: http2and3
PriceClass: PriceClass_100
WebACLId: !GetAtt EdgeWebAcl.Arn
Origins:
- Id: s3-site
DomainName: !GetAtt SiteBucket.RegionalDomainName
OriginAccessControlId: !GetAtt SiteOAC.Id
S3OriginConfig:
OriginAccessIdentity: ""
DefaultCacheBehavior:
TargetOriginId: s3-site
ViewerProtocolPolicy: redirect-to-https
Compress: true
# AWS managed policy "CachingOptimized"
CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6
FunctionAssociations:
- EventType: viewer-request
FunctionARN: !GetAtt IndexRewriteFunction.FunctionARN
SiteBucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref SiteBucket
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: AllowCloudFrontOACReadOnly
Effect: Allow
Principal:
Service: cloudfront.amazonaws.com
Action: s3:GetObject
Resource: !Sub "${SiteBucket.Arn}/*"
Condition:
StringEquals:
AWS:SourceArn: !Sub >-
arn:aws:cloudfront::${AWS::AccountId}:distribution/${Distribution}
Outputs:
BucketName:
Value: !Ref SiteBucket
DistributionId:
Value: !Ref Distribution
DistributionDomain:
Value: !GetAtt Distribution.DomainNameCode breakdown
- SiteBucket
PublicAccessBlockConfiguration: ... trueAll four Block Public Access settings are on. The bucket can never be reached from the internet directly — only through CloudFront.
- SiteOAC
SigningBehavior: always / SigningProtocol: sigv4Tells CloudFront to sign every request to S3 with SigV4. It is attached through the origin's OriginAccessControlId, and OriginAccessIdentity is left as an empty string, meaning the legacy OAI is not used.
- IndexRewriteFunction
Runtime: cloudfront-js-2.0A CloudFront Function that turns /docs/ into /docs/index.html. It runs on viewer request, so the URI is rewritten before the cache lookup. The S3 website endpoint used to do this for you; with the REST endpoint plus OAC you do it here instead.
- aws-common-rules
OverrideAction: Count: {}The AWSManagedRulesCommonRuleSet starts in count mode: it records what it would block but stops nothing yet. Switch the override to None once you are sure there are no false positives.
- rate-limit-per-ip
RateBasedStatement: Limit / AggregateKeyType: IPCounts requests per client IP over the (default) five-minute window and blocks an IP that exceeds RateLimit. Once the IP's rate drops back down, it is allowed again automatically.
- Distribution
WebACLId: !GetAtt EdgeWebAcl.ArnThe WAFv2 web ACL is attached by ARN. The CachePolicyId is the AWS managed 'CachingOptimized' policy, which keeps headers, cookies and query strings out of the cache key while supporting gzip and brotli.
- SiteBucketPolicy
AWS:SourceArn: arn:aws:cloudfront::...:distribution/...The same bucket policy pattern as the syntax section, with the account ID and distribution ID filled in by !Sub.
Sample output (IDs and domains will differ):
$ aws cloudformation deploy --template-file edge-site.yaml \
--stack-name edge-site --region us-east-1
Waiting for changeset to be created..
Waiting for stack create/update to complete
Successfully created/updated stack - edge-site
$ curl -sI https://d1a2b3c4d5e6f7.cloudfront.net/ | grep -i x-cache
x-cache: Miss from cloudfront
$ curl -sI https://d1a2b3c4d5e6f7.cloudfront.net/ | grep -i x-cache
x-cache: Hit from cloudfront- Viewer sends HTTPS request
- WAF rules run in priority order
- Viewer-request function runs
- Cache key lookup at the edge
- Miss: regional cache, then origin
A WAF rule blocks
403 Forbidden from the edge
Cache hit
Served from edge, origin untouched
Cache miss
Fetched via OAC, cached for TTL
TTLs, invalidations and versioned file names
How long an object stays at the edge is decided by the Cache-Control header your origin sends combined with the cache policy's minimum and maximum TTLs. If the origin sends no header, the default TTL applies; if it does, the value is clamped between the minimum and maximum.
You can purge the cache after each deploy with an invalidation, but only the first 1,000 paths per month are free and each path after that is charged (a wildcard such as /images/* counts as one path). A better approach is to let your build tool emit content-hashed file names such as app.3f9c2b.js, cache those for a year, and keep a short TTL only on index.html. Then you rarely need an invalidation at all.
DIST_ID=E2QWRUHAPOMQZL
# Purge only the entry point; hashed assets never change in place
aws cloudfront create-invalidation --distribution-id "$DIST_ID" \
--paths "/index.html" "/"
# Wait until the edges have dropped the old copies
INV_ID=$(aws cloudfront list-invalidations --distribution-id "$DIST_ID" \
--query "InvalidationList.Items[0].Id" --output text)
aws cloudfront wait invalidation-completed --distribution-id "$DIST_ID" --id "$INV_ID"| File type | Caching strategy |
|---|---|
| app.3f9c2b.js, style.a81e.css | Long TTL (a year); never invalidated |
| index.html | Short TTL (e.g. 60 seconds) or invalidate on deploy |
| /api/* responses | Managed CachingDisabled policy |
CloudFront Functions vs Lambda@Edge
There are two ways to run code at the edge. CloudFront Functions run in every edge location and are meant for tiny pieces of JavaScript: adding headers, URL rewrites and redirects, normalising the cache key, validating a token. They cannot make network calls and are limited to a very short execution time. Lambda@Edge runs Node.js or Python Lambda functions at the regional edge caches. It can call the network, read the body and run much longer, but each invocation costs more and adds more latency.
The simple rule: start with CloudFront Functions, and reach for Lambda@Edge only when you need network calls, the request body, or the origin request/response events.
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Where it runs | Every edge location | Regional edge caches |
| Events | Viewer request/response only | Viewer and origin request/response |
| Runtime | JavaScript (cloudfront-js) | Node.js, Python |
| Network / body access | No | Yes |
| Good for | Headers, redirects, rewrites | Auth calls, image resizing, A/B logic |
Rolling out WAF safely: count, observe, then block
Deploy in count mode
Add managed rule groups with OverrideAction: Count. They record what they would block on real traffic without stopping anyone yet.
Observe for at least a few days
Check the CloudWatch metrics and sampled requests (or WAF logs) to see which rules match. Large upload bodies, for example, often match the SizeRestrictions_BODY rule.
Scope down the false positives
Keep individual rules in Count with RuleActionOverrides, or exclude specific paths with a ScopeDownStatement.
Switch to block and keep watching
Change OverrideAction to None and put a CloudWatch alarm on the BlockedRequests metric. A sudden spike may be an attack — or a new deploy that triggers a false positive.
# CLOUDFRONT-scope web ACLs live in us-east-1
aws wafv2 list-web-acls --scope CLOUDFRONT --region us-east-1 \
--query "WebACLs[].{Name:Name,Arn:ARN}" --output table
# Which requests matched the common rule group in the last hour?
ACL_ARN=$(aws wafv2 list-web-acls --scope CLOUDFRONT --region us-east-1 \
--query "WebACLs[?Name=='edge-site-edge-acl'].ARN" --output text)
aws wafv2 get-sampled-requests --region us-east-1 --scope CLOUDFRONT \
--web-acl-arn "$ACL_ARN" --rule-metric-name aws-common-rules \
--time-window StartTime=$(date -u -d '-1 hour' +%s),EndTime=$(date -u +%s) \
--max-items 50Shield Standard vs Shield Advanced
Shield Standard needs no setup: every AWS customer gets it automatically at no extra charge. Putting your site behind CloudFront and Route 53 means the whole edge network absorbs layer 3/4 floods for you.
Shield Advanced is a paid service with a monthly subscription per organization and a one-year commitment (check the pricing page for the current figure). For some applications it pays for itself: you get help from the Shield Response Team (SRT) during an attack, cost protection for scaling charges caused by a DDoS, health-based detection, and some AWS WAF charges included for the protected resources.
| Shield Standard | Shield Advanced | |
|---|---|---|
| Cost | Free, always on | Monthly subscription + commitment |
| Protection | Layer 3/4 | Layer 3/4/7 + health-based detection |
| Human help | None | Shield Response Team (SRT) |
| Bill protection | None | Cost protection for DDoS scaling |
In production
What production teams actually do
A typical e-commerce site has about three behaviors in one distribution: /assets/* goes to S3 with OAC and a long TTL, /api/* goes to an ALB with the managed CachingDisabled and AllViewerExceptHostHeader policies, and the default behavior serves index.html with a short TTL. To make the ALB reachable only through CloudFront, teams restrict its security group to CloudFront's origin-facing managed prefix list and check a secret custom header that CloudFront adds.
On the WAF side, the usual set is AWSManagedRulesCommonRuleSet, KnownBadInputs, AmazonIpReputationList and a dedicated rate-based rule for the login endpoint. WAF logs go to S3 or CloudWatch Logs and are queried with Athena. The web ACL itself lives in a template and changes through code review, because a 'temporary' block rule added in the console at midnight is a classic cause of a later outage.
Track the cache hit ratio as a metric
With additional metrics enabled on the distribution, CloudWatch shows CacheHitRate. Static assets should sit above 90 percent; a sudden drop usually means something unnecessary slipped into the cache key.
Common mistakes
Common mistakes
- Putting every header and cookie into the cache key. Add User-Agent or a session cookie to the key and every user gets a private cache entry, pushing the hit ratio towards zero. If the origin merely needs a header, forward it with an origin request policy instead of keying on it.
- Turning a managed rule group on in Block mode straight away. The CommonRuleSet includes a request-body size rule, so file uploads and APIs with large JSON bodies start returning 403 immediately. Watch it in Count mode first.
- Creating the web ACL in the wrong place. A web ACL for CloudFront must use Scope CLOUDFRONT in us-east-1; one created with REGIONAL scope in ap-southeast-1 cannot be attached to a distribution.
- Using the S3 website endpoint as the origin and expecting OAC to work. OAC works with the S3 REST endpoint (bucket.s3.region.amazonaws.com); the website endpoint still needs a public bucket.
- Invalidating /* on every deploy. The whole cache empties at once and a wave of traffic hits the origin. Use content-hashed file names instead.
Best practices
Best practices
- Keep every origin private: OAC for S3, a prefix list plus a secret header for an ALB.
- Keep the cache key minimal and forward what the origin needs through an origin request policy.
- Start every WAF change in Count mode and keep the web ACL in version-controlled templates.
- Give expensive endpoints such as login, OTP and search their own rate-based rules.
💰 Cost & Cleanup
CloudFront charges for data transfer out to the internet (per GB) and for requests (HTTPS costs slightly more). CloudFront has an always-free tier covering a monthly allowance of data transfer and requests, so a lab like this normally stays inside it. AWS WAF has no free tier: you pay a monthly fee per web ACL, a monthly fee per rule, and a fee per million requests inspected. Delete the stack as soon as you finish. Never subscribe to Shield Advanced for a lab — it carries a one-year commitment.
Clean up when you are done
# The bucket must be empty before CloudFormation can delete it
BUCKET=$(aws cloudformation describe-stacks --stack-name edge-site --region us-east-1 \
--query "Stacks[0].Outputs[?OutputKey=='BucketName'].OutputValue" --output text)
aws s3 rm "s3://$BUCKET" --recursive
aws cloudformation delete-stack --stack-name edge-site --region us-east-1
# Disabling and deleting a distribution can take several minutes
aws cloudformation wait stack-delete-complete --stack-name edge-site --region us-east-1Mini challenge
A custom cache policy for hashed assets
Write a small CloudFormation template (assets-cache-policy.yaml) that creates a dedicated cache policy for content-hashed /assets/* files, and export its ID so a distribution's CacheBehaviors can reuse it later.
- MinTTL 0, DefaultTTL one day (86400), MaxTTL one year (31536000)
- No cookies, headers or query strings in the cache key
- Gzip and Brotli compression enabled
- Output the policy ID with an export name that includes the stack name
Expected: The template passes cfn-lint with no errors, and after deploying, aws cloudformation list-exports shows the policy ID, ready to be referenced with !ImportValue from an /assets/* behavior.
Show hint
Use the AWS::CloudFront::CachePolicy resource. Set all three behaviors under ParametersInCacheKeyAndForwardedToOrigin to none. !Ref returns the cache policy ID.
Show solution
AWSTemplateFormatVersion: "2010-09-09"
Description: Long-lived cache policy for content-hashed static assets
Resources:
AssetsCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: !Sub "${AWS::StackName}-hashed-assets"
Comment: Long TTL for file names that change when their content changes
MinTTL: 0
DefaultTTL: 86400
MaxTTL: 31536000
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingGzip: true
EnableAcceptEncodingBrotli: true
CookiesConfig:
CookieBehavior: none
HeadersConfig:
HeaderBehavior: none
QueryStringsConfig:
QueryStringBehavior: none
Outputs:
AssetsCachePolicyId:
Value: !Ref AssetsCachePolicy
Export:
Name: !Sub "${AWS::StackName}-AssetsCachePolicyId"Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- The cache policy controls the cache key and TTLs; the origin request policy controls what reaches the origin without splitting the cache.
- Use OAC with an AWS:SourceArn condition to keep the S3 bucket fully private while CloudFront serves it.
- Content-hashed file names with long TTLs beat invalidating on every deploy.
- Start with CloudFront Functions; use Lambda@Edge only for network, body or origin-event needs.
- Create CloudFront web ACLs in us-east-1 with CLOUDFRONT scope, start in Count, then Block. Shield Standard is free and always on; buy Advanced only when the risk justifies it.
Amazon CloudFront Developer Guide — AWS Documentation
Restricting access to an Amazon S3 origin (OAC) — AWS Documentation
AWS WAF, AWS Firewall Manager, and AWS Shield Advanced Developer Guide — AWS Documentation