Using AWS Lambda Layers

Anaica Grouver
3 min readNov 14, 2020

--

Ever wished there was a way to keep your deployment packages smaller to make deployment easier? Ever wished there was a simple & easy way to reuse code effectively on AWS lambda? Ever wished there was a way to avoid errors that can occur when you install and package dependencies within your function? Well, guess what? There is!

You can do all of the above with AWS Lambda Layers. Now, what is a layer? A layer is a ZIP archive that contains libraries or other dependencies. Thanks to layers, you can use dependencies of your function without including them in your deployment package.

When we load layers in the lambda function, the layers are unzipped in the /opt directory in the function execution environment. Depending on the runtime you choose, the structure of your layer will change accordingly. Check it out here.

Let’s get started!
I will now guide you on how to include a library (lodash) as a layer in Nodejs. We will do this in two ways, manually & via Serverless Framework.

For Nodejs layers, we will be following the following directory structure:

Now let’s zip this & upload it on AWS.

Once you are done with creating a layer, we can access it from lambda. But before, let us see how to upload a layer with Serverless Framework. Below is how the yml file will look like. Deploying this will create the specified layer.

Directory Structure

Let’s move onto testing the layer. To add a layer to the lambda function, we will follow the following steps.

After this step, deploy the changes made due to layer configuration & use test with default configuration by clicking on test. You will see the above results. Your lambda layer is up and running!

Few pointers to keep in mind:

  • A lambda function can use as many as 5 layers at a time
  • You can create your own layers, use existing ones or use layers of other AWS customers
  • The order of lambda layers matters, so if the layers depend on each other, make sure to keep an eye on the order

--

--