Overview and What You Will Learn
Amazon CloudFront is a content delivery network that caches your content at edge locations close to users, and AWS Global Accelerator gives your application static anycast IP addresses that route traffic over the AWS global network. They both speed up global access, but they solve different problems, so choosing correctly matters. In this lab you serve a private S3 bucket through CloudFront with Origin Access Control, then watch caching and invalidation work.
By the end you will be able to:
- Explain how CloudFront caching, cache keys and TTLs work
- Pick an origin type: S3 with OAC, a VPC origin or a custom HTTP origin
- Keep an S3 bucket private while serving it through CloudFront
- Restrict access by country and protect content with signed URLs
- Clear stale content with invalidations or versioned file names
- Choose between CloudFront Functions and Lambda@Edge
- Explain how Global Accelerator works and when to use it instead of CloudFront
Why This Matters in Production
A streaming service such as Hotstar serves thumbnails, metadata and static assets to millions of people. A user in Chennai should get those from a nearby edge location in milliseconds, not make a round trip to an origin in Mumbai. With a healthy cache hit ratio, most requests never reach the origin, so the origin needs less capacity and survives traffic spikes.
Some traffic cannot be cached, such as trading API calls, game sessions or live scores. A broker such as Zerodha cares about consistent latency for those, and Global Accelerator carries them from the nearest edge over the AWS backbone instead of the congested public internet. The skill is knowing which service fits which traffic.
Core Principles
What Is Amazon CloudFront and What Problems Does It Solve?
CloudFront caches content at a global network of edge locations and serves it to users from the nearest one. It improves read performance because users get cached content nearby, and it reduces origin load because cache hits never reach your S3 bucket or servers. It also helps absorb DDoS traffic, includes AWS Shield Standard, and integrates with AWS WAF for filtering at the edge.
Without CloudFront: User in Chennai -> origin in Mumbai on every requestWith CloudFront: User in Chennai -> nearby edge (cache hit) -> origin only on a missHow Does CloudFront Caching Work?
On each request, the edge location checks its cache using a cache key built from the URL path and any headers, query strings or cookies you choose to include. A hit is served immediately, and a miss goes to the origin, is stored for its TTL, and is returned. CloudFront also uses regional edge caches between the edge and the origin to improve hit ratio.
- The default TTL is 24 hours (86400 seconds), and cache policies set minimum, default and maximum TTLs
- CloudFront honors the origin's Cache-Control headers within those limits
- Use managed cache policies such as CachingOptimized for static content and CachingDisabled for uncacheable APIs
- Keep the cache key small. Including every query string or cookie lowers the hit ratio
Which CloudFront Origin Type Should You Use?
An origin is where CloudFront fetches content on a cache miss. Use S3 with OAC for static files, a VPC origin for private application servers, and a custom origin for any other HTTP backend.
| Origin | Use for |
|---|---|
| S3 bucket (REST endpoint) | Static files, kept private with OAC |
| VPC origin | Private ALB, NLB or EC2 in private subnets |
| Custom origin | Public ALB, on-premises server, S3 website endpoint |
An S3 static website endpoint is a custom origin, not an S3 bucket origin, and it supports HTTP only. For resilience, an origin group lets CloudFront fail over to a second origin when the first returns errors.
How Does Origin Access Control Keep an S3 Bucket Private?
Origin Access Control (OAC) lets CloudFront sign its requests to S3, so the bucket stays fully private and only your distribution can read it. OAC replaces the older Origin Access Identity and supports features such as SSE-KMS. You attach a bucket policy that trusts the CloudFront service and only your distribution.
| Policy element | Value |
|---|---|
| Effect | Allow |
| Principal | cloudfront.amazonaws.com |
| Action | s3:GetObject |
| Resource | arn:aws:s3:::my-bucket/* |
| Condition | AWS:SourceArn equals your distribution ARN |
Requests to the CloudFront URL work, and requests to the S3 URL directly return 403 Access Denied.
Common MistakeForgetting to apply the bucket policy after creating the OAC. CloudFront generates the policy for you but does not apply it, so every request to S3 fails with 403 until you copy it into the bucket permissions.
SecurityDo not make the bucket public to serve it through CloudFront. A public bucket lets anyone bypass the CDN, WAF and any access controls you set on the distribution.
How Do You Restrict CloudFront Access by Country?
Geo restriction allows or blocks viewers by country for the whole distribution, and blocked viewers receive a 403 response. Use an allow list to serve only approved countries, or a block list to exclude specific ones. CloudFront decides the country with a third-party IP geolocation database, so it is accurate but not perfect. For rules that differ by path, use AWS WAF geo match conditions.
Typical use: licensed video content that can only be shown in certain countries.
RememberGeo restriction is set in the distribution settings under Security. To change it from the CLI you must fetch the whole distribution config and its ETag, edit it, and update with that ETag, so the console is simpler for this one setting.
How Do You Protect Private Content on CloudFront?
Use signed URLs or signed cookies to give time-limited access to specific content, and AWS WAF to filter malicious requests. A signed URL suits a single file such as a download, and signed cookies suit many files such as a whole video. Your application generates the signature with a key pair that CloudFront trusts.
How Do You Clear Stale Content from CloudFront?
The best approach is to avoid the problem with versioned file names, and the fallback is an invalidation. Until the TTL expires, edge locations keep serving the old copy of an updated file. An invalidation removes objects from the cache so the next request fetches fresh content.
- Versioned names: Use names like app.4f3a9c.js so a new version is a new cache key and no invalidation is needed
- Invalidations: Use for files that keep the same name, such as index.html
- The first 1,000 invalidation paths each month are free, and later paths are billed. A wildcard path such as /* counts as one path
aws cloudfront create-invalidation \ --distribution-id E1ABCDEF234567 \ --paths "/index.html" # Invalidate a folderaws cloudfront create-invalidation \ --distribution-id E1ABCDEF234567 \ --paths "/images/*" # Check progressaws cloudfront get-invalidation \ --distribution-id E1ABCDEF234567 \ --id <INVALIDATION-ID>Common MistakeUpdating a file in S3 and expecting users to see it at once. Without a new file name or an invalidation, they get the cached copy until the TTL ends.
What Is the Difference Between CloudFront Functions and Lambda@Edge?
Both run your code at the edge, but CloudFront Functions are tiny, very fast and cheap, while Lambda@Edge is a fuller Lambda runtime that can use the network. Code can run at four points: viewer request, origin request, origin response and viewer response. CloudFront Functions run only on the two viewer events.
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Language | JavaScript | Node.js and Python |
| Run time | Under 1 ms | Up to 5 s viewer, 30 s origin |
| Network access | No | Yes |
| Triggers | Viewer only | All four |
Memory also differs: Lambda@Edge viewer events are limited to 128 MB, and origin events can use far more. Deploy Lambda@Edge functions from us-east-1.
- CloudFront Functions: URL rewrites and redirects, header changes, cache key normalization, simple token checks
- Lambda@Edge: Authentication that calls a database or service, reading the request body, SDK calls, dynamic response generation
What Is AWS Global Accelerator?
Global Accelerator gives your application two static anycast IP addresses and routes user traffic to the nearest AWS edge location, then across the AWS global network to your endpoint. Endpoints can be Application Load Balancers, Network Load Balancers, EC2 instances or Elastic IPs in one or more Regions. It supports TCP and UDP, so it works for non-HTTP traffic such as gaming, VoIP and IoT.
- Static IPs: Clients and firewalls can allow-list two fixed addresses, and the backend can change freely
- Health checks and failover: Global Accelerator checks endpoint health and shifts traffic away from unhealthy endpoints, typically within about a minute, with no waiting for DNS caches to expire
- Traffic control: Traffic dials set the share of traffic per Region, and endpoint weights split traffic inside a Region, which helps with blue-green rollouts
- Client IP preservation: Supported for some endpoint types, so your application can see real client addresses
Global Accelerator does not cache content. Every request still reaches your endpoint, and you pay an hourly fee plus a data transfer premium.
Should You Use CloudFront or Global Accelerator?
Use CloudFront for web content that can be cached, and Global Accelerator for traffic that cannot be cached or is not HTTP. CloudFront can also speed up dynamic HTTP requests by using the AWS network, but it is built around caching and HTTP. Global Accelerator is built around fixed IPs, TCP and UDP, and fast failover.
| Need | Better fit |
|---|---|
| Cache images, video and static files | CloudFront |
| Edge code, WAF, signed URLs | CloudFront |
| Static IPs for allow-lists | Global Accelerator |
| TCP or UDP, such as gaming or VoIP | Global Accelerator |
| Fast multi-Region failover without DNS | Global Accelerator |
They are complementary. A video platform can serve thumbnails and static assets through CloudFront, and send real-time API traffic, such as live scores and chat, through Global Accelerator.
Common MistakeUsing Global Accelerator for cacheable static content. It does not cache, so you pay more and gain no cache benefit compared with CloudFront.
Detailed Step-by-Step Practical Lab
This lab serves a private S3 bucket through CloudFront with OAC. Replace rahul with your own suffix, since bucket names are global.
Step 1: Create a private bucket and upload a file
aws s3 mb s3://devops-cloudfront-lab-rahul --region ap-south-1 echo '<h1>Version 1 served via CloudFront</h1>' > index.htmlaws s3 cp index.html s3://devops-cloudfront-lab-rahul/index.htmlBlock Public Access stays on, which is the default.
Step 2: Create the distribution in the console
In CloudFront, choose Create distribution.
- Origin domain: select the S3 bucket
- Origin access: Origin access control settings, then Create new OAC
- Viewer protocol policy: Redirect HTTP to HTTPS
- Default root object: index.html
- Create the distribution
CloudFront shows a banner to update the S3 bucket policy. Choose Copy policy, open the bucket permissions, paste the policy and save.
# Wait until the distribution reports Deployedaws cloudfront wait distribution-deployed --id E1ABCDEF234567Step 3: Test caching and private access
# First request: cache miss. Repeat it: cache hit.curl -I https://d111111abcdef8.cloudfront.net/index.htmlcurl -I https://d111111abcdef8.cloudfront.net/index.html # Direct S3 URL: 403 because the bucket is privatecurl -I https://devops-cloudfront-lab-rahul.s3.ap-south-1.amazonaws.com/index.htmlLook at the x-cache header. The first response shows a miss and the second shows a hit from CloudFront.
Step 4: Update the file and invalidate
echo '<h1>Version 2 served via CloudFront</h1>' > index.htmlaws s3 cp index.html s3://devops-cloudfront-lab-rahul/index.html # Still returns version 1 from the cachecurl -s https://d111111abcdef8.cloudfront.net/index.html aws cloudfront create-invalidation \ --distribution-id E1ABCDEF234567 \ --paths "/index.html"After the invalidation completes, usually within a minute or so, the same curl returns version 2.
Step 5: Clean up
In the console, disable the distribution, wait until it finishes deploying, and delete it. Then remove the bucket.
aws s3 rb s3://devops-cloudfront-lab-rahul --forceProduction Best Practices & Common Pitfalls
- Always use OAC for S3 origins: Keep the bucket private.
- Use HTTPS: Redirect HTTP to HTTPS, and keep custom domain certificates in ACM in us-east-1.
- Version static assets: File names with hashes avoid invalidations and give long TTLs safely.
- Tune TTLs and cache keys: Long TTLs and small cache keys give a higher hit ratio.
- Attach WAF: Filter bad requests at the edge, and use Shield Advanced for large DDoS risk.
- Use origin groups: Fail over to a second origin if the first returns errors.
- Pick the right edge compute: Start with CloudFront Functions and move to Lambda@Edge only when you need network access or the body.
- Use Global Accelerator for uncacheable, non-HTTP or fixed-IP needs: Not for static content.
- Monitor cache hit ratio: A low ratio usually means a cache key or TTL problem.
Quick Reference & Troubleshooting Commands
| Task | Command |
|---|---|
| List distributions | aws cloudfront list-distributions |
| Get distribution details | aws cloudfront get-distribution --id <DIST-ID> |
| Create invalidation | aws cloudfront create-invalidation --distribution-id <DIST-ID> --paths "/*" |
| Check invalidation | aws cloudfront get-invalidation --distribution-id <DIST-ID> --id <INVAL-ID> |
| List accelerators | aws globalaccelerator list-accelerators --region us-west-2 |
| Describe an accelerator | aws globalaccelerator describe-accelerator --accelerator-arn <ARN> --region us-west-2 |
| List listeners | aws globalaccelerator list-listeners --accelerator-arn <ARN> --region us-west-2 |
| Problem | Likely cause and fix |
|---|---|
| 403 from S3 origin | OAC not set up or bucket policy not applied. Apply the generated policy. |
| Old content after update | Cached until TTL. Invalidate or use new file names. |
| 502 or 504 from CloudFront | Origin unreachable or slow. Check origin health, security groups and timeouts. |
| Low cache hit ratio | TTL too low or cache key includes too many values. Simplify the cache policy. |
| Custom domain HTTPS fails | Certificate is not in us-east-1 or lacks the domain name. |
| Accelerator not sending to a Region | Health check failing or traffic dial at 0. Check both. |