DEV Community

Cover image for AWS Node.js Lambda performance optimization
Prabusah
Prabusah

Posted on • Updated on

AWS Node.js Lambda performance optimization

TL;DR

if using aws-sdk V2 (JavaScript) set a new environment variable for a Node.js AWS Lambda as below to reuse TCP connection:

Environment Variable Name: AWS_NODEJS_CONNECTION_REUSE_ENABLED
Environment variable Value: 1
Enter fullscreen mode Exit fullscreen mode

if using aws-sdk V3 (JavaScript) by default the TCP connection is reused, so no change required.

How AWS Lambda interacts with other services?

Lambda makes an http request to other services. HTTP request is facilitated by aws-sdk usually for communication with other AWS Services.

How HTTP works (high level)

HTTP is a request(client) - response(server) protocol. TCP connection needs to be established. Client(browser/application) requests data from Server via the connection... and Server responds the via the same connection.

How TCP connection established (high level)

Client sends SYN (synchronize) packet (TCP data is transmitted as packets) to Server. Server responds SYN-ACK (acknowledgement) packet to client. Client acknowledges the receipt SYN-ACK by sending ACK packet to the Server. So it's a 3 step process.

AWS Lambda and TCP

Example Lambda pseudocode:

lambda handler(){
  import aws-sdk
  put a record to Amazon DynamoDB by calling aws-sdk put().
}
Enter fullscreen mode Exit fullscreen mode

DynamoDB put is an HTTP call facilitated by aws-sdk.
So each time this lambda gets invoked (irrespective code/warm start), the Lambda has to establish TCP connection (has to do SYN, SYN-ACK, ACK) then make the put() call to send the data to DynamoDB.
Consider this pseudocode lambda is invoked million times then this TCP connection needs to be established million times.

How to solve TCP connection RE-establishment (concept)

Keep the connection alive.

How to keep the TCP connection alive in AWS Lambda

Create a new environment variable with name as AWS_NODEJS_CONNECTION_REUSE_ENABLED and set the value as 1.

Image by Shirley Hirst from Pixabay

Top comments (0)