
When Do These Functions Run?
It is crucial to understand that CloudFront functions and Lambda@Edge functions are designed for different scenarios. Here’s when each type executes:-
CloudFront Functions run:
- Immediately when a viewer sends a request to an edge location.
- Just before CloudFront returns a response to the viewer.
-
Lambda@Edge Functions run:
- When CloudFront receives a request from a viewer.
- When CloudFront forwards a request to the origin, especially for content not cached at the edge.
- When a response is received from the origin, before delivering it back to the viewer.

Use Cases and Choosing the Right Service
CloudFront Functions
CloudFront functions are perfect for lightweight, short-running tasks. Common use cases include:- Cache Key Normalization: Transform HTTP request attributes to create an optimal cache key, which improves the cache hit ratio.
- Header Manipulation: Insert, modify, or delete HTTP headers in requests or responses. For instance, you might add a header with the true client IP.
- URL Redirects or Rewrites: Redirect viewers based on request details or rewrite URLs. This allows for dynamic request management.
- Request Authorization: Inspect authorization headers or metadata to validate tokens like JSON Web Tokens (JWT).

For extremely short execution times (sub-millisecond), choose CloudFront functions to take full advantage of their speed and efficiency.
Lambda@Edge Functions
Lambda@Edge functions are ideal for scenarios that require extended execution times or additional capabilities, such as:- Running operations that take several milliseconds or more.
- Handling tasks with adjustable CPU and memory configurations.
- Integrating with other AWS services using third-party libraries like the AWS SDK.
- Performing functions that depend on network access to external services.
- Accessing the request body or file system when needed.

For logic that requires network access, integration with external systems, or longer running times, Lambda@Edge is the recommended service.
Summary
Both Lambda@Edge and CloudFront functions allow you to run code as close to your users as possible at the edge. They provide flexible options for manipulating requests and responses in Amazon CloudFront:- CloudFront Functions: Best for lightweight tasks such as header manipulation, URL redirects/rewrites, and authorization on sub-millisecond executions.
- Lambda@Edge Functions: Suitable for operations requiring extended execution times, network or file system access, and deeper integrations with other AWS services.
