Case study

CategoryArticles

What is Lamdba@Edge and How is it Different from AWS Lambda?

In this article, you will learn:

Data traffic on the modern Internet is growing rapidly. To keep up with this growth, website and application owners have turned to CDNs (Content Delivery Networks) like Amazon CloudFront to cache web content on geographically dispersed servers located at edge locations around the world. End users can expect faster load times and less load on the origin server. But what if you need to bring the code and its computing closer to your user? This is where Lambda@Edge can help.

In this blog post, we’ll introduce Lambda@Edge functions, use cases, benefits, how to deploy it, and its pricing.

You can also watch our video about Lambda@Edge.

What is Lambda@Edge?

Lambda@Edge allows you to run code across Amazon CloudFront edge locations globally without provisioning or managing servers, responding to end-users at the lowest network latency.

Lambda at edge how it works

You just upload your Node.js or Python code to AWS Lambda and configure your function to be triggered in response to CloudFront requests/events. The code is then ready to execute across AWS edge locations globally when a content request is received and scales with the volume of requests globally.

Lambda at edge how it works

CloudFront events that can be used to trigger Lambda@Edge

Your functions will automatically trigger in response to the following Amazon CloudFront events:

Lambda at edge how it works

  • Viewer Request – This event occurs when an end-user or a device on the Internet makes an HTTP(S) request to CloudFront, and the request arrives at the edge location closest to that user.
  • Viewer Response – This event occurs when the CloudFront server at the edge is ready to respond to the end-user or the device that made the request.
  • Origin Request – This event occurs when the CloudFront edge server does not already have the requested object in its cache, and the viewer request is ready to be sent to your backend origin web server (e.g. Amazon EC2 or Amazon S3).
  • Origin Response – This event occurs when the CloudFront server at the edge receives a response from your backend origin web server.

Lambda at edge how it works

Lambda@edge limits

The following AWS Lambda features are not supported by Lambda@Edge:

  • Lambda functions with more than 512 MB of ephemeral storage.
  • The runtime must be Node.js 12.x, Node.js 14.x, Python 3.7, Python 3.8, Python 3.9.
  • Configuration of your Lambda function to access resources inside your VPC.
  • Lambda function dead letter queues.
  • Lambda environment variables.
  • Lambda functions with AWS Lambda layers.
  • Using AWS X-Ray.
  • Lambda reserved concurrency and provisioned concurrency.
  • Lambda functions that use the arm64 architecture.

Quotas that differ by event type:

Lambda at edge how it works

Lambda@Edge benefits

Managed computing

You can automatically scale and run your code in AWS locations around the world without deploying or managing origin servers in multiple locations, or setting up load balancing or DNS (Domain Name System) routing services.

You can add new functionality without making any changes to existing applications running on the origin server. Finally, by using Lambda@Edge and CloudFront, you have less origin infrastructure to manage than with a traditional CDN.

Lower latency for webs and apps

Lambda@Edge runs your code in AWS edge locations around the world, close to your users, so you can deliver full-featured custom content with high performance and low latency.

Customize your content at the edge

With Lambda@Edge, you can customize the content delivered through CloudFront CDN, and you can select the computing resources provided, thus customizing execution time, based on your application performance needs.

Lambda@Edge pricing

Lambda@Edge is charged based on the following two factors:

  • The number of requests. The cost is $0.60 per 1 million requests ($0.0000006 per request). At the time of writing, the price is the same for every AWS region.
  • Function duration. Currently, the cost is $0.00005001 for every GB-second used. For example, if you allocate 128MB of memory to be available per execution with your Lambda@Edge function, then your duration charge will be $0.00000625125 for every 128MB-second used. Note that Lambda@Edge functions are metered at a granularity of 50ms.

Take a look at the AWS Lambda pricing model, some things you need to keep in mind when using it and how to optimize the cost of Lambda functions.

Learn more

Lambda@Edge use cases

Lambda@Edge is optimized for latency-sensitive use cases where your end viewers are distributed globally. All the information you need to make a decision should be available at the CloudFront edge, within the function and the request.

The use cases of Lambda@Edge can be divided into:

Performance

One of the biggest benefits of using Lambda@Edge is to improve cache hit rates, either by increasing the likelihood that content will be cached when it is returned from the origin, or by increasing the availability of content that is already in a cache condition. You can add or modify cache control headers on responses.

  • Use query string or user agent normalization to reduce request variability
  • Dynamically route to different origins based on attributes of request headers, cookies, or query strings

Dynamic Content

With Lambda@Edge, you can dynamically generate content based on request or response attributes.

  • Resize images based on request attributes
  • Do A/B testing
  • Generate a 302/301 redirection response for all requests to an expired or outdated resource

Security

Lambda@Edge can also be used to handle custom authentication and authorization.

  • Sign requests to custom origins that enforce access control
  • Set up bot detection
  • Add security headers to the response

Origin functions

In some cases, the origin requires additional request and response logic. You can run your Lambda@Edge function in CloudFront instead of code running on the origin server for a more seamless solution. For example, you can implement logic to do the following:

  • Create a user-friendly URL
  • Manage authentication and authorization for origin requests
  • Manipulate URLs or requests to match your origin directory structure
  • Implement custom load balancing and failover logic

How to deploy the first Lambda@Edge function

The first thing you will notice is that you will not find this service in the AWS Management Console. This is because it is a little different from a lot of other services like Amazon S3, Amazon EC2 etc. So let’s look at how the Lambda@Edge function is created in the AWS Management console.

Before going through this simple manual, you will need an Amazon CloudFront distribution.

1. In the AWS Lambda console, create a Lambda function in the US East (N. Virginia) Region. When creating your function, select AWS policy template: Basic Lambda@Edge permissions as your execution role.

Deploy Lambda at Edge1

2. Upload or add your code in Node.JS or Python. Save and deploy this function. 3. Add a trigger to this function.

Deploy Lambda at Edge2

4. Choose CloudFront as a trigger and click on deploy.

Deploy Lambda at Edge3

5. Choose the CloudFront distribution and cache behavior. Then specify the CloudFront event that causes the function to execute.

Deploy Lambda at Edge4

6. When you create a trigger, Lambda replicates the function to AWS edge locations. 7. If you need a more accurate description, try visiting the official AWS docs. And if you need to delete your test function, visit deleting Lambda@Edge functions and replicas.

Lambda@Edge examples

Because Lambda@Edge can be used for many use cases that have been described in the previous section, it’s very difficult to add examples of the code that will be needed for a specific use case. AWS has some in their official documentation here: Lambda@Edge example functions.

In our video about Lambda@Edge, we are using the Node.JS code below to redirect traffic from non-www Route 53 hosted domain to www domain. If you want to use it, just change the my-test-2022.cf domain to yours.

 exports.handler = async (event) => {
    // (1)
    const request = event.Records[0].cf.request;
    // (2)
    if (request.headers.host[0].value === 'my-test-2022.cf') {
      // (3)
      return {
        status: 301',
        statusDescription: Redirecting to www domain,
        headers: {
          location: [{
            key: 'Location',
            value: https://www.my-test-2022.cf${request.uri}
          }]
        }
      };
    }
    return request;
  };

What is the difference between AWS Lambda and Lambda@edge?

The difference is that AWS Lambda is a regional service, and if you use it for Internet-related apps, you usually use it with Amazon API Gateway. And if you need to use this kind of application globally, you can deploy it yourself to multiple regions around the world or you can leverage Amazon CloudFront CDN.

Using Lambda@Edge and Amazon CloudFront allows you to execute logic automatically across multiple AWS edge locations based on where your end viewers are located.

This is the main difference between Lambda and Lambda@Edge. Everything else is mostly similar.

Conclusion

By using CloudFront and Lambda@Edge, you can start building high-performing distributed serverless web applications for your use cases. In this blog post, we shared what Lambda@Edge is, its benefits, use cases, and how to deploy it in the AWS Management Console.

Are you ready to accelerate your business to the cloud?

Contact us

Similar blog posts

See all posts
CategoryCase Studies

InScope Choses StormIT and AWS for Deployment of their AML Solution

InScope chose to migrate its core technology platform to Amazon Web Services, a cloud leader in Infrastructure & Platform Services

Find out more
CategoryArticles

What is a Web Application Firewall (WAF) and Why Use it?

What is the difference between a firewall and a web application firewall (WAF) and what are the benefits of WAF. Learn more...

Find out more
CategoryArticles

AWS Instance Scheduler: Everything you Need to Know and Tutorial

What is the AWS Instance Scheduler? Deployment of the AWS Instance Scheduler solution. Learn more

Find out more
CategoryArticles

Scalability in Cloud Computing: Horizontal vs. Vertical Scaling

Look deeper into horizontal and vertical scaling and also into AWS scalability and which services you can use.

Find out more
CategoryArticles

Does Putting CloudFront in Front of API Gateway Make Sense?

Learn about API Gateway endpoint types and the difference between Edge-optimized API gateway and API Gateway with CloudFront distribution.

Find out more
CategoryCase Studies

Windy - The Extraordinary Tool for Weather Forecast Visualization

StormIT helps Windy optimize their Amazon CloudFront CDN costs to accommodate for the rapid growth.

Find out more