DEV Community

Durgadas Kamath for AWS Community Builders

Posted on • Originally published at durgadas.in

Improve the speed of your AWS lambda API (NodeJS) with these two easy techniques.

Being inquiring is fine, but striving for improvement is better. I have been using AWS Serverless services (Lambda, DynamoDB) with NodeJS as the runtime . I’ve often wondered how to reduce latency while developing APIs that integrate with AWS services.

While adhering to best practises with minimal imports and other requirements is essential, there are two simple measures you can do to further enhance the speed of your Serverless application.


callbackWaitsForEmptyEventLoop = false

Our lambda API accepts (event, context, callback) as an argument when it is defined. NodeJS leverages an event loop, and if you use a callback to deliver a response, it delays sending the output until the event loop is empty.

If this property (callbackWaitsForEmptyEventLoop) is set to false, the callback will immediately return the response, and any outstanding events will run on next invocation.

context.callbackWaitsForEmptyEventLoop = false;
Enter fullscreen mode Exit fullscreen mode

callbackWaits


AWS_NODEJS_CONNECTION_REUSE_ENABLED = 1

A lambda implementation will nearly always include integration with AWS services. When interacting with AWS services using the aws-sdk, a fresh TCP/IP connection is always established. This increases latency, which may potentially be longer than the time needed to query DynamoDB:-).

So, AWS offers a “Connection Reuse” method. Simply changing the environment variable AWS_NODEJS_CONNECTION_REUSE_ENABLED to 1 will enable this.

awsConnectionReuse

Another approach is to add keepAlive value to the options while configuring the AWS client.

awsKeepAlive

Note: This parameter is enabled by default if you’re using the AWS SDK version 3.


Check out my YouTube channel for videos on serverless computing.

Follow me for more of interesting articles. Happy Learning #AWSCommunity #AWSCommunityBuilder

Top comments (0)