AlgoViz

Amazon CloudFront

medium 25 min

CloudFront is the content delivery network of AWS.

Video lesson · Chapter 1 of 5

The release file travels from Dublin to Tokyo

0:00 / 3:53

CloudFront in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Amazon CloudFront is the content delivery network of AWS. You describe what to deliver in a distribution: the servers that hold the content, called origins, and rules called cache behaviors that say which URL goes to which origin and how long copies may be kept.

When someone requests a URL, DNS leads them to an edge location that can serve them well. If the edge has a copy, it answers. If not, the request goes to a larger regional cache, perhaps to one last shared cache called Origin Shield, and only then to the origin.

Why it exists

The distance between a person and your server costs time on every request, and popular files cost your server the same work again and again. Copies near people fix both. The general ideas are on the CDN page; here we look at how this product does it.

Teams on AWS choose it because it fits the rest: private S3 buckets, load balancers, certificates, the AWS firewall, and no transfer charge between AWS origins and CloudFront.

A short history

  1. 18 November 2008

    CloudFront opens in beta, as a way to deliver files stored in S3.

  2. July 2017

    Lambda@Edge becomes generally available: Node.js functions run on four events of a request.

  3. May 2021

    CloudFront Functions arrives, with light JavaScript that runs at the edge locations themselves.

  4. August 2022

    HTTP/3 becomes available for viewers.

  5. November 2025

    Flat-rate plans appear beside pay-as-you-go, including a free plan.

Words to know

Distribution
One CloudFront configuration with its own domain name.
Origin
Where the content comes from: S3, a load balancer, or any HTTP server.
Cache behavior
Rules for one path pattern: origin, methods, policies, functions.
Edge location, or PoP
The place that talks to the viewer.
Regional edge cache
A larger cache between edge locations and origins.
Origin Shield
One extra cache layer, in one Region, that all other caches go through.
Cache policy
The TTL limits and the parts of the cache key.
OAC
Origin access control: CloudFront signs its requests so a bucket can stay private.

How it works

Step through the idea, or press Play.

Step 1 of 3

DNS picks an edge location. Usually the nearest in latency

Understand it

Start here

Fruit carts and barns

Fruit is sold from small carts on every corner. A cart holds only what people on that corner like. Behind the carts is a regional barn with more, and far away are the farms. Nobody walks to the farm for an apple.

From cart to farm
Apples are on the cart

Each step back is slower and has more choice. A good cart answers most people.

Why

What it is for

  • Global speed

    AWS lists more than 750 PoPs in over 100 cities, 15 regional edge caches and over 1,140 embedded PoPs inside internet providers.

  • Security at the edge

    Shield Standard against DDoS, AWS WAF, geographic restriction, signed URLs.

  • Edge compute

    CloudFront Functions for small work, Lambda@Edge for larger work.

  • Cost control

    No transfer charge from AWS origins to CloudFront. Price classes, Origin Shield and flat-rate plans.

  • Fits AWS

    S3, load balancers, API Gateway, media services, Route 53, ACM certificates, IAM.

  • Visibility

    Access logs, real-time logs, CloudWatch metrics and the X-Cache header.

It carries static files, whole sites, API calls, video segments, large downloads and WebSocket or gRPC connections. Requests that cannot be cached still gain: TLS ends nearby, connections to the origin are reused, and long distances are crossed on the AWS network.

Path

Three cache layers before the origin

Edge, regional cache, Origin Shield, origins

Users in Europe and the United States reach two edge locations inside the CloudFront boundary. Each edge asks its own regional edge cache on a miss. Both regional caches ask one Origin Shield, which fetches from your origins outside CloudFront: an S3 bucket and a load balancer.
Every arrow to the right is a miss. Origin Shield is optional.
  1. 1

    Resolve the name

    DNS returns the address of an edge location that can serve this viewer, typically the nearest in latency. This is the normal mode; fixed anycast addresses exist as a special option for allow lists.

  2. 2

    TLS

    The edge uses your certificate, which must be in ACM in us-east-1. Viewers may use HTTP/1.1, HTTP/2 or HTTP/3 and TLS up to 1.3.

  3. 3

    WAF and viewer functions

    AWS WAF rules decide first. Then a viewer-request function may rewrite, redirect or refuse.

  4. 4

    Match a behavior

    Path patterns are checked in order; the first match wins. The default behavior * is last.

  5. 5

    Edge cache

    The cache policy builds the key. A fresh copy is returned.

  6. 6

    Regional edge cache

    Larger, so less popular objects stay longer. Uncacheable and write requests skip it.

  7. 7

    Origin Shield

    If enabled, all layers fetch through one Region, so one request per object reaches the origin.

  8. 8

    Origin, then back

    The response is stored in each layer and compressed if allowed. Origin-response and viewer-response functions may change it.

A request that misses twice

If the bucket is in the same Region as the regional cache, the edge asks S3 directly.

What reaches the origin

Ro=R (1−he)(1−hr)(1−hs)100,000×0.15×0.5×0.4=3,000 per secondR_o = R\,(1-h_e)(1-h_r)(1-h_s) \qquad 100{,}000 \times 0.15 \times 0.5 \times 0.4 = 3{,}000 \text{ per second}
Example ratios for edge, regional cache and shield. Without the shield the origin would see 7,500.

Rules

Behaviors: one URL space, many origins

A typical distribution

OrderPatternOriginCaching
0/api/*Load balancerCachingDisabled, all methods
1/media/*S3 bucketSigned URLs, one day
2/static/*S3 bucketCachingOptimized, versioned names
Last* (default)Load balancerShort TTL for HTML
If /static/* came after a broader pattern, it would never be used.

Which rule, which cache?

Each behavior chooses the origin or origin group, allowed methods, viewer protocol, cache policy, what is forwarded to the origin, compression, signing and functions. The cache policy controls the key; an origin request policy may forward more to the origin without splitting the cache.

Cache

Keys and TTLs

By default the key is the distribution's domain and the path. Add a header, cookie or query string only if the response truly depends on it. Adding User-Agent creates thousands of versions of the same file.

How long, and with what key?

TTL rules

CaseResult
No cache header, common policyDefault TTL, 24 hours in CachingOptimized
max-age or s-maxage from the originUsed, kept between the minimum and maximum TTL
no-store or private, minimum TTL 0Not cached
no-store, minimum TTL above 0Cached anyway for the minimum TTL
Error response10 seconds by default (error caching minimum TTL)
stale-while-revalidate, stale-if-errorOld copy may be served meanwhile
The fourth row surprises people. Keep the minimum TTL at 0 for anything personal. See cache TTL.

Shield

When Origin Shield pays

Turn it on

  • Viewers in many regions
  • Origins that work hard per request, such as packaging or image resizing
  • Little origin capacity, or a second CDN in front of the same origin
  • After deployments, when many misses arrive together

Skip it

  • Content that cannot be cached
  • Viewers in one region near the origin
  • gRPC: those requests bypass it
  • When the extra charge is more than the origin work saved

Choose the AWS Region with the lowest latency to the origin; for an origin in AWS that is its own Region, or the nearest one offered. A full miss pays one hop more.

Change

Getting new content out

MethodHowKnow this
Versioned file namemain.3f9a.jsWorks in browsers too, no charge, easy rollback
Invalidate paths/images/*First 1,000 paths a month are free; a wildcard counts as one path
Invalidate by tag#product:42Needs CacheTagConfig and a tag header from the origin
Short TTLmax-age=30Simple; costs hits
An invalidation reaches edge and regional caches, not browsers. Do not build on a fixed completion time. More in CDN invalidation.

Code

Two kinds of edge functions

Where functions sit on the way in

A viewer request enters the CloudFront boundary and meets a viewer-request function, then the cache. On a miss the request meets an origin-request function and leaves for your origin.
Responses pass origin-response and viewer-response functions on the way back.

CloudFront Functions and Lambda@Edge

CloudFront FunctionsLambda@Edge
Runs onViewer request and responseAll four events
LanguageJavaScriptNode.js, Python
TimeUnder a millisecondUp to 30 seconds
Memory2 MB128 MB viewer events; up to 10 GB origin events
Code size10 KB50 MB compressed
NetworkOne call per run, to an origin of the same distribution, 1 secondAny destination
Request body, filesNoYes
Built-in dataKeyValueStoreNone
Deployed fromCloudFrontA numbered version in us-east-1
Origin events run only on misses. Viewer events run on every request, also on hits.
JavaScript
function handler(event) {  var request = event.request;  if (request.uri.endsWith("/")) {    request.uri += "index.html";  } else if (!request.uri.split("/").pop().includes(".")) {    request.uri += "/index.html";  }  return request;}
CloudFront Function: serve index.html for folders

Failure

Origin failover

Origin group

An origin group has a primary and a secondary. You choose the status codes that mean failure: 403, 404, 429, 500, 502, 503, 504. Failover applies to GET, HEAD and OPTIONS only, per request, with no health checks in between. A POST is never repeated for you.

How long before it gives up on connecting

T=a×tc3×10 s=30 stuned: 1×2 s=2 sT = a \times t_c \qquad 3 \times 10\text{ s} = 30\text{ s} \qquad \text{tuned: } 1 \times 2\text{ s} = 2\text{ s}
aa is connection attempts, 1 to 3, and tct_c the connection timeout, 1 to 10 seconds. The defaults make a reader wait 30 seconds for the secondary. The response timeout is a separate setting, 1 to 120 seconds.

Security

Private content and private origins

LayerStopsNote
Shield StandardNetwork floodsIncluded. Shield Advanced is a paid service with a response team
AWS WAFInjection, bad bots, high ratesRuns before the cache
Geographic restrictionWhole countriesAllow list or block list
Signed URLLinks without permissionOne file; has an end time
Signed cookiesThe same, for many filesStreaming, whole folders; URLs stay unchanged
OACReading the bucket directlyReplaces OAI; supports SSE-KMS and all Regions
TLS policyOld protocolsMinimum version per distribution
Signing uses RSA 2048 or ECDSA 256 key pairs in trusted key groups. OAC also works with some origins other than S3, such as Lambda function URLs.

The gates in order

Run

Operate it: metrics, errors, cost

Read the signs

SignUsual causeDo
Miss from cloudfront, alwaysKey too wide, TTL 0, cookies in keyTrim the cache policy
403 from S3Bucket policy or OAC, or a missing key without list permissionCheck the policy for this distribution
502TLS or name problem with the originCertificate and host name
504Origin slow or blockedFirewall, timeout, slow work
Old contentLong TTL or browser copyVersioned names
Certificate not offeredIt is in another RegionRequest it in us-east-1

Quotas and promises: the service level agreement is 99.9% a month, with credits below that. Cost depends on data out, requests, region, functions, invalidations and shield, or on a flat-rate plan without overage charges. Model the mix before you decide; check the pricing page for today's numbers.

HTTP/3 is a setting on the distribution, with no code change. QUIC avoids head-of-line blocking between streams, resumes quickly and survives a change of network; browsers fall back when UDP is blocked. Details: HTTP/2 and HTTP/3.

Decide

When to choose it

Choose it when

  • Origins are in AWS
  • Static sites, images, downloads from S3
  • APIs and pages with short TTLs
  • HLS or DASH video
  • Private content with signatures
  • WAF, Shield and IAM are already yours
  • Small edge logic without servers

Think again when

  • Everything is personal and uncacheable
  • All users sit beside the origin
  • You want no dependence on AWS
  • You need purges worldwide in fractions of a second
  • Even an edge hit is too slow
  • The team wants a simpler bill than usage pricing (or look at the flat-rate plans)

Compared with others

NetworkClosest inDiffers inChoose it for
CloudflareCache, WAF, edge code, HTTP/3Anycast routing; purge under 150 ms median; not tied to one cloudOrigins anywhere, quick start
FastlyCache, edge code, logsVCL configuration, fast purgeFine control of caching
AkamaiReach, securityMore sites, enterprise salesVery large media
Google Cloud CDNCache, anycastPart of Google's load balancerOrigins in Google Cloud
Azure Front DoorCache, WAF, routingMicrosoft's successor to Azure CDN classic, which retires on 30 September 2027Origins in Azure
The theory of choosing is in CDN design.
YAML
Resources:  Oac:    Type: AWS::CloudFront::OriginAccessControl    Properties:      OriginAccessControlConfig:        Name: site-oac        OriginAccessControlOriginType: s3        SigningBehavior: always        SigningProtocol: sigv4  Distribution:    Type: AWS::CloudFront::Distribution    Properties:      DistributionConfig:        Enabled: true        HttpVersion: http2and3        DefaultRootObject: index.html        Origins:          - Id: site            DomainName: !GetAtt Bucket.RegionalDomainName            OriginAccessControlId: !GetAtt Oac.Id            S3OriginConfig:              OriginAccessIdentity: ""   # empty: OAC is used instead        DefaultCacheBehavior:          TargetOriginId: site          ViewerProtocolPolicy: redirect-to-https          Compress: true          CachePolicyId: 658327ea-f89d-4fab-a63d-7e88639e58f6  # CachingOptimized
CloudFormation: private bucket with OAC

Summary

The whole topic in one minute.

A distribution routes URL patterns to origins. Requests fall through edge, regional cache and optional Origin Shield, and each layer answers when it can. Cache key and TTL decide the hit ratio; versioned file names make most invalidations unnecessary.

CloudFront Functions do small work on every request, Lambda@Edge does larger work. Origin groups retry a failed read on a second origin, OAC keeps buckets private and signed URLs keep content private. Choose it when the origins are in AWS.

  • A distribution holds origins and ordered behaviors; first match wins.
  • Edge, regional cache, Origin Shield: each layer removes misses.
  • Keep cache keys small and the minimum TTL at 0 for personal data.
  • Version names first, invalidate by path or tag second.
  • Functions for small work on every request, Lambda@Edge for larger work.
  • Origin groups repeat reads only; shorten the connection timeout.
  • OAC for private buckets, signed URLs or cookies for private content.

Sources