What is Lambda@Edge?
Lambda@Edge is an AWS service that allows you to run Lambda functions at AWS Edge locations globally. It is designed to customize the behavior of CloudFront distributions, enabling low-latency execution of code closer to users.
Key Features of Lambda@Edge
- Global Execution: Executes code at AWS edge locations near the user for low latency.
- Event-Driven: Integrates with CloudFront events (viewer requests, origin requests, viewer responses, origin responses).
- No Servers to Manage: Fully serverless; AWS manages scaling and infrastructure.
- Supports Multiple Use Cases:
- Header modification
- Dynamic request/response customization
- URL redirection and rewriting
- Authentication and authorization
- Data compression and caching optimization
Integration Points
Lambda@Edge integrates directly with CloudFront events:
- Viewer Request: Triggered when the client makes a request to CloudFront.
- Origin Request: Triggered before CloudFront forwards a request to the origin server.
- Origin Response: Triggered after receiving a response from the origin server.
- Viewer Response: Triggered just before CloudFront returns the response to the client.
Best Practices
- Use Lightweight Functions:
- Keep functions small and optimized for quick execution to reduce latency.
- Avoid Long-Running Tasks:
- Perform heavy computations or database queries outside Lambda@Edge.
- Securely Handle Sensitive Data:
- Ensure sensitive data is encrypted and managed securely.
Example Scenarios
- Dynamic Content Localization:
- Use the
Viewer Request trigger to detect the user's country via headers and serve region-specific content.
- Header-Based Caching:
- Add or modify headers in
Origin Request or Viewer Response to improve cacheability.