Optimizing NodeJS Library Use in Lambda Functions
DeveloperSteve
Posted on August 11, 2022
As Dev/Ops, we build our applications with our end users in mind. Ensuring that they have a speedy and responsive application experience is integral to the application’s success. It’s equally important to make sure that the server side performance is up to the task at hand and not consuming more resources than it needs.
That’s why it’s critically important that our Lambda functions only call on the libraries and dependencies that they need to run. This is especially so when it comes to the AWS-SDK, which contains a lot of functionality that your Lambda function may not need but will load into memory.
Let’s take a look at an example using a basic NodeJS function that connects to a DynamoDB table called lambda_test
.
This is the code that we want to use for our test. It’s important to note that the whole AWS-SDK library is being called on but we are only using DynamoDB.
const AWS = require('aws-sdk');
exports.handler = async (event, context) => {
const documentClient = new AWS.DynamoDB.DocumentClient();
let responseBody = "";
let statusCode = 0;
const params = {
TableName: "lambda_test"
};
try {
const data = await documentClient.scan(params).promise();
responseBody = JSON.stringify(data.Items);
statusCode = 200;
} catch (err) {
responseBody = `Unable to get data: ${err}`;
statusCode = 403;
}
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json"
},
body: responseBody
};
return response;
};
Checking on test invocations in the Lumigo dashboard, we can see that it does run, although it has some fairly high metrics.
Ideally, we only want to call in the relevant DynamoDB libraries because we only need that to run as part of this script. So instead of using const AWS = require(‘aws-sdk’)
in our code to call on the whole SDK, we can just call the DynamoDB part of the library and save some time and resources.
By changing only two lines in the code snippet, we can improve the performance. Our new test code will look like this:
const AWS = require('aws-sdk/clients/dynamodb')
exports.handler = async (event, context) => {
const documentClient = new AWS;
let responseBody = "";
let statusCode = 0;
const params = {
TableName: "lambda_test"
};
try {
const data = await documentClient.scan(params).promise();
responseBody = JSON.stringify(data.Items);
statusCode = 200;
} catch (err) {
responseBody = `Unable to get data: ${err}`;
statusCode = 403;
}
const response = {
statusCode: statusCode,
headers: {
"Content-Type": "application/json"
},
body: responseBody
};
return response;
};
And now, if we take that for a spin to test out our changes we can see that even the cold start improved.
Check out some other ways to see how you can optimize your NodeJS lambda functions
Posted on August 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.