TExcelTAD
Home › AWS Cloud › Amazon CloudFront

Amazon CloudFront

Amazon CloudFront is AWS's content delivery network (CDN). It caches copies of your content at hundreds of edge locations around the world, so a user in Sydney downloads your images from Sydney instead of from your servers in Ireland. That means lower latency for users, less load (and data transfer) on your origin, and a layer of protection against attacks.

Concepts

Term Meaning
Distribution Your CloudFront configuration, reachable at d1234abcd.cloudfront.net or your own domain
Origin Where the original content lives: an S3 bucket, an ALB, an API, any HTTP server
Cache behavior Rules per path pattern (/images/*, /api/*): which origin, cache policy, allowed methods
Cache key What makes two requests "the same": path + selected headers, cookies, query strings
TTL How long an object stays cached (from Cache-Control headers or the cache policy)
Invalidation Force removal of cached objects before their TTL ends
Origin Access Control (OAC) Lets only CloudFront read a private S3 bucket

Creating and invalidating

bash
aws cloudfront create-distribution \
    --origin-domain-name tad-site.s3.eu-west-1.amazonaws.com \
    --default-root-object index.html
aws cloudfront create-invalidation --distribution-id E2QWRUHAPOMQZL --paths "/index.html" "/css/*"

Sample output of the invalidation:

text
{
    "Location": "https://cloudfront.amazonaws.com/2020-05-31/distribution/E2QWRUHAPOMQZL/invalidation/I2J0I21PCUYOIK",
    "Invalidation": {
        "Id": "I2J0I21PCUYOIK",
        "Status": "InProgress",
        "InvalidationBatch": {
            "Paths": {"Quantity": 2, "Items": ["/index.html", "/css/*"]},
            "CallerReference": "cli-1772446500-123456"
        }
    }
}

Tip: Instead of invalidating, use versioned file names (app.3f9a1c.js) with long TTLs. A new deployment references new names, and old cached files simply stop being requested.

Model: an edge cache

Each edge location keeps its own cache. The first request for an object at an edge is a miss (fetched from the origin); later ones are hits until the TTL expires:

python · try it yourself
class Edge:
    def __init__(self, name):
        self.name, self.cache = name, {}
    def get(self, path, now, ttl, origin_log):
        entry = self.cache.get(path)
        if entry and now < entry:
            return "Hit from cloudfront"
        origin_log.append((self.name, path))
        self.cache[path] = now + ttl
        return "Miss from cloudfront"

origin_requests = []
edges = {"SYD": Edge("SYD"), "FRA": Edge("FRA")}
requests = [(0, "SYD", "/logo.png"), (1, "SYD", "/logo.png"), (2, "FRA", "/logo.png"),
            (3, "FRA", "/logo.png"), (5, "SYD", "/logo.png"), (400, "SYD", "/logo.png")]

for now, edge, path in requests:
    status = edges[edge].get(path, now, ttl=300, origin_log=origin_requests)
    print(f"t={now:>3}s {edge} {path}  X-Cache: {status}")
hits = len(requests) - len(origin_requests)
print(f"cache hit ratio: {hits}/{len(requests)}, origin requests: {origin_requests}")
t=  0s SYD /logo.png  X-Cache: Miss from cloudfront
t=  1s SYD /logo.png  X-Cache: Hit from cloudfront
t=  2s FRA /logo.png  X-Cache: Miss from cloudfront
t=  3s FRA /logo.png  X-Cache: Hit from cloudfront
t=  5s SYD /logo.png  X-Cache: Hit from cloudfront
t=400s SYD /logo.png  X-Cache: Miss from cloudfront
cache hit ratio: 3/6, origin requests: [('SYD', '/logo.png'), ('FRA', '/logo.png'), ('SYD', '/logo.png')]

Model: the cache key matters

If the cache key includes values that don't change the response (say, a tracking query string), every variation becomes a separate cache entry and the hit ratio collapses:

python · try it yourself
from urllib.parse import urlsplit, parse_qsl, urlencode

requests = [
    "/products?id=7&utm_source=mail",
    "/products?id=7&utm_source=ads",
    "/products?utm_source=ads&id=7",
    "/products?id=7",
    "/products?id=8&utm_source=mail",
]

def cache_key(url, allowed_params):
    parts = urlsplit(url)
    params = sorted((k, v) for k, v in parse_qsl(parts.query) if allowed_params is None or k in allowed_params)
    return parts.path + ("?" + urlencode(params) if params else "")

for label, allowed in [("all query strings", None), ("only 'id'", {"id"})]:
    keys = [cache_key(u, allowed) for u in requests]
    distinct = len(set(keys))
    print(f"{label:<18}: {distinct} cache entries, {len(requests) - distinct} hits of {len(requests)}")
all query strings : 4 cache entries, 1 hits of 5
only 'id'         : 2 cache entries, 3 hits of 5

Keep the cache key as small as possible: include only the headers, cookies and query strings that really change the content. Use origin request policies to forward extra values to the origin without adding them to the key.

More features

  • HTTPS with free certificates from AWS Certificate Manager (the certificate must be in us-east-1 for CloudFront).
  • AWS WAF and Shield integration at the edge.
  • CloudFront Functions (lightweight JavaScript) and Lambda@Edge to rewrite requests and responses.
  • Signed URLs / signed cookies for private content.
  • Origin failover with origin groups.

Test yourself

What is a CloudFront origin?

  1. An edge location
  2. The source of the original content, such as an S3 bucket or ALB
  3. A DNS record
  4. A cache policy

Why can including all query strings in the cache key hurt performance?

  1. It breaks HTTPS
  2. Irrelevant variations create separate cache entries and lower the hit ratio
  3. Query strings are not supported
  4. It increases TTL

How can you make an S3 bucket readable ONLY through CloudFront?

  1. Enable versioning
  2. Use Origin Access Control and a bucket policy for CloudFront
  3. Make the bucket public
  4. Use Transfer Acceleration