Skip to content

Lesson 14 of 30Modern AWS

CloudFront and Route 53

Serve a site from the edge with CloudFront, lock S3 origins with OAC, and point domains at AWS with Route 53 records and routing policies.

15 min read0/4 questions

Before a user's request reaches anything in your VPC, two services have usually touched it: Route 53 turned your domain name into an IP address, and CloudFront answered from a server a few miles away instead of an ocean away. Together they decide how fast your site feels, how much of your traffic your servers even see, and how you fail over when a Region goes down.

CloudFront: a CDN at the edge

Amazon CloudFront is AWS's CDN (content delivery network). It runs in hundreds of edge locations (from Cloud Basics) and caches your responses close to users. A request in Sydney for your logo is answered from Sydney, not from us-east-1, cutting the round trip from about 200 ms to about 10 ms.

A CloudFront distribution has:

  • Origins: where content really lives. An S3 bucket, an ALB, API Gateway, any HTTPS server.
  • Cache behaviors: rules by path pattern that pick an origin and how to cache. /static/* cached for a year, /api/* not cached at all.
  • A domain like d111111abcdef8.cloudfront.net, plus your own aliases (www.example.com) with an ACM certificate from us-east-1.
A cache hit, a cache miss, and the origins behind them
Edge location (Sydney)Region us-east-1Ada: SydneyAdaSydneySam: SydneySamSydneyCloudFront: edge cacheCloudFrontedge cacheS3 bucket: private, OACS3 bucketprivate, OACALB: /api/*ALB/api/*APIAPIGET /logo.svgGET /logo.svgmiss/api/*

Ada requests /logo.svg. Route 53 has sent her to the nearest edge location.

1/5

How long things stay cached

The edge keeps a copy for its TTL (time to live). What decides the TTL is a cache policy (CloudFront's settings, including min, default and max TTL) together with the origin's Cache-Control header. The cache policy also defines the cache key: which parts of the request (path, chosen query strings, headers, cookies) make two requests "the same". Keep the key small. Adding every cookie to the key means almost no request is ever a hit.

Pythonedge_cache.py
cache = {} # key -> (body, expires_at)origin_calls = 0 def origin(path): global origin_calls origin_calls += 1 return f"<contents of {path}>" def get(path, now, ttl=60): hit = cache.get(path) if hit and hit[1] > now: return "HIT " cache[path] = (origin(path), now + ttl) return "MISS" for t, path in [(0, "/logo.svg"), (5, "/logo.svg"), (30, "/app.js"), (59, "/logo.svg"), (61, "/logo.svg")]: print(f"t={t:>2}s {get(path, t)} {path}")print("origin calls:", origin_calls)
Output
Press Run (⌘ Enter) to see what happens.

Five requests, three origin calls. On a real site with millions of users, a good hit ratio (often 90%+ for static assets) means your origin handles a small fraction of the traffic.

Versioned file names are the trick that lets you cache forever. Build tools emit app.3f9a1c.js; when the code changes, the name changes. Cache those with Cache-Control: public, max-age=31536000, immutable, and keep index.html on a short TTL so it can point at new file names quickly.

Invalidations

If you must remove something from every edge before its TTL ends, create an invalidation:

aws cloudfront create-invalidation --distribution-id E2ABCDEF123 --paths "/index.html" "/blog/*"

The first 1,000 invalidation paths a month are free, then they cost money (each wildcard counts as one path). Invalidations take a little time to reach every edge. Treat them as the exception; versioned file names are the rule.

Quick check
You deploy a new frontend to S3. Some users still get the old JavaScript for hours. Your files are named app.js and cached for 24 hours. What is the best long-term fix?
Need a nudge? A hint rules out a wrong answer.

Origin Access Control: keep the bucket private

For an S3 origin, you want users to reach files only through CloudFront (so you get HTTPS, caching, WAF and logs) and never by hitting the bucket directly. Origin Access Control (OAC) does this: CloudFront signs its requests to S3, and the bucket policy allows only that distribution. Block Public Access stays on.

bucket policy for OAC
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::acme-site-prod/*",
      "Condition": {
        "StringEquals": { "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E2ABCDEF123" }
      }
    }
  ]
}

OAC replaced the older Origin Access Identity (OAI); use OAC for new distributions. (S3's "static website hosting" endpoint is a different, public, HTTP-only thing. With OAC you use the bucket's normal REST endpoint and set a default root object like index.html.)

Quick check
You want a React app in S3 served over HTTPS on www.example.com, with the bucket not publicly readable. What do you set up?
Need a nudge? A hint rules out a wrong answer.

Route 53: DNS on AWS

Amazon Route 53 is AWS's DNS service (named after port 53, DNS's port). You buy or transfer a domain, and its records live in a hosted zone:

  • A public hosted zone answers DNS queries from the internet for example.com.
  • A private hosted zone answers only inside VPCs you associate with it, for internal names like db.internal.

A hosted zone costs about $0.50 a month (example price) plus a small per-query fee.

RecordMaps a name toExample
AAn IPv4 addressapi.example.com → 203.0.113.10
AAAAAn IPv6 addressapi.example.com → 2001:db8::10
CNAMEAnother name (not allowed at the zone apex)blog.example.com → example.ghost.io
MXMail serversexample.com → 10 mail.example.com
TXTText, for verification and email policy"v=spf1 include:_spf.example.net ~all"
NSThe name servers for the zonens-123.awsdns-45.com
Alias (Route 53 only)An AWS resource: CloudFront, ALB, API Gateway, S3 websiteexample.com → d111111abcdef8.cloudfront.net

Alias records are Route 53's extension and the one to use for AWS targets. Unlike a CNAME, an alias works at the zone apex (example.com itself, not just www.), Route 53 resolves it to the target's current IPs, and queries to alias targets are free.

Match the pairs0/4 matched

Which record type?

Choose an item, then its match on the other side.

Routing policies

Route 53 can answer the same name differently depending on where and how healthy things are:

  • Simple: one answer.
  • Weighted: split traffic by weight, like 90/10 for a canary release.
  • Latency-based: answer with the Region that is fastest for this user.
  • Failover: answer with the primary while its health check passes, else the secondary.
  • Geolocation / geoproximity: answer by the user's country or distance (data residency, localized sites).
Pythonrouting.py
import random records = [ {"region": "us-east-1", "weight": 90, "healthy": True}, {"region": "eu-west-1", "weight": 10, "healthy": True},] def weighted(records, rng): live = [r for r in records if r["healthy"]] pick = rng.uniform(0, sum(r["weight"] for r in live)) for r in live: pick -= r["weight"] if pick <= 0: return r["region"] return live[-1]["region"] rng = random.Random(7)answers = [weighted(records, rng) for _ in range(1000)]print("healthy:", {r: answers.count(r) for r in ("us-east-1", "eu-west-1")}) records[0]["healthy"] = False # health check failsanswers = [weighted(records, rng) for _ in range(1000)]print("us-east-1 down:", {r: answers.count(r) for r in ("us-east-1", "eu-west-1")})
Output
Press Run (⌘ Enter) to see what happens.

Health checks combine with any policy: an unhealthy record is skipped. That is how a multi-Region failover works: Route 53 notices the primary's health check failing and starts answering with the secondary.

One catch: DNS answers are cached by resolvers for the record's TTL (alias records use the target's TTL, often 60 seconds). Failover is never instant, so keep TTLs short on records you may need to move.

Quick check
You want to send 5% of users to a new version running behind a second ALB, then ramp up. Which routing policy?
Need a nudge? A hint rules out a wrong answer.
Key terms
distribution
A CloudFront configuration: origins, cache behaviors, domains and a certificate.
cache behavior
A path pattern rule in CloudFront that picks an origin and caching settings.
invalidation
Forces edges to drop cached paths before their TTL. Use rarely; prefer hashed file names.
Origin Access Control
Lets only your CloudFront distribution read a private S3 bucket.
alias record
A Route 53 record pointing at an AWS resource. Works at the zone apex, unlike CNAME.
hosted zone
The container for a domain's DNS records in Route 53, public or private.