Logo

dev-resources.site

for different kinds of informations.

AWS Serverless: How to Create and Use a Lambda Layer via the AWS SAM - Part 1

Published at
1/9/2025
Categories
aws
lambda
lambdalayer
cloudcomputing
Author
bhatiagirish
Author
12 person written this
bhatiagirish
open
AWS Serverless: How to Create and Use a Lambda Layer via the AWS SAM - Part 1

In my previous articles, I covered various use cases for AWS Serverless Lambda functions, ranging from a simple "Hello, World" example to more advanced scenarios involving API Gateway, DynamoDB, and integrations with Amazon Bedrock for Generative AI applications.

I also shared an article demonstrating how to create a Lambda layer using the AWS Management Console.

If you're interested in these topics, please visit my content page for these published articles.

In this article, I will demonstrate how to use AWS Lambda Layers and configure them for a Lambda function using AWS SAM. For this use case, I will start by creating the layer in the AWS Management Console. Then, I will switch to AWS SAM to reference the layer in the Lambda function, build the function, and validate it locally.

Let's look at the architecture diagram!

Image architecture

Introduction to Lambda Layers

Let's first review what a lambda layer is! A Lambda Layer is a way to share reusable code and libraries among multiple lambda functions. It makes the size of lambda function deployment smaller. Also, by packaging shared functions in a Lamba layer, you can simplify the deployment process and ensure consistency across functions.
In order to create the layer, first step is to create a zip file that contains your sharing function code or supplement libraries. Once created and uploaded in the AWS using console or IaC, this layer then can be referenced by the lambda functions.

Benefits of Using Lambda Layers

Lambda layers offer several advantages, including:

  • Reusability of Code

For example, a common function can be shared across multiple Lambda functions.

  • Simplified Deployment

By placing common code in a layer, the deployment size of Lambda functions is reduced. This also provides a central location for updating shared code.

  • Inline Function Editing

With reduced deployment size due to layers, Lambda functions can be edited inline in the AWS Management Console without exceeding size constraints.

  • Library Management

Frequently used libraries can be packaged in a layer, making them accessible to multiple functions.

Constraints to Consider When Using Lambda Layers

When using Lambda layers, keep the following constraints in mind:

  • A Lambda function can use up to five layers.
  • Each layer has a maximum size limit of 50 MB (compressed).
  • The total size of the uncompressed function code and layers combined cannot exceed 250 MB.

Additionally, layers are immutable. Any update to a layer creates a new version, and functions must explicitly reference the updated version to incorporate the changes.

Use Cases of Lambda Layers

Lambda layers can be used in various scenarios, including:

  • Shared Libraries
    Shared libraries can be packaged in layers. For example, the Pandas library can be included for use in Python functions.

  • Custom Functions
    Custom functions can be packaged in a layer and reused across multiple Lambda functions.

  • Common Configuration
    Common configuration settings can be packaged in a layer.

  • Logging Tools
    Logging utilities can be included in a layer.

Create a Lambda Layer

In this example, I will create a Lambda Layer to include a reusable Python function that generates a greeting message.

The function, hellogreeting, takes a name as input and returns a personalized message. If no name is provided, it defaults to a generic "Hello, World!" message.

Here’s the function code:

Image fncode

This function will be packaged into a Lambda Layer so it can be reused across multiple Lambda functions without duplicating code. In the current example, I will invoke this layer from one lambda function.

To create this function as layer, Navigate to the Lambda console and select create Layers.

Image createlayer1

Provide the layer name, description and runtime as python 3.13 and upload the zip file created for the layer. This will create the targeted layer in the console.

Use the Lambda Layer in a Function

I will use this lambda layer in a Lambda function. To use the layer, let's review the steps:

Import the Required Modules and Layer Functionality

The json module is imported to format the response as JSON.
The hellogreeting function is imported from the helloworldlayer.

Lambda Handler Function

  • The lambda_handler function is the entry point for the Lambda function.
  • It uses the hellogreeting function, passing the name "girish" as a parameter to generate a personalized greeting message.

Return the Response

  • The response is returned as a dictionary with:
  • statusCode: 200 indicating success.
  • body: json.dumps(msg) where msg contains the greeting message formatted as JSON.

Code is as below:

Image fncode2

Now that we have both the Lambda layer and the Lambda function code, let's attach the layer to the Lambda function.

For this section, I will utilize AWS SAM (Serverless Application Model) to develop and validate the Lambda function locally. AWS SAM is particularly useful for testing and debugging serverless applications before deploying them to the cloud.

Reviewing the template.yaml for AWS SAM

Let's review the template.yaml for the AWS SAM:

Image samtemplate

The template.yaml file includes a reference to the Lambda layer. Specifically, the Layers property points to the layer's ARN created in the earlier step using the AWS Console.

Note: Each time you update a layer, a new version is created. To use the updated layer, ensure you update the reference in your template.yaml.

Build and Validate

Since I am using AWS SAM for this function, let’s begin by building the function. Use the following command to build the function:
Command: sam build

Image sambuild

Once the build is successful, you can invoke the function locally using the sam local invoke command:

Command: sam local invoke

For example:

sam local invoke helloGreetingFn
When executed with the name parameter set to 'girish', you should expect the following output:

Image result

Deploying to AWS Cloud

After validating the function locally, you can deploy it to the AWS Cloud using the sam deploy command:

Command: sam deploy

This concise workflow demonstrates how to create, validate, and deploy Lambda functions using AWS SAM. By leveraging AWS SAM, you can streamline the development process and ensure your functions are tested thoroughly before deployment.

Cleanup - Delete the Lambda function & Layer

Once you have completed the setup, ensure you delete the Lambda function to avoid unnecessary resource usage. Additionally, delete the Lamba layer. If you created any new roles during the process, remember to delete those as well.

Conclusion

In this article, I demonstrated how to configure a Lambda Layer and integrate it with a Lambda function. We covered how Lambda Layers enable the reuse of code, such as shared functions and libraries, and how they can be referenced by one or more Lambda functions. To create the Lambda layer, I used the AWS Console. For referencing this layer in the Lambda function and building the function, I utilized AWS SAM.

In the next article, I will demonstrate how to use AWS SAM to create both the Lambda layer and the Lambda function, showcasing the effective use of an Infrastructure as Code (IaC) approach when working with Lambda layers and functions.

I hope you found this article both helpful and informative!

Thank you for reading!

Watch the video here:

https://www.youtube.com/watch?v=NYLdukCUpwM

𝒢𝒾𝓇𝒾𝓈𝒽 ℬ𝒽𝒶𝓉𝒾𝒶
𝘈𝘞𝘚 𝘊𝘦𝘳𝘵𝘪𝘧𝘪𝘦𝘥 𝘚𝘰𝘭𝘶𝘵𝘪𝘰𝘯 𝘈𝘳𝘤𝘩𝘪𝘵𝘦𝘤𝘵 & 𝘋𝘦𝘷𝘦𝘭𝘰𝘱𝘦𝘳 𝘈𝘴𝘴𝘰𝘤𝘪𝘢𝘵𝘦
𝘊𝘭𝘰𝘶𝘥 𝘛𝘦𝘤𝘩𝘯𝘰𝘭𝘰𝘨𝘺 𝘌𝘯𝘵𝘩𝘶𝘴𝘪𝘢𝘴𝘵

lambda Article's
30 articles in total
Favicon
Getting Started with AWS Lambda: A Guide to Serverless Computing for Beginners
Favicon
Interfaces funcionais predefinidas
Favicon
Pergunte ao especialista - expressões lambda nas biblioteca de APIs
Favicon
Referências de construtor
Favicon
Referências de método
Favicon
Pergunte ao especialista - referência a um método genérico
Favicon
AWS Serverless: How to Create and Use a Lambda Layer via the AWS SAM - Part 2
Favicon
Setting Up AWS SNS, Lambda, and EventBridge via CLI: A Beginner's Guide
Favicon
As expressões lambda em ação
Favicon
Fundamentos das expressões lambda
Favicon
Pergunte ao especialista - especificando os tipos de dados em lambdas
Favicon
Introdução às expressões lambda
Favicon
AWS Serverless: How to Create and Use a Lambda Layer via the AWS SAM - Part 1
Favicon
Optimizing AWS Costs: Practical Tips for Budget-Conscious Cloud Engineers
Favicon
Build a highly scalable Serverless CRUD Microservice with AWS Lambda and the Serverless Framework
Favicon
Serverless or Server for Django Apps?
Favicon
Optimizing Serverless Lambda with GraalVM Native Image
Favicon
Solving the Empty Path Issue in Go Lambda Functions with API Gateway HTTP API
Favicon
AWS workshop #2: Leveraging Amazon Bedrock to enhance customer service with AI-powered Automated Email Response
Favicon
How to return meaningful error messages with Zod, Lambda and API Gateway in AWS CDK
Favicon
Managing EKS Clusters Using AWS Lambda: A Step-by-Step Approach
Favicon
Schedule Events in EventBridge with Lambda
Favicon
Ingesting Data in F# with Aether: A Practical Guide to Using Lenses, Prisms, and Morphisms
Favicon
How to Create a Lambda Function to Export IAM Users to S3 as a CSV File
Favicon
New explorations at Serverless day
Favicon
Mastering AWS Lambda Performance: Advanced Optimization Strategies for 2025
Favicon
Lambda vs. Named Functions: Choosing the Right Tool for the Job
Favicon
How did I contribute for OpenAI’s Xmas Bonus before cutting 50% costs while scaling 10x with GenAI processing
Favicon
My (non-AI) AWS re:Invent 24 picks
Favicon
Alarme Dynamo Throttle Events - Discord

Featured ones: