# Amazon Cloudfront

### 🔗 **Quicklinks (Bookmark):**

* Cost Explorer: [AWS Cloudfront Costs by API](https://us-east-1.console.aws.amazon.com/costmanagement/home?region=us-east-1#/cost-explorer?chartStyle=STACK\&costAggregate=unBlendedCost\&endDate=2025-09-30\&excludeForecasting=false\&filter=%5B%7B%22dimension%22:%7B%22id%22:%22Service%22,%22displayValue%22:%22Service%22%7D,%22operator%22:%22INCLUDES%22,%22values%22:%5B%7B%22value%22:%22Amazon%20CloudFront%22,%22displayValue%22:%22CloudFront%22%7D%5D%7D%5D\&futureRelativeRange=CUSTOM\&granularity=Daily\&groupBy=%5B%22Operation%22%5D\&historicalRelativeRange=LAST_MONTH\&isDefault=true\&reportMode=STANDARD\&reportName=New%20cost%20and%20usage%20report\&showOnlyUncategorized=false\&showOnlyUntagged=false\&startDate=2025-09-01\&usageAggregate=undefined\&useNormalizedUnits=false)
* Cost Explorer (Select Transfer in Usage Type): [AWS Cloudfront Datatransfer Costs & Usage](https://342912988800-nzphfa77.us-east-1.console.aws.amazon.com/costmanagement/home?region=us-east-1#/cost-explorer?chartStyle=STACK\&costAggregate=unBlendedCost\&endDate=2025-09-30\&excludeForecasting=false\&filter=%5B%7B%22dimension%22:%7B%22id%22:%22Service%22,%22displayValue%22:%22Service%22%7D,%22operator%22:%22INCLUDES%22,%22values%22:%5B%7B%22value%22:%22Amazon%20CloudFront%22,%22displayValue%22:%22CloudFront%22%7D%5D%7D%5D\&futureRelativeRange=CUSTOM\&granularity=Daily\&groupBy=%5B%22UsageType%22%5D\&historicalRelativeRange=LAST_MONTH\&isDefault=true\&reportMode=STANDARD\&reportName=New%20cost%20and%20usage%20report\&showOnlyUncategorized=false\&showOnlyUntagged=false\&startDate=2025-09-01\&usageAggregate=undefined\&useNormalizedUnits=false)

<div align="center"><figure><img src="https://2365269676-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-Mfczr4lKFhrfXN7ion1%2Fuploads%2FTnlDnmDiz8sTGZIyywJI%2Fimage.png?alt=media&#x26;token=99338568-c9fe-48fc-8b17-a03cefa464d5" alt="" width="158"><figcaption></figcaption></figure></div>

* Cost Explorer: [AWS Cloudfront Invalidations (URL) Costs & Usage](https://us-east-1.console.aws.amazon.com/costmanagement/home?region=us-east-1#/cost-explorer?chartStyle=STACK\&costAggregate=unBlendedCost\&endDate=2025-09-30\&excludeForecasting=false\&filter=%5B%7B%22dimension%22:%7B%22id%22:%22Service%22,%22displayValue%22:%22Service%22%7D,%22operator%22:%22INCLUDES%22,%22values%22:%5B%7B%22value%22:%22Amazon%20CloudFront%22,%22displayValue%22:%22CloudFront%22%7D%5D%7D,%7B%22dimension%22:%7B%22id%22:%22UsageType%22,%22displayValue%22:%22Usage%20type%22%7D,%22operator%22:%22INCLUDES%22,%22values%22:%5B%7B%22value%22:%22Invalidations%22,%22displayValue%22:%22Invalidations%20\(URLs\)%22%7D%5D%7D%5D\&futureRelativeRange=CUSTOM\&granularity=Daily\&groupBy=%5B%22UsageType%22%5D\&historicalRelativeRange=LAST_MONTH\&isDefault=true\&reportMode=STANDARD\&reportName=New%20cost%20and%20usage%20report\&showOnlyUncategorized=false\&showOnlyUntagged=false\&startDate=2025-09-01\&usageAggregate=usageQuantity\&useNormalizedUnits=false)
* Savings: [AWS Cloudfront savings Bundle](https://us-east-1.console.aws.amazon.com/cloudfront/v3/home?#/savings-bundle/purchase)
* Cloudfront Monitoring: [AWS Cloudfront Popular URLs Dashboard](https://us-east-1.console.aws.amazon.com/cloudfront/v3/home#/popular_urls)
* Cloudfront Monitoring: [AWS Cloudfront Usage Dashboard](https://us-east-1.console.aws.amazon.com/cloudfront/v3/home#/usage)
* Cloudfront Queries: [Query CUR on Athena](https://catalog.workshops.aws/cur-query-library/en-US/queries/networking-and-content-delivery#amazon-cloudfront)

Amazon CloudFront is AWS’s global CDN for accelerating web apps, APIs, and media with 700+ points of presence and built-in DDoS protection (Shield Standard). It’s fast—but bills can spike from **data transfer out**, **request volume**, **edge compute (Functions/Lambda\@Edge)**, **invalidations**, and **over-broad geography**. This page blends Grok’s outline with a pragmatic FinOps playbook, including **Security Savings Bundle** details.

***

### 🚀 What is CloudFront?

CloudFront securely delivers static/dynamic content, video, software, and APIs with low latency from a global edge network. It integrates tightly with S3, ALB/EC2/ECS, and media origins—**origin→CloudFront transfer from AWS origins is $0/GB**—and supports edge compute for request/response customization.

**Features**

* Global edge network with intelligent routing and caching
* **Edge compute**: CloudFront Functions (ultra-light JS) and Lambda\@Edge (full Node.js)
* Built-in security: **AWS Shield Standard** at no extra cost; WAF/Shield Advanced optional
* HTTPS by default; signed URLs/cookies, Origin Access Control (OAC/OAI), field-level encryption
* Free tier for low/steady workloads

**Common content types**

* Static/dynamic web, API traffic, streaming/live/on-demand video, downloads/game updates/firmware, IoT data

***

### ⚙️ Price Classes — pick the right coverage

| Class   | Coverage                                               | Use when                                                           |
| ------- | ------------------------------------------------------ | ------------------------------------------------------------------ |
| **All** | Full global network (700+ PoPs)                        | Truly global audiences and latency-sensitive media                 |
| **200** | Broad global, excludes some higher-cost/remote regions | Balanced cost/performance for worldwide but concentrated audiences |
| **100** | Major markets (NA/EU plus select regions)              | Cost-focused when most users are in North America/Europe           |

> Start with the **narrowest** Price Class that meets your latency SLOs; expand only where data shows a need.

***

### 🧬 Edge compute options

| Option                   | Best for                                                         | Notes                                                                        |
| ------------------------ | ---------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| **CloudFront Functions** | Header/cookie rewrites, URL normalization, simple auth/AB tests  | Sub-ms, ultra-low cost; no network calls/body access; runs at edge location  |
| **Lambda\@Edge**         | Complex logic: body transforms, origin selection, external calls | Higher cost & latency; code replicated globally; runs at regional edge cache |

**Rule of thumb:** Prefer **Functions** for simple logic; use **Lambda\@Edge** only when you need body/network access.

***

### 🏛️ Origins & deployment

| Origin                      | Use when                                  | Notes                                                                   |
| --------------------------- | ----------------------------------------- | ----------------------------------------------------------------------- |
| **S3**                      | Static sites/assets/downloads             | Pair with **OAC**; origin fetches to CloudFront are **free**            |
| **ALB/EC2/ECS/EKS**         | Dynamic sites, APIs, personalized content | Cache what you can; still benefits from free origin→edge transfer       |
| **MediaPackage/MediaStore** | Live/VOD streaming                        | Segment-friendly caching; consider **Origin Shield** for origin offload |

All distributions support HTTPS; enable **field-level encryption** for sensitive headers.

***

### 🧠 CloudFront optimization strategy

**Quick wins**

* Put CloudFront in front of AWS origins to zero out origin→edge transfer
* Choose the **lowest** Price Class that meets user latency
* Prefer **CloudFront Functions** over Lambda\@Edge for light logic

**Caching & behaviors**

* Long TTLs for immutable assets; use cache policies to vary only on required headers/cookies/query params
* Enable **Brotli/Gzip** compression; use **Origin Shield** to reduce origin hits
* Design path-based behaviors (e.g., `/api/*` vs `/static/*`) and apply appropriate TTLs

**Traffic control & security**

* **Geo-restrict** regions you don’t serve; block obvious abuse with **AWS WAF**
* Use **signed URLs/cookies** for private content; keep S3 buckets private via **OAC/OAI**

**Invalidations & housekeeping**

* Batch invalidations (the **first 1,000 paths/month are free**); avoid wildcard nukes
* Target **>80% cache hit ratio**; analyze top URLs, regions, and status codes monthly

***

### 💸 Pricing model & the **Security Savings Bundle**

| Plan                                   | What you pay for                                                                                                                                                                             | Notes                                                                                                                          |
| -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ |
| **Pay-as-you-go**                      | Data transfer out (tiered by geo), HTTP/HTTPS requests, optional features (real-time logs, FLE), edge compute invocations                                                                    | Baseline pricing for most workloads                                                                                            |
| **Free Tier**                          | **1 TB** data out + **10M** HTTP/HTTPS requests + **2M** CloudFront Functions invocations/month                                                                                              | Great for dev/low-volume                                                                                                       |
| **CloudFront Security Savings Bundle** | **Commit to a monthly CloudFront spend for 12 months** and get **up to \~30% savings** across CloudFront usage types. Includes **AWS WAF usage credits up to \~10%** of your monthly commit. | Self-service signup; your regular usage draws down the commit; overages billed at standard rates. Shield Advanced not included |

**Bundle cheat-sheet**

* **Term:** 12 months; billed on a monthly spend commitment
* **Applies to:** Data transfer out, requests, Functions, Lambda\@Edge, logging, etc.
* **Security kicker:** WAF credits (up to \~10% of your commit) included
* **Good fit when:** Your CloudFront spend is predictable/stable month-to-month

***

### 📊 Cost controls to turn on

* **Geo reports + Price Class** to align coverage with audience demand
* **Cache hit ratio monitoring**; fix low-hit paths with cache keys/TTLs
* **Budgets/alerts** for DTO spikes, invalidation overages, and edge compute invocations
* **Real-time logs** for hot-path debugging and bot analysis

***

### 🔒 Security & compliance

* **Shield Standard** is included; layer **AWS WAF** for app rules (bot control, rate limiting, OWASP)
* **OAC** keeps S3 private; use **mTLS/signed URLs/cookies** for private delivery
* **Field-level encryption** for sensitive headers; log delivery to S3 with lifecycle rules

***

### 📈 Monitoring & tools

* **CloudWatch**: `Requests`, `BytesDownloaded`, `4xx/5xx`, `CacheHitRate`
* **CloudFront reports**: popular objects, geos, user agents, origin metrics
* **Real-time logs**: near-instant request detail for analysis (deliver to Kinesis/Data Firehose)
* **Cost Explorer/CUR**: break down DTO by region tier, requests, Functions/Lambda\@Edge

***

### 🧪 Practical selection cheat-sheet

* **Mostly NA/EU traffic** → Start **Price Class 100**; expand only where latency proves it
* **Simple header/URL logic** → **CloudFront Functions**
* **Complex body/origin logic** → **Lambda\@Edge** (with guardrails)
* **Video/media** → Pair with **MediaPackage**/**Origin Shield**, tune segment caching
* **API behind ALB** → Use cache policies to vary on auth headers minimally; enable compression

***

### ✅ CloudFront FinOps Checklist

* [ ] Put CloudFront in front of **AWS origins** (S3/ALB/EC2) to eliminate origin→edge transfer charges.
* [ ] Start with the **narrowest Price Class** that meets latency SLOs (PC100 → PC200 → All only if data proves it).
* [ ] **Tight cache keys**: vary only on required headers/cookies/query params; use long TTLs for immutable assets.
* [ ] Turn on **Brotli/Gzip**; right-size images and static assets; consider WebP/AVIF where appropriate.
* [ ] Use **Origin Shield** to reduce miss fan-out and protect origins; pick the shield Region closest to the origin.
* [ ] Prefer **CloudFront Functions** for lightweight logic; use **Lambda\@Edge** only when you need body/network access.
* [ ] Ship **content-hashed filenames**; batch invalidations (first 1,000 paths/month are free); avoid wildcard nukes.
* [ ] **Geo-restrict** regions you don’t serve; layer **AWS WAF** for bots/abuse and rate limits on hot paths.
* [ ] Keep S3 private via **OAC/OAI**; protect sensitive headers with **field-level encryption**; use signed URLs/cookies.
* [ ] If spend is predictable, enroll in the **CloudFront Security Savings Bundle** (12-month commit; CDN savings + WAF credits).
* [ ] Dashboards: **CacheHitRate**, DTO by region tier, Requests, 4xx/5xx, invalidations, and edge compute invocations.
* [ ] **Monthly review**: adjust Price Class, TTLs, cache keys; audit bundle commit vs. actuals; prune unused behaviors.

***

### 🧠 AWS CloudFront Cost Optimization Challenges

CloudFront is “cheap” until request volume, DTO to expensive geos, invalidations, and edge compute sneak up on you. Here are the non-trivial traps teams hit—and fixes that actually move the needle.

***

**Q1: We used Price Class All by default. Are we overpaying?**

Many workloads don’t need every edge location. Serving from high-cost regions inflates DTO.

**✅ Solution**

* Start with **Price Class 100** (NA/EU) or **200**; expand only where latency data requires it.
* Track p95 latency and **CacheHitRate** by country/region before widening coverage.

***

**Q2: Our Data Transfer Out (DTO) is huge—and we’re unsure about origin egress.**

Viewer DTO is unavoidable, but origin→edge behavior differs by origin type.

**✅ Solution**

* Front **AWS origins** (S3/ALB/EC2) with CloudFront to eliminate origin→edge transfer.
* Compress (Brotli/Gzip), minimize payloads, and increase TTLs to reduce bytes delivered.
* If using **non-AWS origins**, model & monitor that origin’s egress cost explicitly.

***

**Q3: Deploys cause invalidation storms.**

Frequent invalidations add up after the monthly free tier and can degrade cache efficiency.

**✅ Solution**

* Use **content-hashed filenames** for static assets so you rarely invalidate.
* **Batch invalidations** and avoid `/*`. Keep under the free 1,000 paths/month when possible.

***

**Q4: Lambda\@Edge is getting expensive.**

Running heavy logic at the edge across all requests drives compute and duration costs.

**✅ Solution**

* Move simple logic (URL/header/cookie rewrites, A/B flags) to **CloudFront Functions**.
* Keep **Lambda\@Edge** only for use-cases needing body access, network calls, or complex transforms.
* Consolidate event hooks (e.g., viewer-request vs origin-response) to reduce invocations.

***

**Q5: Our Cache Hit Ratio (CHR) is stuck \~60%.**

Over-varying cache keys and short TTLs cause misses and extra origin load.

**✅ Solution**

* Tighten **cache keys**: vary only on required headers/cookies/query parameters.
* Use long TTLs for immutable assets; verify `Cache-Control` vs min/max TTLs.
* Add **Origin Shield** to reduce miss fan-out and improve hit locality.

***

**Q6: Real-time logs quietly added dollars.**

Per-line billing (plus streaming/processing) adds up if left on all the time.

**✅ Solution**

* Enable real-time logs only during **targeted debug windows** or with **sampling**.
* Use standard logs/metrics for day-to-day; add budgets/alerts on log volume.

***

**Q7: Our origin melts even with CloudFront in front.**

Low CHR, many behaviors, or globally distributed demand can overwhelm origins.

**✅ Solution**

* Enable **Origin Shield** and pick a shield Region close to your origin.
* Normalize cache keys; raise TTLs on cachable routes; validate ETags/conditional GETs.
* Re-examine behavior split (`/static/*` vs `/api/*`) to maximize caching.

***

**Q8: “Our API is personalized, so we can’t cache.” Any savings left?**

Treating APIs as fully uncacheable leaves DTO and request charges untouched.

**✅ Solution**

* Cache **fragments**: public endpoints, metadata, per-user blocks with short TTLs.
* Keep vary lists tight (e.g., a single auth header/cookie) to avoid cache explosion.
* Compress responses and minimize payloads to reduce DTO even on misses.

***

**Q9: We have predictable traffic—are we missing a bigger discount?**

Teams on steady spend often leave list-price money on the table.

**✅ Solution**

* Enroll in the **CloudFront Security Savings Bundle**: 12-month monthly commit for CDN savings, plus **WAF credits**.
* Commit at a level you **consistently** hit; avoid over-committing if traffic is volatile.
* Re-size the commit at renewal based on actuals.

***

**Q10: If we raise CHR, will CloudFront cost automatically drop?**

Higher CHR reduces **origin** load, but CloudFront still bills viewer DTO/requests.

**✅ Solution**

* Reduce **bytes delivered** (compression, image formats/sizing) and **expensive regions** (Price Class).
* Reduce **request counts** via longer TTLs and better caching on semi-static routes.
* Use **reports** to correlate hot paths with cost and adjust behaviors accordingly.

***

### 📚 Reference

* [CloudFront best practices with S3 origins](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html)
* [CloudFront pricing](https://aws.amazon.com/cloudfront/pricing/)
* [CloudFront free tier](https://aws.amazon.com/free/)
* [Security Savings Bundle overview](https://aws.amazon.com/about-aws/whats-new/2021/02/introducing-amazon-cloudfront-security-savings-bundle/)
* [Security Savings Bundle signup](https://repost.aws/articles/ARKhHkxOphQQO_vX4MQsPhwg/how-can-cloudfront-security-savings-bundle-save-up-to-30-on-your-amazon-cloudfront-costs)
* [Price Class guidance](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PriceClass.html)
* [Functions vs. Lambda@Edge developer docs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-functions-choosing.html)
* [CloudFront Functions docs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/cloudfront-functions.html)
* [“Interpret your CloudFront bill” guide](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/billing-and-usage-interpreting.html)
* [CloudFront billing and usage reports](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/reports-billing.html)

> *Features and pricing change; validate specifics for your Region in AWS pricing/docs before rollout.*
