# CloudFront: a fast edge in front of your app

Put a CDN in front of a private S3 bucket: walk the create-distribution wizard, keep the bucket private with Origin Access Control, add HTTPS with ACM and clear the cache after a deploy.

Course: [AWS for DevOps](https://devops.rajeev.pro/courses/aws), lesson 9. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/aws/09-cloudfront

## What you will learn

- Explain what a CDN does and where CloudFront's edge locations fit
- Create a distribution in front of a private S3 bucket with Origin Access Control
- Pick between the flat-rate plans and pay as you go
- Tune caching with cache policies and behaviors, and invalidate after a deploy
- Add your own domain with an ACM certificate from us-east-1
- Know when to run code at the edge with CloudFront Functions or Lambda@Edge

## Why a CDN

Before a CDN, every visitor fetched every file from the origin. If that origin sat in Mumbai, a visitor in
São Paulo waited while each request crossed the planet. A popular image also made the origin repeat the same
work for every visitor. Distance slowed pages, and repeated requests added load.

CloudFront keeps copies at edge locations near viewers. The first request can go back to the origin; later
requests can use the cached response. CloudFront is AWS's content delivery network (CDN). It can also serve
HTTPS, apply web protections, and keep an S3 origin private.

```text
visitor → nearest edge location ──(cache hit)──→ file
                    └──(cache miss)──→ origin (private S3 bucket or ALB) → cached for next time
```

In this lesson, you'll configure a distribution, choose what to cache, and see how the edge can protect content.
The screenshots below are the real create-distribution wizard in a practice account, walked to the final
**Review** step. That account hadn't yet been verified for CloudFront, which AWS requires before a new account's
first distribution, so this lesson stops at Review. If your new account gets the same error, open an
**Account and billing** support case asking AWS to verify it.

## Create a distribution

**CloudFront → Distributions → Create distribution.** The first choice is how to pay:

> **Figure.** Create distribution, step 1 Choose a plan: (1) Flat-rate plans selected, with Pay as you go as the alternative. Four plans: Free 0 dollars a month with global CDN, WAF, DNS and edge compute; Pro 15 dollars; Business 200 dollars; Premium 1,000 dollars. (2) The Choose Free button.
>
> (1) Flat-rate plans or pay as you go. (2) The Free plan covers a small site: CDN, WAF and up to 100 GB a month.

**Flat-rate plans** bundle the CDN, WAF, DNS and logging at a fixed monthly price with no overage charges.
**Pay as you go** bills each request and GB separately: cheapest at very low volume, but with no spending cap.
For a learning project or a small site, Free is the safe choice.

> **Figure.** Step 2 Get started: (1) Distribution name academy-site. (2) Distribution type: Single website configuration selected; Multiple website configuration is the alternative. Below, an optional Route 53 managed domain.
>
> (1) A name, stored as a tag. (2) One configuration for one site.

## The origin

The **origin** is where CloudFront fetches files it hasn't cached yet: an S3 bucket, a load balancer, API
Gateway, a Lambda function, or any public URL.

> **Figure.** Step 3 Specify origin: origin types Amazon S3 (selected), Elastic Load Balancer, API Gateway, Elemental MediaPackage, Lambda function, VPC origin and Other. (1) Amazon S3. (2) S3 origin: the bucket's Regional domain name in ap-south-1.
>
> (1) An S3 origin. (2) The bucket's domain name; Browse S3 picks it from a list.

> **Figure.** Origin settings: (1) Allow private S3 bucket access to CloudFront - Recommended, ticked: CloudFront will update the bucket policy so only this distribution can read it. (2) Use recommended origin settings. Below, Use recommended cache settings tailored to serving S3 content.
>
> (1) Origin Access Control: the bucket stays private, readable only by this distribution. (2) Recommended origin and cache settings for S3.

**Origin Access Control (OAC)** is the important part. CloudFront signs its requests to S3, and the wizard adds a
bucket policy that allows `s3:GetObject` only for this distribution:

```json
{
  "Effect": "Allow",
  "Principal": { "Service": "cloudfront.amazonaws.com" },
  "Action": "s3:GetObject",
  "Resource": "arn:aws:s3:::my-site-bucket/*",
  "Condition": { "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::111122223333:distribution/E1ABCDEF" } }
}
```

Block Public Access stays on (lesson 6), and nobody can skip the CDN and read the bucket directly.

> **Figure.** Step 4 Enable security: (1) Web Application Firewall protections included in the plan at no extra charge, protecting against common web vulnerabilities, application probing and known-bad IP addresses. (2) Use monitor mode, to count what would be blocked before blocking.
>
> (1) WAF protections included in the plan. (2) Monitor mode counts would-be blocks first, so you can check nothing legitimate gets caught.

> **Figure.** Step 5 Review and create: distribution name academy-site, billing Free (0 dollars a month), today's pro-rated charge 0 dollars; the S3 origin with CloudFront granted access; default cache settings for S3; security protections enabled. (1) Billing Free. (2) Create distribution.
>
> (1) Billing: Free, $0. (2) Create distribution. A new distribution takes a few minutes to deploy to every edge.

When it's created you get a domain like `d1234abcd.cloudfront.net`; open it and you get `index.html` from the
nearest edge. Set the distribution's **default root object** to `index.html` so `/` works.

> **Video.** [CloudFront Origin Access Control (OAC) - SCS-C03](https://www.youtube.com/watch?v=lN_2g0w4p40) (Cybr)

## Caching and invalidations

> **Figure.** First request from a visitor in São Paulo: the nearby edge location has no copy, so it fetches logo.png from the origin, a private S3 bucket in Mumbai readable only through Origin Access Control, keeps a copy for the TTL and answers with X-Cache: Miss from cloudfront. Every request after: the edge already has the copy and answers directly with X-Cache: Hit from cloudfront, without asking the origin.
>
> A miss travels to the origin once and leaves a copy at the edge. Hits are answered nearby.

A **behavior** maps a path pattern (`/api/*`, `*.js`, default `*`) to an origin and a **cache policy**: how long
to keep files (TTL) and what makes two requests "the same" (the cache key: path, plus any headers, cookies or
query strings you include). Keep the cache key small; every extra header splits the cache.

Think of the cache key as a label on a shelf. Requests with the same key can share one response. If you add a
cookie or header, different values create separate entries. That is useful only when the response really varies
by that value. Otherwise, the cache hit rate falls and more requests reach the origin. A behavior applies these
rules to matching paths, so give APIs a policy that does not cache user-specific responses.

| Content                                       | Typical policy                                                   |
| --------------------------------------------- | ---------------------------------------------------------------- |
| `app.3f9c2e1.js`, images with versioned names | cache for a year: the name changes when the file does            |
| `index.html`                                  | short TTL, or invalidate on every deploy                         |
| `/api/*` to an ALB                            | `CachingDisabled`, forward the headers and cookies the app needs |

After a deploy, clear old copies with an **invalidation**:

```sh
$ aws s3 sync ./build s3://my-site-bucket/ --delete
$ aws cloudfront create-invalidation --distribution-id E1ABCDEF --paths "/index.html"
```

Response headers tell you what happened: `X-Cache: Hit from cloudfront` means an edge served it, `Miss from
cloudfront` means it went to the origin.

An invalidation asks CloudFront to remove cached objects that match the paths you name. Use it when content
changed but its URL stayed the same. For static assets, versioned filenames are often simpler: `app.a91f.js`
and `app.b720.js` are separate cache entries. The new HTML can point to the new filename without clearing the
old one. Keep the HTML entry point on a shorter lifetime because it points to those versioned files.

> **Video.** [AWS CloudFront Caching Behaviors Explained | Cache Keys, TTL & Origin Shield](https://www.youtube.com/watch?v=rrpREiIAcHE) (CloudWolf AWS)

## Your own domain and HTTPS

To use `www.example.com` instead of the `cloudfront.net` name:

1. Request a **public certificate in ACM in us-east-1** (N. Virginia) for the domain. CloudFront only reads
   certificates from that Region, wherever your origin is.
2. Prove you own the domain with the DNS record ACM gives you (one click if the domain is in Route 53).
3. Add the domain as an alternate domain name on the distribution and pick the certificate.
4. Point the domain at the distribution with a Route 53 **alias** record (lesson 8).

> **Figure.** AWS Certificate Manager in the United States (N. Virginia) Region, Request certificate page: certificate type options, with Request a public certificate highlighted.
>
> ACM in N. Virginia: Request a public certificate. Public ACM certificates are free and renew themselves.

> **Video.** [How to configure AWS Cloudfront for your website with free SSL | CDN | AWS Certificate Manager](https://www.youtube.com/watch?v=ibe25dyyidE) (Identical Cloud)

## Code at the edge

> **Figure.** CloudFront Functions page with the Create function button highlighted.
>
> CloudFront Functions: small JavaScript functions that run at every edge location.

|          | CloudFront Functions                                    | Lambda@Edge                                            |
| -------- | ------------------------------------------------------- | ------------------------------------------------------ |
| Runs     | at every edge location, under 1 ms                      | at regional edge caches, up to seconds                 |
| Language | JavaScript only                                         | Node.js or Python                                      |
| Can      | rewrite URLs, add headers, redirect, simple auth checks | call other services, read the body, generate responses |
| Cost     | very low, per million invocations                       | higher, like Lambda                                    |

A typical function adds security headers or rewrites `/about` to `/about/index.html` for a static site.

> **In production.** Keep the bucket private behind OAC, serve only HTTPS (redirect HTTP), use versioned file names so you rarely need invalidations, turn on standard logging or real-time logs, attach WAF rules, and define the distribution in Terraform or CloudFormation. For an API behind an ALB, use a caching-disabled behavior and allow only CloudFront to reach the ALB.

> **Video.** [AWS CloudFront: Hands-On Guide to Edge Functions (Functions vs Lambda@Edge)](https://www.youtube.com/watch?v=vkwqrrsH-d8) (Maruchin Tech)

## Signed URLs, geo restriction and origin failover

CloudFront signed URLs grant one path for a short time; signed cookies grant a set of paths to a browser. Geo
restriction is a coarse country allow or deny list, not application authorisation. Origin failover switches to a
secondary origin for configured errors, so the fallback must contain compatible content.

These controls answer different questions. A signature says whether a request may fetch protected content until
an expiry time. A country restriction says whether viewers from a country may reach this distribution. Neither
replaces application authorization for a user's records. Failover says what CloudFront should do when the primary
origin returns one of the configured errors. Choose those errors deliberately and keep the secondary content
compatible; otherwise the fallback can return stale or unrelated files while the distribution appears available.

```sh
$ aws cloudfront get-distribution-config --id "$DISTRIBUTION_ID" \
  --query 'DistributionConfig.{Origins:Origins.Items[].DomainName,Restrictions:Restrictions}'
```

## Mission: A private bucket behind a CDN

Create a private S3 bucket with an index.html, walk CloudFront's create-distribution wizard with that bucket as the origin and private access allowed, and stop at Review to check every setting. If your account is verified for CloudFront, create it, load the page through the cloudfront.net domain, then disable and delete the distribution and the bucket.

- You need: An AWS account with the console and AWS CLI
- You'll have: A Review page showing the Free plan, your S3 origin and private bucket access; if created, your page served from a cloudfront.net URL

```sh
$ BUCKET=academy-cf-$(aws sts get-caller-identity --query Account --output text)-$RANDOM
$ aws s3api create-bucket --bucket $BUCKET --region ap-south-1 --create-bucket-configuration LocationConstraint=ap-south-1
$ printf '<h1>Served by CloudFront</h1>\n' > index.html
$ aws s3 cp index.html s3://$BUCKET/index.html --content-type text/html
$ echo "Origin: $BUCKET.s3.ap-south-1.amazonaws.com"
$ # Console: CloudFront → Create distribution → Free → name → S3 origin above,
$ #          Allow private S3 bucket access → Next → Next → Review (→ Create distribution)
$ # If created: curl -sI https://<distribution>.cloudfront.net/index.html | grep -i x-cache
$ # Clean up: disable the distribution, wait for Deployed, delete it; then:
$ aws s3 rb s3://$BUCKET --force
```

The first `curl` after creating says `Miss from cloudfront`, the second `Hit from cloudfront`: the second request
never reached your bucket.

## Try it

- Open CloudFront → Create distribution and read the four plans. What does Free include?
- Walk the wizard with an S3 origin and stop at Review. Which permission will it add to the bucket?
- Request a public certificate in ACM in us-east-1 for a domain you own.
- Once a distribution exists, create an invalidation for /index.html and time how long it takes.
- Read the response headers of a CloudFront URL twice and compare X-Cache.
- Open CloudFront Functions and read the example code.

## Quiz

1. Why put CloudFront in front of an S3 website instead of serving the bucket directly?
   - S3 cannot serve files
   - **Users get the files from an edge location near them, the bucket can stay private, and you get HTTPS on your domain** (answer)
   - It is required by S3
   Why: CloudFront caches copies at edge locations worldwide, so a user in Delhi isn't fetching every file from the origin Region.

2. What does Origin Access Control (OAC) do?
   - Makes the bucket public
   - **Lets only your CloudFront distribution read the private bucket, through a bucket policy that names it** (answer)
   - Encrypts the files
   Why: The wizard's Allow private S3 bucket access option sets this up. Nobody can bypass the CDN and read the bucket directly.

3. You deploy a new index.html, but users still see the old page. What do you do?
   - Delete the distribution
   - **Create an invalidation for /index.html (or version your file names)** (answer)
   - Wait a year
   Why: Invalidations remove cached copies at every edge. For assets, versioned names like app.3f9c2e1.js avoid needing them at all.

4. In which Region must the ACM certificate for a CloudFront custom domain be requested?
   - The same Region as the bucket
   - **us-east-1 (N. Virginia), always** (answer)
   - Any Region
   Why: CloudFront is a global service and reads its certificates from us-east-1. A certificate in ap-south-1 won't show up in the list.

5. You need to add a security header to every response with almost no latency. Which fits best?
   - **CloudFront Functions** (answer)
   - An EC2 instance
   - A NAT gateway
   Why: CloudFront Functions run lightweight JavaScript at every edge in under a millisecond. Lambda@Edge is for heavier logic that needs more time, memory or network calls.

## Resources

- [What is Amazon CloudFront?](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) (AWS Docs)
- [Restrict access to an Amazon S3 origin (OAC)](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html) (AWS Docs)
- [Cache policies](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/controlling-the-cache-key.html) (AWS Docs)
- [Invalidate files](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html) (AWS Docs)
- [Choosing between CloudFront Functions and Lambda@Edge](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-choosing.html) (AWS Docs)
