Lambda@ Edge

Learn via video courses
Topics Covered

Overview

Lambda@Edge can execute the code closer to the users of the application and is also an advanced feature of AWS CloudFront that enables it to offer improved performance and lower latency. You don't have to worry bout the hassle of handling and provisioning the infrastructure across various locations around the globe. Also, as far as the pricing structure is concerned, you only incur costs for the compute time that is consumed.

What are Lambda@Edge Functions?

With Lambda@Edge, a feature of Amazon CloudFront, you can execute the code closer to your users for the application, which improves the performance and reduces latency. You don't have to worry bout the hassle of handling and provisioning the infrastructure across various locations around the globe. Also, as far as the pricing structure is concerned, you only incur costs for the compute time that is consumed. No additional costs are incurred or no charges are applied while the code is resting and not executing.

Distribution of the applications across the world becomes easier with the implementation of the Lambda@Edge which not only improves the performance of that application abuts also offers a seamless experience for the users using it all at no server administration. All the code written is executed once Lambda@Edge receives the triggers from the AWS CloudFront content delivery network (CDN). You can simply upload the code to the AWS Lambda which executed it and takes care of all the necessary execution dependencies as well as scales the code offering high availability at all the AWS locations closest to the end user.

Listed below are a few of the following AWS Lambda features that are not supported by the Lambda@Edge functions:

  • AWS Lambda layers along with the Lambda functions.
  • Lambda environment variables.
  • More than 512 MB of ephemeral storage for the Lambda functions is not supported.
  • Implementing the AWS X-Ray.
  • Use of the arm64 architecture in the Lambda functions.
  • Dead letter queues are available in the Lambda function.
  • Runtime that is allowed is Node.js 12. x, Node.js 14.x, Python 3.7, Python 3.8, Python 3.9.
  • To access the resources inside the VPC, the configuration for the same is not supported for the Lambda function.
  • Reserved along with provisioned concurrency in Lambda.

Lambda@Edge Example Functions

Listed below are a few of the Lambda@Edge example functions:

General Examples

Case Statement- A/B testing: It can be utilized for testing two different versions of an image without the need to create any redirects or modify the URL.

Illustrate how the utilization for testing two different versions of an image without the need to create any redirects or modifying the URL

Generating Responses - Examples

Case Statement: Serving static content -

Illustrate how the Lambda function can be implemented for serving the static website content, which helps to reduce the load onto the origin server which eventually reduces the overall latency.

Working with Query Strings - Examples

Case Statement: Redirecting the unauthenticated users to a sign-in page -

Illustrate how redirecting the users to a specific sign-in page when they haven't entered their credentials.

Customise the Content by Country or Device Type Headers - Examples

Case Statement: Serving multiple versions of an object depending upon the device -

Illustrate how the Lambda function can be implemented for how the multiple versions of an object can be served depending upon the type of device being utilized by the users.

Content-Based Dynamic Origin Selection Examples

Case Statement: Utilising an origin request event for changing from an AWS S3 origin to a custom origin -

Updating Error Statuses Examples

Case Statement: Utilising an origin response event for updating the status error status to 302 -

Accessing the Request Body Examples

Case Statement: Utilising a request event to update an HTML form -

Illustrate how the body of a POST request( generated by an HTML form ) could be modified.

For more detail, visit lambda-examples

Get Started Creating and Using Lambda@Edge Functions

A lot of scenarios can be handled very easily and smoothly by implementing Lambda@Edge functions. We shall learn in this section of the article how Lambda@Edge works in conjugation with AWS CloudFront.

Creating and using the Lambda functions with AWS CloudFront:

  • From the AWS Lambda console, start by creating a Lambda function say for the US East (N. Virginia) Region. These steps can also be implemented programmatically via AWS SDKs.
  • You can now save and publish, numbered versions, of the Lambda function.
  • You can also modify the Lambda function, by editing the $LATEST version in the function. Once you modify it, always first publish it with a new numbered version before setting it up to work with AWS CloudFront.
  • You need to now select the AWS CloudFront distribution and the cache behavior applicable to the Lambda function. Now, define one or more CloudFront triggers that might enable the execution of the Lambda function. This can be something like creating an event so that the execution of the Lambda function happens when the AWS CloudFront receives a request from its viewer.
  • These events or triggers once created are replicated around the globe for the AWS location by the Lambda as seen in the diagram below. Get started creating and using Lambda Edge functions

Using AWS Lambda with CloudFront Lambda@Edge

With AWS CloudFront Lambda@Edge, you can execute either Node.js or even Python Lambda functions for customizing your content which gets delivered via AWS CloudFront. This way the functions get executed close to the viewer in the AWS locations. These Lambda@Edge functions execute in response to the AWS CloudFront triggers, without you carrying the hassle of provisioning or managing any servers. With the Lambda functions, you could also implement them to modify the CloudFront requests as well as responses.

Scenarios, when the CloudFront events occur when you have implemented and execute the Lambda functions, are listed as follows:

  • Viewer's request: When a request from a viewer is received by the CloudFront.
  • Origin's request: Before the AWS CloudFront forwards a request to the origin.
  • Origin's response: When a request from the origin is received by CloudFront.
  • Viewer response: Before the AWS CloudFront returns a response to the viewer.

The below diagram explains how you could use the AWS Lambda with AWS Cloudfront Lambda@Edge: how you could use the AWS Lambda with AWS CloudFront Lambda Edge

Creating a Lambda@Edge Function in the Lambda Console

We shall now see a step-by-step tutorial following which you could get started with creating a Lambda@Edge function in the AWS Lambda console for running Lambda functions based on the AWS CloudFront triggers:

Creation of the CloudFront Lambda@Edge function:

  • Login to the AWS Management Console, and open the AWS Lambda console via the link AWS Lambda.

  • You will find a Create function option if there is already one or more Lambda functions.

  • For those getting started for the first time, you can simply create one function. clicking on Get Started Now.

  • For regions you can select the US East (N. Virginia) from the Region list.

  • You can start creating the function via either your customized piece of code or leverage the CloudFront blueprint for creating the function.

  • While working on creating a function via your customized piece of code, you will have to select the Author from scratch option.

  • For checking out the various Cloufront blueprints available to choose a form for the creation of your function, you need to type CloudFront in the filter field, and then select Enter.

  • You then select the AWS CloudFront blueprint according to your needs and select the name of the blueprint.

  • You shall then see a Basic information section where you need to specify the below-given values:

    • Name - Enter a name for your function.
    • Role - Select Create new role from the Cloudfront template(s). You can either choose a customized role or create your existing role.
    • Role name - Enter a name for the role.
    • Policy templates - Select Basic Edge Lambda permissions.
  • Now if you select a blueprint as explained in the above steps, then the CloudFront section will also let you create one trigger, that would be linked to the function with a cache at the AWS CloudFront distribution as well as a CloudFront trigger. Well, It's recommended to select the Remove button, so that no trigger is created for the function at the time of the function's creation. You can always add the triggers later on.

Quick Note: You might be wondering why have we asked to add triggers later. To answer that, it's always best to do the first test as well as debug the function before adding the events. Also, the function starts its execution as soon as the trigger is added, where it shall also finish the replication to the AWS locations around the globe along with the deployment in the corresponding distribution.

  • Select the create function option. With Lambda you can create two versions of the function that are, LATESTalongwithVersion1.YoucanonlymodifytheLATEST along with Version` 1`. You can only modify the LATEST version, whereas the console shall display Version 1 initially.
  • For editing the function, you can select Version 1, under the ARN for the function. On the Versions tab, select the $LATEST. It's important to note, that if you left the function and returned to it, the button shall show a Qualifiers label.
  • You can then select the applicable Code entry type from the Configuration tab, from where you can follow the prompts to modify or upload the piece of code.
  • For execution at the Runtime, select the value depending upon the function's code.
  • You can easily apply the applicable tags from the Tags section. You can also select the Actions option form where you can select the Publish new version.
  • You now need to write down the description for the new version of the function. After high, you can publish it via the Publish button.
  • It's always recommended to Test and debug the lambda * function.
  • Once everything is tested well, and the execution of the function is correct for the CloudFront events, you can publish another version and can edit the function to add more events according to your requirements.

Customizing at the Edge with Lambda@Edge

An extension of AWS lambda is the Lambda@Edge service which offers to smoothly execute functions that help to customize content which enables delivery for CloudFront. Automatic scaling is possible with Lambda@Edge which ranges between a few requests per day to thousands per second. You get the capability to work with Node.js or Python in one Region and start executing these functions across all the global AWS locations which are closer to the users (achieving great user experience) without handling the hassle of provisioning or managing any physical servers.

You can implement the Lambda@Edge function with a CloudFront distribution which then shall intercept requests as well as responses occurring at the AWS CloudFront edge locations. Scenario, when the CloudFront events occur when you have implemented and execute the Lambda functions, are listed as follows:

  • Viewer's request: When a request from a viewer is received by the CloudFront.
  • Origin's request: Before the AWS CloudFront forwards a request to the origin.
  • Origin's response: When a request from the origin is received by CloudFront.
  • Viewer response: Before the AWS CloudFront returns a response to the viewer.

Uses for Lambda@Edge processing?

  • Before the AWS CloudFront forwards the request to the origin, the Lambda function inspects the header or authorization tokens and inserts this header for controlling access to the content.
  • With the Lambda function, cookies are inspected and rewritten as URLs to validate the different versions of a site for the A/B testing.
  • You can generate HTTP responses with the Lambda function when the AWS CloudFront viewer request or origin request events take place.
  • With a Lambda function the network calls can be routed to the external resources for confirming the user credentials or fetching the additional content for customizing the response.

Lambda@Edge benefits

Listed below are the benefits that one can unleash by implementing the Lambda@Edge with their architecture:

Customization of the content at the edge: The content delivered through CloudFront CDN can be simply customized according to the requirements via Lambda@Edge. You get the ability to choose the computing resources offered, hence the customizing execution time, all depending upon the application's performance requirements.

Managed Computing: With Lambda@Edge, scaling and executing your code can also be automated for AWS locations around the globe without handling the hassle of deploying as well as managing the origin servers in various AWS locations. Also, setting up the load balancing or the Domain Name System (DNS) routing services comes easily. Adding new functionality without disturbing or modifying the existing code and causing any trouble to the existing applications running on the origin server. The implementation of both Lambda@Edge and CloudFront offers less origin infrastructure which needs to be managed as compared to the traditional CDN.

Less latency for applications and websites: Executing the code across the AWS edge locations around the globe is easier with Lambda@Edge. As with Lambda@Edge, this code run is much closer to the viewer, enabling you to deliver full-featured customized content at low latency and high performance.

Lambda@Edge Pricing

As studied so far, with Lambda@Edge you can execute the code closer to the users of the application, and is also an advanced feature of AWS CloudFront that enables it to offer improved performance and lower latency. With that being said, it is important to understand the pricing structure offered by Lambda@Edge which will help us to make better decisions keeping costs in mind.

  • You incur costs for the total number of requests spreading across your entire set of functions.
  • Each time a request starts to execute as a response to the AWS Amazon CloudFront trigger occurring globally, Lambda@Edge counts it in.
  • The time from which the code has started o executed is the duration until the code has returned an output or terminates.
  • The pricing for the request is, for 1 million requests $0.60 is the cost incurred, ($0.0000006 per request).
  • For each GB-second utilized, you get charged $0.00005001.

A simple example to understand all the points mentioned above would be if 128MB of memory available per execution is allocated to the Lambda@Edge function, the duration cost that is incurred is $0.00000625125 for each 128MB-second utilized, which is metered at 1ms granularity.

Below you shall find the pricing structure of the AWS Lambda@Edge:

Region: US East (Ohio)
Price
Requests$0.60 per 1M requests
Duration$'0.00005001 for every GB second

Conclusion

  • The content delivered through CloudFront CDN can be simply customized according to the requirements via Lambda@Edge. You get the ability to choose the computing resources offered, hence the customizing execution time, all depending upon the application's performance requirements.
  • The pricing for the request is, for 1 million requests $0.60 is the cost incurred, ($0.0000006 per request). For each GB-second utilized, you get charged $0.00005001.
  • As with Lambda@Edge, this code run is much closer to the viewer, enabling you to deliver full-featured customized content at low latency and high performance.
  • Lambda@Edge you can execute the code closer to the users of the application and is also an advanced feature of AWS CloudFront that enables it to offer improved performance and lower latency.
  • You don't have to worry bout the hassle of handling and provisioning the infrastructure across various locations around the globe. Also, as far as the pricing structure is concerned, you only incur costs for the compute time that is consumed.