Lesson 1 of 3 Amazon CloudFront and AWS Global Accelerator

Building CloudFront Distributions and Controlling Caching

This lesson explains how CloudFront, AWS's content delivery network, reduces latency, lowers origin load and cost, and adds security at the edge.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe origins, cache behaviours and edge locations.
  • Explain how cache policies and TTLs control caching.
  • Explain how CloudFront accelerates dynamic content and uploads.
  • Choose between CloudFront Functions and Lambda@Edge.

How a distribution is built

A CloudFront distribution is built from three parts. Origins are where the content comes from: an S3 bucket, an Application Load Balancer, EC2 instances, API Gateway, AWS Elemental MediaPackage or any HTTP server. Cache behaviours map URL path patterns, such as /images/* or /api/*, to origins, and each behaviour has its own cache, origin request and response policies, so static images can be cached for days while API responses are not cached at all.

Edge locations around the world serve users and cache responses. Between them and the origins, Regional edge caches hold content that has dropped out of the smaller edge caches, which further reduces the requests that reach the origin.

The following diagram shows a request passing the two cache layers to one of two origins.

How a CloudFront distribution is built. Users are served by the nearest edge location, which caches responses. Regional edge caches hold content that has dropped out of the smaller edge caches. Cache behaviours map path patterns to origins with their own policies, such as caching /images/* from an S3 bucket for days and sending /api/* to an Application Load Balancer without caching.
Only a miss in both cache layers reaches an origin, and only the behaviour that matches the path decides which origin.

Controlling the cache

CloudFront serves a response from its cache only if a later request produces the same cache key. A cache policy decides which headers, cookies and query strings are part of the key, and the minimum, default and maximum TTLs. Every value added to the key creates more variants of each object, so the key should contain only values that change the response, keeping the hit ratio high. An origin request policy forwards extra values that the origin needs, such as a header for logging, without adding them to the key.

Invalidations remove objects from the cache before their TTL expires, for example after an urgent fix. They are charged beyond a monthly allowance, so versioned file names, such as app.v42.js, are the cheaper way to publish new content. Origin Shield adds a central caching layer between the edge locations and the origin, so a cache miss at many edge locations results in a single request to the origin, which protects it from load. The following table summarises these features.

FeaturePurpose
Cache policyTTLs and the headers, cookies and query strings in the cache key: keep it small for a high hit ratio
Origin request policyForward values to the origin without adding them to the cache key
InvalidationsRemove content early (versioned file names are cheaper)
Origin ShieldA central caching layer protecting origins

Monitor the hit ratio, error rates and origin latency; standard and real-time logs record each request. A low hit ratio usually means a bloated cache key or short TTLs.

Match the pairs

CloudFront cache controls

Exam skills 4.4.4 · 3.4.1

Match each requirement with the CloudFront feature that meets it.

Log in to try this activity Interactive activities are free with an account.

Beyond static caching

CloudFront does more than cache static files. It also accelerates dynamic content and uploads that cannot be cached, because requests enter the AWS network at the nearest edge location and travel to the origin over the AWS backbone on persistent, optimised connections, rather than across the public internet.

Origin groups provide availability: when the primary origin returns specified error codes or cannot be reached, CloudFront retries the request against a secondary origin, for example an S3 bucket in another Region. Price classes reduce cost by limiting the distribution to edge locations in cheaper regions of the world, at the expense of higher latency for users elsewhere.

True or false

Beyond caching

Exam skills 4.4.4 · 2.2.2

Check what CloudFront does beyond caching static files.

Log in to try this activity Interactive activities are free with an account.

Code at the edge

CloudFront can run code at the edge to change requests and responses, with two options of different weight. CloudFront Functions run lightweight JavaScript in every edge location, in under a millisecond, on viewer requests and responses only. They cannot make network calls, but they are cheap enough to run on every request, so they suit high-volume tasks such as rewriting URLs, redirecting, adding security headers or normalising the cache key.

Lambda@Edge functions, written in Node.js or Python, run in regional edge caches, can run for longer, can make network calls and can also run on origin requests and responses, which happen only on cache misses. They suit heavier logic, such as authenticating a user against an external service or resizing an image before it is cached. The following table summarises the differences.

CloudFront Functions
RuntimeLightweight JavaScript, < 1 ms
EventsViewer request and response
Network callsNo
Use forHeader changes, URL rewrites, redirects at scale
Lambda@Edge
RuntimeNode.js or Python, longer
EventsViewer and origin events
Network callsYes
Use forHeavier logic

The following diagram shows the four points where code can run and which option can use each.

Where CloudFront code runs. CloudFront Functions run on viewer requests and responses only, in every edge location, in under a millisecond and without network calls. Lambda@Edge can also run on origin requests and responses, which happen only on cache misses, and can make network calls and run for longer.
Origin-facing events run only on cache misses, so logic placed there runs far less often than viewer-facing logic.
Sort into groups

CloudFront Functions or Lambda@Edge?

Exam skills 4.4.4 · 2.1.5

Choose the edge code option for each task.

Log in to try this activity Interactive activities are free with an account.
Worked example

One distribution, two origins

A web application serves static assets from S3 and its API from an ALB. Users worldwide complain of slow page loads.

Path patternOriginCache behaviour
/static/*S3 bucket (with OAC)Cache for a long time; versioned file names
/api/*ALBDo not cache (or cache briefly); forward the Authorization header
Default /*S3 (the single-page app's index.html)Short TTL so new releases appear quickly

Static files are now served from edge locations near users, and API requests travel over the AWS network from the nearest edge, which is faster than the public internet. Origin load falls because most requests are cache hits.

Check yourself

What decides whether CloudFront can serve a cached copy of a response?

Show answer

The cache key set by the cache policy: the URL plus any headers, cookies and query strings the policy includes. Fewer values in the key mean a higher cache hit ratio.

Exam Tips

Remember for the exam

  • When global users experience slow static content, use CloudFront.
  • For origin failover and high availability, use a CloudFront origin group.
  • For simple header rewrites or redirects at scale use CloudFront Functions; for heavier logic use Lambda@Edge.
  • To improve the cache hit ratio, minimise the headers, cookies and query strings in the cache key.
  • When the origin needs a header but caching should ignore it, use an origin request policy.