Lambda Functions and Lambda layers

Muhammad Shakeel
7 min readJan 19, 2022

--

so today we talking about layers for lambda functions. Lambda layers are very useful and give us two advantages

1) we can extracts some codes from a lambda function into a layer and then this layer can be used across several functions, so if you have some modules and library and you want to reuse it across several functions and bundle it with them we can create layer and then use it in these functions.

2) The other benefit is that the bundle of our lambda becomes much smaller since we extract the code and put it in a layer it means the lambda function will have less code that we’ll need to deploy every time we have data function.

To learn how layers work

We’ll create a lambda functions name Sample-function

Create the function

You create a Node.js Lambda function using the Lambda console. Lambda automatically creates default code for the function.

  1. Open the Functions page of the Lambda console.
  2. Choose to Create function.
  3. Under Basic Information, do the following:
  4. For Function name, enter image-detail.
  5. For Runtime, confirm that Node.js 14.x is selected.
  6. Choose to Create function.

Note that Lambda provides runtimes for .NET (PowerShell, C#), Go, Java, Node.js, Python, and Ruby.

Now some sample code to our lambda function

so lets export or download the function at our pc

  • Open the sample-function page of the Lambda console and choose the Actions dropdown button.
  • Select Export Function and click Download Deployment package from the pop-up window.
  • Extract the downloaded .zip file into an empty folder and open this folder in the console.
  • So first of all we want to create an NPM package

run npm init

and set up all. Now that we created our package we want to install random pictures which we use to get random picture URL as well as the width and height of the picture with author-name

npm random-picture

Finally, we create an imageDimension.js file to get image dimensions.

imageDimension.js Look like

exports.getDirection = (width, height) => {
console.log(width, height);
if (width === height) {
return 'square';
}
else if (width > height) {
return 'horizontal';
}
else {
return 'vertical';
}
};

index.js Look like

const { RandomPicture } = require('random-picture')
const { getDirection } = require("./imageDimension");
exports.handler = async (event) => {
const res = await RandomPicture();
return {
"Dimension": getDirection(res.width, res.height),
url: res.url,
author: res.author,
};
};

So let’s create a zip file of that folder. Open the sample-function page of the Lambda console choose Upload from the dropdown button and click the .zip file option from the code tab.

Select the .zip file and save it. After completing this action, your code source editor directory looks like this.

So let’s test our function. When we run the function, we get Dimension, URL of the picture, and author-name.

So our function works so let’s try to take all of the code that we want to extract and separate it into a layer.

Create Layers

  1. Open the Layers page of the Lambda console.
  2. Choose to Create layer.
  3. Under Create a layer, set name and description. We’ll call it image-detail
  4. (Optional) For Description, enter a description for your layer.
  5. Choose a layer source ‘Upload a .zip file’ option to upload a zip file that will contain the code of our layer.

So let's create the zip file.

  • So let's create an empty folder and open it in the console.
  • First of all, we want to create an NPM package

run npm init

and set it up. Now that we created our package. we want to install a random-picture which we use to get a random picture URL as well as the width and height of the picture with the author's name.

npm install random-picture

  • Finally, we create an imageDimension.js files that are going to contain a function that we saw earlier. So it just copy-past functions into our new file. we’ll go back to our function and let's copy the contents of imageDimension.js file of sample-function and paste it into image-detail Layer’s imageDimension.js file.

imageDimension.js Look like

exports.getDirection = (width, height) => {
console.log(width, height);
if (width === height) {
return 'square';
}
else if (width > height) {
return 'horizontal';
}
else {
return 'vertical';
}
};
  • But there’s one more thing that we need to do. Create a folder named nodejs

“The name of the folder is not accidental. This is the name that lambda requires us to use when we want to load node modules.”

  • So we’ll move node modules to the nodejs folder and also package.json and packageplock.json.

Once these files are placed in the nodejs folder, we can just assume that when we require a library it will be required from the nodejs folder node_modules.

  • So let’s create a zip file that we can upload to the layer.

So we’ll go back to the console and choose the zip file that we want to upload.

  • we also need to specify runtimes that this layer will be compatible with should work with nodejs 14.x

Finally, create the layer

The layer was created as you see the layers also have versioning so this is version one of the layer and that is very convenient because it allows us to use different versions of the same layer across different functions.

Let's switch back to our lambda function and attach the layer that we created.

  • Open the sample-function page of the Lambda console, you’ll see that there is an option to list the layers and to add new ones at top of the page.
  • So let’s choose to add a layer
  • Under Choose a layer, select Custom layers and it should list the layers that created Image-detail under Custom layer, and select version.

Finally, let’s add the layer.

Now that we added the layer and save the function. We can start getting a read of some of the code we have that is now part of the layer. So let's see what we can remove.

  • Select node_modoles folder with all its contents so we no longer need it, we also select package.json, package-lock.json, and also select imageDimension.js file and we’ll delete all of these files. Because these files are now under the layer we no longer need them here.

Now we are left only with the handler and the imports of the codes that we’re going to use. One last thing that we’ll need to change is how we require the imageDimension.js file because when we require it this way then will try to load it from the same folder. If we want to tell lambda that we want the imageDimension.js file far from our layer we need to use the opt folder this is the folder that will contain the code that we extracted into our layer excluding the node_modules which we already saw that need to go to the nodejs folder

So now your sample function has only one handler file index.js and code look like.

So let's try to save and then test our functions again.

once again we get a response as result.

So now our bundle is significantly smaller and every time we deploy the function it will work much faster because this much less code to deploy that’s the first advantage.

The second advantage is that now all the code that we have in our layer can reuse across other functions. If we have functions that need to load Axios or the random-image library, we can just attach the layer that we created to them and use these modules as if they are part of the lambda function.

the important thing to remember is that we need to place our nide_modules within a folder called nodejs and second, when we load files to be created we have to tell them that they are in the opt folder and then lambda will know that they should be loaded from our layer.

--

--

Muhammad Shakeel

Exceptionally creative and dependable Professional Level Web and Mobile Developer with a stellar customer service record and superb work ethic. AWS | JavaScript