Lesson 4 of 4 Amazon CloudFront

Running Code at the Edge with CloudFront Functions and Lambda@Edge

This lesson explains how CloudFront runs code close to users to inspect and change requests and responses, and how its two options, CloudFront Functions and Lambda@Edge, differ in capability, speed and cost.

Learning outcomes

After completing this lesson, you will be able to:

  • Choose between CloudFront Functions and Lambda@Edge for a task.
  • Describe the four events at which an edge function can run and what each can change.
  • Describe how edge functions are published and associated with a cache behaviour.

CloudFront Functions vs Lambda@Edge

CloudFront Functions and Lambda@Edge both run code at edge locations, but they are designed for different amounts of work.

CloudFront Functions are small JavaScript functions that run in every edge location, in the same place as the cache. They start in under a millisecond and may use only about a millisecond of compute, which makes them cheap enough to run on every request at very high volume. They can read and change the URL, headers, cookies and query string of viewer requests and responses, but they cannot call other services over the network or read the request body. They suit lightweight tasks such as URL rewrites, redirects, adding headers and checking a simple token.

Lambda@Edge functions are Lambda functions, written in Node.js or Python, that CloudFront replicates to its regional edge caches. They can run for up to 5 seconds on viewer events and 30 seconds on origin events, make network calls, read the request body and use larger packages, and they can run on origin events as well as viewer events. They cost more per request and add more latency, so they suit work that CloudFront Functions cannot do, such as validating a token against a database or resizing images. The following table summarises the differences.

CloudFront Functions
Runs atEvery edge location
LanguageJavaScript
Start-up and run timeUnder a millisecond; at most about 1 ms of compute
EventsViewer request and viewer response only
Network and body accessNo network calls; no request body
Best forHigh-volume header changes, URL rewrites, redirects and simple token checks
CostLower
Lambda@Edge
Runs atRegional edge caches
LanguageNode.js or Python
Start-up and run timeMilliseconds; up to 5 s (viewer events) or 30 s (origin events)
EventsViewer and origin request and response
Network and body accessNetwork calls and request body allowed
Best forHeavier logic, network calls, larger packages
CostHigher
Sort into groups

Which edge function?

Exam skills 4.3.4

Choose between CloudFront Functions and Lambda@Edge.

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

The four events

A request through CloudFront passes four points at which an edge function can run, and the choice of point decides how often the function runs and what it can change.

The viewer request event runs when CloudFront receives a request, before it checks the cache, so it runs for every request, including cache hits. It is the place for redirects, URL rewrites that change which object is fetched, and authorisation checks that must apply even to cached content. The origin request event runs only on a cache miss, just before CloudFront forwards the request to the origin, so it can choose a different origin or add headers that the origin needs without running for cached requests.

The origin response event runs when the origin's response arrives, before CloudFront caches it, so any change it makes, such as resizing an image or adding a header, is cached and served to later viewers without running again. The viewer response event runs just before CloudFront returns a response to the viewer, for every response, including cache hits, which suits adding headers or cookies that must be present on every response. CloudFront Functions support only the two viewer events. The following table summarises the four events.

EventRunsTypical use
Viewer requestOn every request, before the cache is checkedRedirects, URL rewrites, authorisation checks
Origin requestOnly on a cache miss, before calling the originChoosing an origin, adding headers for the origin
Origin responseOnly on a cache miss, after the origin respondsChanging the response before it is cached, such as resizing an image
Viewer responseOn every response, before it is returnedAdding security headers or cookies

The following diagram shows where the four events occur on the path of a request and its response.

The four CloudFront events. Viewer request runs for every request before the cache is checked, origin request only on a cache miss, origin response before the response is cached, and viewer response for every response. CloudFront Functions support only the two viewer events; Lambda@Edge supports all four.
Events on the viewer side run for every request; events on the origin side run only when the origin is contacted.
Put in order

The four edge events

Exam skills 4.3.4

Put the four CloudFront events in the order a cache miss passes them.

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

Writing and deploying edge functions

Example. Add security headers with a CloudFront Function:

function handler(event) {
  var response = event.response;
  var headers = response.headers;
  headers['strict-transport-security'] = { value: 'max-age=63072000; includeSubDomains; preload' };
  headers['x-content-type-options'] = { value: 'nosniff' };
  headers['x-frame-options'] = { value: 'DENY' };
  return response;
}

The example above adds security headers to responses. The following list describes how edge functions are tested and deployed.

  • CloudFront Functions are tested in the console or with TestFunction, then published and associated with a cache behaviour; CloudFront KeyValueStore supplies data such as redirect maps without redeploying.
  • Lambda@Edge functions must be created in us-east-1, associated by a numbered version (not $LATEST or an alias), and their logs appear in CloudWatch Logs in the Region nearest to where they ran.
  • Lambda@Edge functions cannot use environment variables, layers or VPC access.
Worked example

Choosing an edge function

CloudFront Functions and Lambda@Edge suit different tasks. The following table identifies the appropriate choice for several tasks and the reason in each case.

TaskChoiceWhy
Add security headers to every responseCloudFront FunctionsLightweight, sub-millisecond, cheapest
Redirect old URLs to new onesCloudFront FunctionsSimple request rewriting
Validate a JWT and check user permissions in a databaseLambda@EdgeNeeds network calls and more time
Resize images at the edgeLambda@Edge (origin response)Heavier processing and binary bodies

CloudFront Functions run at every edge location for viewer events only and cannot make network calls; Lambda@Edge runs in Regional edge caches, can call other services, and costs more per request.

Check yourself

Which edge function type can run on origin request and origin response events?

Show answer

Lambda@Edge. CloudFront Functions run only on viewer request and viewer response events.

Exam Tips

Remember for the exam

  • A simple header rewrite at the edge suits CloudFront Functions; heavier logic or network calls need Lambda@Edge.
  • Code that must run only on cache misses belongs on an origin request or origin response event, which requires Lambda@Edge.
  • Lambda@Edge functions are created in us-east-1 and associated by numbered version.
  • CloudFront Functions cannot make network calls or read the request body.