Lambda@Edge

On this page 7

Lambda@Edge is an Amazon Web Services feature that runs AWS Lambda functions inside the Amazon CloudFront network, so that code can inspect, modify or answer HTTP requests and responses close to the end user instead of in a single AWS Region. In serverless computing within the cloud, it extends the function as a service model to the content delivery layer: developers write a function, attach it to a CloudFront distribution and let AWS replicate and execute it at regional edge locations worldwide.

The feature suits lightweight request processing such as header manipulation, URL rewriting, authentication checks, A/B testing and origin selection. It is not a general-purpose compute platform: strict limits on memory, duration, package size and supported runtime features shape what a Lambda@Edge function can reasonably do.

How Lambda@Edge hooks into CloudFront

Lambda@Edge works by binding a published function version to one of four CloudFront events in a cache behavior. Each event marks a point in the life of a request, and the choice of event determines how often the function runs and what it can change.

The function is authored in the US East (N. Virginia) Region, us-east-1, and CloudFront copies it to its regional edge caches. When a request arrives, CloudFront invokes the replica nearest to the viewer and passes an event object describing the request or response. The function returns a modified object, or it generates a response directly without contacting the origin.

The following table summarizes the four trigger points and their practical effect on invocation frequency.

EventWhen it firesTypical use
Viewer requestOn every request, before the cache lookupAuthentication, redirects, header normalization
Origin requestOnly on a cache miss, before forwarding to the originOrigin selection, URL rewriting, signing requests
Origin responseAfter the origin answers, before cachingAdding cache headers, image transformation
Viewer responseOn every response, before it reaches the viewerSecurity headers, cookies, final tweaks
CloudFront events that can trigger a Lambda@Edge function

Because viewer triggers run on every request and origin triggers run only on cache misses, moving logic to the origin side often reduces both cost and latency when the result is cacheable.

Limits and runtime constraints

Lambda@Edge imposes tighter quotas than regional AWS Lambda, and the quotas differ between viewer and origin events. Viewer events are designed for fast, small operations, while origin events allow heavier processing because they run less frequently.

ParameterViewer eventsOrigin events
Maximum memory128 MBSame range as regional Lambda
Maximum timeout5 seconds30 seconds
Compressed package size1 MB50 MB
Generated response bodyAbout 40 KBAbout 1 MB
Network accessAllowedAllowed
Main quotas for viewer and origin triggers

Several regional Lambda features are not available at the edge. Functions cannot use environment variables, Lambda layers, VPC attachment, container images, provisioned concurrency or dead-letter queues, and supported runtimes are limited to Node.js and Python on the x86_64 architecture. Configuration therefore usually lives in the code bundle itself or is fetched from a service at runtime, with caching inside the execution environment.

A Lambda@Edge association must reference a numbered function version, never the $LATEST alias. Every code change requires publishing a new version and updating the distribution, which triggers a global deployment that typically takes several minutes.

Lambda@Edge compared with neighboring options

Lambda@Edge occupies a middle position between CloudFront Functions and regional Lambda. CloudFront Functions are a lighter, cheaper JavaScript runtime that executes at every CloudFront point of presence, while regional AWS Lambda offers the full feature set but runs far from many users. Edge platforms from other providers, such as Cloudflare Workers, follow a similar idea with a different isolation model.

CharacteristicCloudFront FunctionsLambda@EdgeRegional AWS Lambda
Execution locationAll edge locationsRegional edge cachesOne AWS Region
Supported eventsViewer events onlyViewer and origin eventsMany AWS event sources
Typical durationSub-millisecondMilliseconds to secondsUp to 15 minutes
Network callsNot allowedAllowedAllowed
Request body accessNoYes, with size limitsYes
Comparison of AWS options for request processing

A practical rule is to start with CloudFront Functions for simple header and URL logic, choose Lambda@Edge when network calls, body access or origin events are needed, and keep complex business logic in regional services behind the origin.

Choosing the right trigger for a task

Selecting the trigger is the most important design decision in a Lambda@Edge deployment, because it controls cost, cache efficiency and correctness. A function that alters the cache key at the wrong stage can fragment the cache or serve the wrong content to users.

TaskRecommended triggerReason
Validate a JSON Web TokenViewer requestMust block unauthorized requests before cache hits
Route to a regional originOrigin requestRuns only on misses and can change the origin
Resize or convert imagesOrigin responseResult is cached and reused for later viewers
Add security headersViewer response or origin responseOrigin response caches the headers with the object
Assign an A/B test groupViewer requestEach viewer needs a consistent variant
Decision guide for common edge tasks

When a function changes headers, cookies or query strings that influence the response, the cache policy must include them in the cache key, or CloudFront may return a cached variant meant for a different user.

Operational pitfalls and common mistakes

Most Lambda@Edge problems stem from its distributed execution model. Logs, permissions and deletion all behave differently from regional Lambda, and teams that treat the function as a normal regional deployment are often surprised.

  • Logs appear in many Regions. CloudWatch log groups are created in the Region nearest each execution, so troubleshooting requires checking several Regions rather than only us-east-1.
  • The execution role needs two trust principals. Both lambda.amazonaws.com and edgelambda.amazonaws.com must be allowed to assume the role.
  • Replicas delay deletion. A function cannot be deleted until it is removed from all distributions and CloudFront has cleaned up the replicas, which can take hours.
  • Cold starts add latency. Infrequently used edge locations may start new execution environments, so heavy initialization code directly harms response times.
  • Errors become user-facing. An exception or timeout in a viewer trigger results in an HTTP 5xx response, so defensive coding and fallbacks are essential.

Cost deserves attention as well: Lambda@Edge charges a higher per-request price than regional Lambda plus duration in GB-seconds, so a viewer trigger on a high-traffic site can become expensive when CloudFront Functions or origin triggers would suffice.

In plain words

Lambda@Edge lets a website run small pieces of code at locations spread around the world instead of in one central data center. When someone opens a page, the request passes through a nearby point of the Amazon delivery network, and the code can check, change or answer that request on the spot.

Think of it as a receptionist stationed in every branch office. Instead of sending every visitor to headquarters, the receptionist checks badges, points people to the right room and hands out common brochures directly. The key takeaway is that Lambda@Edge makes websites faster and smarter by handling simple decisions close to the visitor.

A real-world example

A media company serves a news site to readers in Europe, North America and Asia from an Amazon S3 bucket and an application origin in one Region. Premium articles must be visible only to subscribers, and the team wants to avoid a round trip to the central application for every page view.

The engineers attach a Node.js function to the viewer request event that validates a signed JSON Web Token stored in a cookie, using a public key bundled with the code. Requests without a valid token for premium paths receive a redirect to the subscription page generated directly at the edge. A second function on the origin response event adds security headers that CloudFront then caches with each object.

After rollout, unauthorized requests never reach the origin, and authentication latency falls to a few milliseconds for most readers. The team monitors CloudWatch logs across several Regions and keeps the token check deliberately small to stay well within the 5-second viewer limit.