Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 70 ยท Load balancing, scaling and delivery

CloudFront CDN

Learn Amazon CloudFront: distributions, origins, cache behaviors, TTLs, invalidations, Origin Access Control, signed URLs and edge functions, with an edge cache emulator.

A user in Sydney opening a website hosted in Frankfurt waits for every byte to cross the planet. A content delivery network (CDN) fixes that by keeping copies of your content in many places close to users. Amazon CloudFront is the AWS CDN: hundreds of edge locations around the world that answer requests from a cache when they can, and fetch from your servers (the origin) only when they must.

A CDN gives you three things at once: lower latency for users, less load on the origin (a cache hit never reaches it), and a protective layer in front of your application, with TLS, DDoS protection through AWS Shield, and AWS WAF filters. You will use it in front of S3 buckets, load balancers and API endpoints, and again in the static site project.

CloudFront runs inside AWS and cannot run on this site. CLI, JSON and function code are read-only. The Python examples are stand-ins: an edge cache emulator with a logical clock, and a toy signed-URL scheme. Real CloudFront uses a multi-layer cache, RSA signatures and many more options.

Distributions, origins and edge locations

You create a distribution, and AWS gives it a domain name like d1234abcd.cloudfront.net. You can attach your own domain (such as www.example.com) with a CNAME or a Route 53 alias record and an ACM certificate. For CloudFront, that certificate must be created in us-east-1 (N. Virginia), whatever the region of your origin.

A distribution has one or more origins:

  • an S3 bucket (for static files),
  • a custom origin: any HTTP server, such as an Application Load Balancer, an EC2 instance, an API Gateway endpoint or a server in your own data center,
  • special origins such as Lambda function URLs or MediaPackage for video.

You can also build an origin group with a primary and a secondary origin, so CloudFront retries the second one when the first returns configured error codes (a simple failover).

When a user requests a file, DNS sends them to a nearby edge location. The request flows through up to three layers:

flowchart LR
    U["User in Sydney"] --> E["Edge location"]
    E -- "hit: reply from cache" --> U
    E -- "miss" --> R["Regional edge cache"]
    R -- "miss" --> O["Origin<br/>S3 or ALB in Frankfurt"]
    O --> R
    R --> E

A cache hit at the edge is answered locally. A miss goes to a regional edge cache, and only then to the origin.

Cache behaviors

A cache behavior is a rule inside a distribution: a path pattern, an origin, and how to treat requests that match. Patterns are checked in order, with the default behavior (*) last. A typical site uses behaviors like these:

Path pattern Origin Notes
/assets/* S3 bucket Cache for a long time, files have hashed names
/api/* ALB Forward all methods, short or no caching
* (default) S3 bucket HTML pages, short TTL

Each behavior sets, among other things:

  • Viewer protocol policy: allow HTTP and HTTPS, redirect HTTP to HTTPS, or HTTPS only.
  • Allowed methods: GET and HEAD only, or also OPTIONS, or all methods (for APIs).
  • A cache policy: what makes up the cache key and the TTLs.
  • An origin request policy: which extra headers, cookies and query strings are forwarded to the origin without being part of the cache key.
  • A response headers policy: add security headers such as HSTS or CORS headers.

The cache key

Two requests share a cached object only when their cache keys are equal. The key always includes the URL path and the distribution's host, plus whatever the cache policy includes: chosen query strings, headers or cookies. Every extra value in the key splits the cache into more variants and lowers the hit ratio. If an API needs Authorization, include it in the key. If a page does not depend on cookies, do not include cookies. A common mistake is forwarding all query strings (or all cookies) "to be safe", which makes almost every request unique and the cache useless.

TTLs and invalidation

How long an object stays in the cache is controlled by the cache policy's minimum, default and maximum TTL, together with the headers the origin sends:

  • If the origin sends Cache-Control: max-age=... or s-maxage, CloudFront uses it, clamped between the minimum and maximum TTL.
  • If the origin sends nothing, the default TTL (24 hours unless you change it) applies.
  • Cache-Control: no-store or private stops caching unless the minimum TTL is above 0.

When a cached object expires, CloudFront does not simply throw it away: it asks the origin whether the object changed (a conditional request with If-None-Match or If-Modified-Since), and a 304 Not Modified response lets it keep serving the cached bytes.

What if you need a new version now, but the old one is cached for a day? You can create an invalidation, which removes matching objects from every edge location:

Terminal
aws cloudfront create-invalidation \
  --distribution-id E1ABCDEFGHIJKL \
  --paths "/index.html" "/blog/*"

The first 1,000 paths per month are free, and a wildcard path counts as one. Invalidation takes a minute or more to spread, and a better habit is versioned file names: app.3f9a1c.js is a new URL for every build, so nothing needs invalidating, and old and new pages never get mixed. Keep the unversioned entry point (index.html) on a short TTL or invalidate only that file.

The emulator below models one edge location with a logical clock (numbers instead of real time). It builds the cache key from the path and selected query strings, honors max-age from the origin, answers HIT, MISS or REFRESH, and supports wildcard invalidation.

Python An edge cache emulator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The utm_source query string is not in the cache key, so tracking parameters do not create copies. The lang query string is, so each language is cached separately. After the origin changes, the old logo.png is still served until the TTL ends or you invalidate it. That is why versioned names are easier to run.

Securing the origin and content

Origin Access Control

An S3 bucket serving a website should not be public. With Origin Access Control (OAC), CloudFront signs its requests to S3 with SigV4, and the bucket policy allows only the CloudFront service for your distribution:

JSON
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontRead",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::my-site-bucket/*",
      "Condition": {
        "StringEquals": {
          "AWS:SourceArn": "arn:aws:cloudfront::123456789012:distribution/E1ABCDEFGHIJKL"
        }
      }
    }
  ]
}

OAC replaces the older Origin Access Identity (OAI). The bucket can stay fully private with Block Public Access on, as described in S3 Security. For non-S3 origins, you can add a secret custom header that the origin checks, or restrict the load balancer's security group to CloudFront's managed prefix list.

Signed URLs and signed cookies

For private content such as paid videos or downloads, a behavior can require signed URLs (one file) or signed cookies (many files). Your application creates a URL with an expiry time (and optionally an IP range) and signs it with a private key. CloudFront holds the public key in a key group and rejects URLs that are expired or whose signature does not match.

Real CloudFront signatures use RSA. The stand-in below uses an HMAC (a shared secret) to show the same logic: sign the path and the expiry, check the signature, then check the clock.

Python A toy signed URL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Changing the path or the expiry breaks the signature, so a viewer cannot extend a link. The same hmac.compare_digest idea (compare in constant time) is good practice anywhere you check signatures.

Running code at the edge

Sometimes a cache is not enough: you want to rewrite a URL, check a header, redirect by country, or add security headers. CloudFront offers two ways:

CloudFront Functions Lambda@Edge
Runtime JavaScript, very small and fast Node.js or Python, full Lambda features
Runs at Edge locations, on viewer request and response Regional edge caches, on viewer and origin request and response
Typical duration Under a millisecond Up to seconds
Network and file access None Yes
Typical use URL rewrites, redirects, header edits, simple A/B and token checks Authentication calls, dynamic origin selection, image resizing

A CloudFront Function that serves /about from /about/index.html (read-only):

JavaScript
function handler(event) {
  var request = event.request;
  if (request.uri.endsWith("/")) {
    request.uri += "index.html";
  } else if (!request.uri.includes(".")) {
    request.uri += "/index.html";
  }
  return request;
}

Other settings you will meet: a default root object (index.html for /), custom error pages (map an S3 403 or 404 to /index.html for single-page apps), price classes (limit the edge locations used to lower cost), HTTP/2 and HTTP/3, automatic compression for gzip and Brotli, and standard logs or real-time logs for analysis. CloudFront also has a monthly free allowance of data transfer, and data from AWS origins to CloudFront is not charged as internet egress.

Edge compute compared, Global Accelerator and WAF

Lambda@Edge or CloudFront Functions?

The table above gives the headline. These are the details that decide a real choice (limits change, so confirm them in the current quotas page):

CloudFront Functions Lambda@Edge
Events Viewer request and viewer response only Viewer request and response, origin request and response
Typical runtime budget Well under 1 ms, a few KB of code, tiny memory Seconds (a few for viewer events, longer for origin events), much more memory and package size
Language A restricted JavaScript runtime Node.js or Python
Can call the network or read files No Yes (for origin events, and with limits for viewer events)
Can read or change the request body No Yes (can include the body when configured)
Where you create it In CloudFront In us-east-1, then replicated to edge regions
Price A small fee per million invocations, cheaper Per request plus duration, noticeably higher

Rules of thumb: if the work is "look at the URL, a header or a cookie and change it", use a CloudFront Function. If you must call another service (to validate a token with an identity provider, for instance), read the body, choose among several origins, or run heavy code such as image resizing, use Lambda@Edge. Both can be combined on different events of one distribution. A function that fails at the edge breaks every request, so test it with the CloudFront test tool and ship it behind a staging distribution first.

Python Which edge feature for this task?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Global Accelerator

AWS Global Accelerator improves the path to your application without caching anything. It gives you two static anycast IP addresses. Clients connect to the nearest AWS edge location, and traffic then travels over the AWS global backbone to your endpoints (Application or Network Load Balancers, EC2 instances or Elastic IPs) in one or more Regions. It performs health checks and fails over between endpoints or Regions in seconds, and a traffic dial and endpoint weights shift traffic for gradual releases or maintenance.

Choose between the two by the type of traffic:

CloudFront Global Accelerator
What it does Caches HTTP(S) content at the edge Routes any TCP or UDP traffic over the AWS network to the best healthy endpoint
Best for Websites, images, video, API acceleration with caching Games, VoIP, IoT, non-HTTP protocols, apps that need fixed IP addresses to allow-list, fast multi-Region failover
Caching Yes No
Client address Fixed set of DNS names, many IPs Two static IPs

They are not rivals. A common design puts CloudFront in front of cacheable pages and Global Accelerator in front of a dynamic or non-HTTP API.

WAF: web ACLs at the edge

AWS WAF filters HTTP requests against rules before they reach your application. You build a web ACL, a list of rules evaluated in priority order, and attach it to a CloudFront distribution, an Application Load Balancer, API Gateway or other supported resources. For CloudFront the web ACL is global and created in us-east-1. A rule can:

  • use an AWS managed rule group (common web exploits, SQL injection, known bad inputs, bot control, IP reputation lists), which AWS keeps updated,
  • match IP sets, countries, headers, URI paths, query strings or regular expressions,
  • be rate-based, blocking an IP that sends more than N requests in a five-minute window.

Each rule's action is Allow, Block, Count (record only), or a CAPTCHA or Challenge. Roll out a new rule in Count mode first, watch the logs for false positives, and then switch it to Block. A rate-based rule as JSON (read-only):

JSON
{
  "Name": "LimitPerIp",
  "Priority": 10,
  "Statement": { "RateBasedStatement": { "Limit": 1000, "AggregateKeyType": "IP" } },
  "Action": { "Block": {} },
  "VisibilityConfig": { "SampledRequestsEnabled": true, "CloudWatchMetricsEnabled": true, "MetricName": "LimitPerIp" }
}

WAF protects against application-layer attacks. For floods at the network layer, AWS Shield (Standard is automatic and free) protects CloudFront, Route 53 and Global Accelerator. See Secrets and Compliance for a hands-on model of ordered WAF rules, count mode and rate limiting.

Field-level encryption

HTTPS already protects data between the viewer and CloudFront, and between CloudFront and your origin. But once a request reaches your origin, every server on the path (the load balancer, the web tier, log files, queues) can read a credit card number in a form field. Field-level encryption narrows that exposure: CloudFront encrypts chosen form fields at the edge with a public key you provide, so only the one service that holds the private key can read them.

Setup has four parts:

  1. Upload a public key (RSA) to CloudFront and keep the private key in the service that needs the data.
  2. Create a field-level encryption profile that lists which form field names to encrypt with which key.
  3. Create a configuration that says which profile applies to which content type or query argument.
  4. Attach the configuration to a cache behavior that accepts POST requests. The viewer protocol policy must be HTTPS.

CloudFront then replaces the value of each listed field with ciphertext and forwards the request. Your web tier passes the opaque value along and stores it without being able to read it, and a payment service decrypts it with the private key. There is a limit of a small number of fields per request, and it is meant for a few very sensitive values, not for encrypting whole bodies.

The stand-in below uses textbook RSA with tiny numbers (p = 61, q = 53). This is not secure and exists only to show who can read what. A real setup uses 2048-bit RSA keys and CloudFront does the encryption for you.

Python Who can read an encrypted field?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Why use a CDN at all?

Before the details of caching, it helps to name what a content delivery network gives you. Latency drops because content comes from an edge location near the viewer. Your origin serves each object once per edge cache instead of once per visitor, which cuts load and bandwidth bills. The huge edge network absorbs traffic spikes and a share of DDoS attacks. And because edges terminate TLS close to users, secure connections also set up faster. Field-level encryption, signed URLs and AWS WAF (covered above) are the security features that sit at this same layer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens when an object is requested, is cached and still fresh at the edge location?

    A fresh cached object is a cache hit. The edge replies directly, which is both faster for the user and cheaper for the origin.
  2. 2. Why can forwarding all query strings and cookies in the cache key hurt?

    Every value in the cache key splits the cache into separate variants. Include only what changes the response.
  3. 3. How do you serve a private S3 bucket through CloudFront without making the bucket public?

    OAC makes CloudFront sign its requests, and the bucket policy allows only that distribution through the AWS:SourceArn condition.
  4. 4. Which statement about certificates for a CloudFront custom domain is correct?

    CloudFront is a global service and reads its ACM certificates from us-east-1, whatever the region of the origin.
  5. 5. You need a quick URL rewrite on every viewer request, in under a millisecond. Which feature fits best?

    CloudFront Functions are made for short, high-volume viewer-side tasks such as rewrites and header edits. Lambda@Edge is for heavier logic.

Summary

  • CloudFront caches content at edge locations, so most requests are answered close to the user and never reach your origin.
  • A distribution has origins (S3, load balancers, custom servers) and cache behaviors that pick an origin, methods, a cache key and TTLs by path pattern.
  • Keep the cache key small. Use versioned file names and short TTLs for entry pages so you rarely need invalidations, and remember that the first 1,000 invalidation paths per month are free.
  • Protect S3 origins with Origin Access Control, and private content with signed URLs or cookies.
  • Use CloudFront Functions for light edge logic and Lambda@Edge for heavier work. Certificates for custom domains live in us-east-1.

Next: Containers: ECR, ECS and Fargate