# Cloud Front

## Icon

![CloudFront Icon](https://icon.icepanel.io/AWS/svg/Networking-Content-Delivery/CloudFront.svg)

## Basics

* Its a content delivery network global service _(CDN)_, that speeds up distribution of your static and dynamic web content, such as `.html`, `.css`, `.js`, and image files to your users which delivers your content through a worldwide network of data centers called edge locations.
* When a user requests content that you're serving with CloudFront, the request is routed to the edge location that provides the lowest latency (time delay), so that content is delivered with the best possible performance.
  * If the content is already in the edge location with the lowest latency, CloudFront delivers it immediately.
  * If the content is not in that edge location, CloudFront retrieves it from an origin that you've defined—such as an Amazon S3 bucket, a MediaPackage channel, or an HTTP server (for example, a web server) that you have identified as the source for the definitive version of your content.
* CloudFront speeds up the distribution of your content by routing each user request through the AWS backbone network to the edge location that can best serve your content.
* Content is cached at edge location from where users of application can retrieve the content on request.
* There are more than 600 POP and all details of POP can be found [here](https://aws.amazon.com/cloudfront/features/?whats-new-cloudfront.sort-by=item.additionalFields.postDateTime\&whats-new-cloudfront.sort-order=desc#Global_Edge_Network).
* They also provide integration with shield and WAF which provides DDos protection.
* They can have different types of origin _(real server whose resources need to be distributed)_ like,
  * S3 bucket
    * Provides enhanced security with CloudFront Origin Access Control _(OAC, older version is OAI)_
  * Custom Origin _(HTTP)_
    * Application loadbalancer
    * S3 Website
    * EC2 instance
    * Any HTTP backend

## Working

![CloudFront Working](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-efa87cc0b86bd453c0b7037cf7e7a1ec8ed1722e%2FCloudFront_Working.png?alt=media) ![S3 as Origin](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-b3a0f7a292d0e0e22277b5811cd03ee01bb23c0b%2FCloudFrontAndS3.png?alt=media)

## Caching

* Each edge location have a cache associated with it and contents are cached here after first request based on **caching policy** created.
* Cache hit ratio needs to be maximized to reduce the request to origin.
* The cached contents are retrieved using cache keys. Cache key is created as follows,
  * By default it is a combination of hostname and resource name
    * Sample would be `www.org.com/path/resource`.
  * You can enhance cache key with `cookie`, `HTTP headers`, `query string` using CloudFront cache policies.
    * Cached based on `HTTP headers`.
      * With option to include `None` or whitelist specific headers.
    * `Cookies`
      * With option to include `None` or whitelist specific cookies, `include-all-except` or `ALL`
    * `Query String`
      * Same inclusion option as cookies.
* `TTL`,
  * Can be controlled using cache policy by the origin.
  * `Cache-Control` header, `Expires` header helps to control these value and contents can be cached upto 1 year.
* Header, cookies and query string included in cache key are automatically forwarded to origin server.
* Best performance is when NO headers/query-string/cookies are included in cache key.
* AWS also provides Predefined Managed policies, but user can also create their own policy.
* **Origin Request Policy** allows to configure what values need not be included in forming the cache key but need to be forwarded to Origin.
  * It allows to add custom HTTP headers not part of viewer request so that request can be forwarded with details required for Origin.

## Cache Invalidation

* Cache is normally invalidated only when TTL expires.
* One can invalidate all or some files partially by performing cache refresh through **CloudFront Invalidation**.

## Cloud Front IPS

* The list of cloud front IPs can be found [here](https://d7uri8nf7uskq.cloudfront.net/tools/list-cloudfront-ips), which must be provided with access to your Load balancer so that it can forward the request to the HTTP backend.

## Geo Restriction

* CloudFront provides following lists to block or allow user request based on their country of origin,
  * Allow List
  * Block List
* They use a third party tool to get the geo IP database to get the location of the user.

## Signed URL and Cookies

* These can be used to distribute content to premium users around the world by creating URL or cookies that allow access to content.
* When a signed url or cookie is created a policy should be attached. The policy includes,
  * URL expiration
  * IP ranges which can access this data
  * Trusted signers _(which AWS account can create signed URLs)_.

### Pre Signed URL

* URL can be used to share single file with expiration date.
* Can be managed only by root user.
* Can filter by IP, path, expiration date.

### Pre Signed cookies

* If you wanna share multiple files one can use Pre-Signed cookies.

### Signers

* There are two ways of signing URL and cookies.
  * **Key group** : Can use IAM for API security and can leverage APIs to create and rotate key in cloud front distribution.
    * Public RSA key reside in cloud front KeyGroup.
    * Private RSA key reside at EC2 instances.
  * **CloudFront Key Pair** : This is old method and need root account to manage the key pair. Not recommended.

## Origin Groups

* This allows failover as we can have a primary and a secondary origin to increase the availability of the service.

## Field level encryption

* Can use encryption at edge location using asymmetric encryption to encrypt sensitive fields.

## Real time Logs

* Can use these to monitor, analyze and take actions based on content delivery performance.
* Data from CF is passed to kinses stream, which can the pass the details out to other services like Lambda etc.

## Pricing

* There are 3 price classes offered by AWS.
  * **Price Class ALL**
    * Included all regions and offers best performance
  * **Price Class 200**
    * Most regions, but excludes most expensive regions.
  * **Price Class 100**
    * Only least expensive regions.
