Files
2026-11-02 15:53:54 +00:00

137 lines
6.1 KiB
Markdown

# CloudFront
## What is it?
[[_CloudFront|CloudFront]] is a CDN. It can be used for:
- Static & Dynamic content
- Video Streaming
- Web Sockets
### Benefits
- [[_CloudFront|CloudFront]] can be fronted with [[AWS WAF]] for OWASP's top 10 protection.
- [[_CloudFront|CloudFront]] can stream [[Videos On Demand]] using [[ISS Microsoft Smooth Streaming]]
### Core components
**Origin**: Location where all original files are located. Examples include: [[_S3|S3]], EC2, ELB, Route53.
**Edge Locations**: Compute located strategically close to end users.
**Regional Caches**: Compute located in board geographical locations to speed up requests for edge locations.
**Distribution**: A collection of Edge locations and Regional Cache that defines how cached content should behave.
## Running Code
### Stages where [[Lambda@Edge]] and [[CloudFront Functions]] can trigger
The order that the functions trigger within CloudFront is:
| Order | Stage | L@E | CF Fns | Description | Example Use Cases |
|--|---|---|---|---|--|
| 1 | Viewer Request | ✔️ | ✔️ | When CloudFront receives a request from the viewer. | Redirection (`HTTP` -> `HTTPS`), Cookie Inspection for Auth, Modify Headers for A/B Testing |
| 2 | Origin Request | ✔️ | ❌ | Before CloudFront forwards the request to the origin. | Add security headers (CSP/HSTS), set cookies for client side tracking, customise error messages |
| 3 | Origin Response | ✔️ | ❌ | After CloudFront receives the request from the origin. | Rewrite URLs for SEO or routing, inject headers for origin authentication, selective content serving based on user agent (desktop/mobile mode). |
| 4 | Viewer Response | ✔️ | ✔️ | Before CloudFront returns the response to the viewer. | Modify headers to control caching, update URLs in HTML for versioning, customise error responses from origin. |
```mermaid
sequenceDiagram
participant Viewer
participant Edge
participant Origin
Viewer->>Edge: Viewer Request
Edge->>Origin: Origin Request
Origin->>Edge: Origin Response
Edge->>Viewer: Viewer Response
```
### Difference between [[Lambda@Edge]] and [[CloudFront Functions]]
| | CF Fns | L@E |
|---|---|---|
| Programming Languages | JavaScript (ECMAScript 5.1) | Node.JS and Python |
| Event Sources | Viewer only | Viewer and Origin |
| Scale | +10,000,000 requests/s | 10,000 requests/s/Region |
| Function Duration | Submilisecond | Up to 5s (Viewer) / Up to 30s (Origin) |
| Max Memory | 2MB | 128MB-3,008MB |
| Max Bundle Size | 10KB | 1MB (Viewer) / 50MB (Origin) |
| Network, File System, and Request Body Access | ❌ | ✔️ |
| Access to geolocation | ✔️ | ❌ (Viewer request) / ✔️ (Origin request & response, Viewer response) |
| Can build/test entirely within CloudFront | ✔️ | ❌ |
| Functions logging and metrics | ✔️ | ✔️ |
| Pricing | Cheaper. Free tier available; charged pre request. | More expensive. Charged per request & function duration. |
## CloudFront Origin
It's the source where CloudFront will send requests.
### CloudFront Origin Groups
It allows you to group a **primary** and **secondary origin** together as a destination for requests to enable high availability and fault tolerance.
The **Primary Origin** is where **all** the requests will be sent.
The **Secondary Origin** is where the requests will be sent if the **Primary Origin** is **not available**. It will act like a **failover** origin.
The **failover** criteria is based on **HTTP Status Codes**: 400, 403, 404, 416, 500, 502, 503, 504.
CloudFront will failover on: `GET`, `HEAD`, and `OPTION` requests.
CloudFront will NOT failover on: `PUT`, `POST`, `PATCH`, and `DELETE`.
## CloudFront Caching Policy
### Cache Key
The **Cache Key** is a unique identifier for every object in the cache and determines whether a viewer request results in a cache hit.
A cache hit occurs when a viewer request generates the same **Cache Key** as a prior request and the object for that cache key is in the edge location's cache.
The more people hit the cache, the better the application performance will be.
### Cache Policy
A **Cache Policy** determines the **Cache Key**.
[[AWS]] has managed **Cache Policies** for use:
- `Amplify`
- `CachingDisabled`
- `CachingOptimized`
- `CachingOptimizedForUncompressedObjects`
- `Elemental-MediaPackage`
You can make your own **Caching Policy**:
- **TTL Settings**:
- **Minimum** / **Maximum** **TTL**: min / max time to hold the file in the cache.
- **Default TTL**: default time to hold a file in the cache.
- **Cache Key Settings**:
- **Headers**: which headers are a part of the **Cache Key**.
- **Cookies**: which cookies are a part of the **Cache Key**.
- **Query String**: which query string parameters are a part of the **Cache Key**.
- **Compression Support**: What compression format is part of the **Cache Key**.
### Origin Request
Happens when there is a cache miss and CloudFront must reach out to Origin to retrieve data.
**Origin Request** always returns:
- URL Path
- Request Body (if present)
- Specific HTTP Headers:
- Host
- User Agent
- `X-Amz-Cf-Id`
**Origin Request** doesn't include these by default:
- URL Query String
- Cookies
- All other HTTP Headers
**Cache Key** information (set by the **Cache Policy**) are automatically included in **Origin Requests**:
- URL Query Strings
- HTTP Headers
- Cookies
### Response Header Policy
Allows you to modify the HTTP Headers in the response that viewers will see.
[[AWS]] has managed policies for you to use and you can make your own also.
⚠️ If you are dealing with CORS, you will be setting things here, as this will mess with them.
## Origin Access Identity
**OAI** makes sure that an S3 bucket is only accessible through **CloudFront** and not the internet.
Lots of drawbacks. Not available anymore.
## Origin Access Control
Same as Origin Access Identity, makes sure that an [[_S3|S3]] bucket is only accessible through **CloudFront** and not the internet.
Overview:
* Enhanced sec.
* Comprehensive [[HTTP]] support.
* Supports uploading and downloading encrypted [[_S3|S3]] objects with SSE-KMS.
* Supports accessing [[_S3|S3]] in all [[AWS]] Regions.