Published on

AWS Lambda optimization tip - reuse TCP connections in Node.js

Authors
Tired of using AWS Console? 🤕
Time to boost your productivity with Cloudash — an AWS desktop client.

The default Node.js HTTP/HTTPS agent creates a new TCP connection for every new request. Usually this is not a cause for concern, but for short-lived operations like DynamoDB queries it's possible that establishing a TCP connection can take longer than the operation you want to execute.

Moreover, to quote AWS docs:

Additionally, since DynamoDB encryption at rest is integrated with AWS KMS, you may experience latencies from the database having to re-establish new AWS KMS cache entries for each operation.

Not good.

Luckily, there's a simple fix - make sure that AWS_NODEJS_CONNECTION_REUSE_ENABLED environment variable is set to true. One this environment variable is set, your AWS Lambda functions will no longer establish a new TCP connection every single time.

That's cool and all, but what's the benefit?

As measured by AWS Serverless Hero Yan Cui in his excellent blogpost on this very topic it's possible to see even ~100ms performance improvements (your mileage may vary).

How do I make sure that I'm getting those benefits in my AWS Lambda functions?

You can either:

  • Set AWS_NODEJS_CONNECTION_REUSE_ENABLED to true for in Lambda function configuration (Cloudash team discourages so-called ClickOps though, consider using IaC instead)
  • Use AWS SDK v3 where this setting is the default. In fact there's an article on how to disable it in AWS docs.
  • Use NodejsFunction AWS CDK construct, where awsSdkConnectionReuse option is set to true by default.

If you'd like to learn more about AWS Lambda environment variable, check out our guide to default AWS Lambda environment variables.

Tired of switching between AWS console tabs? 😒

Cloudash provides clear access to CloudWatch logs and metrics, to help you make quicker decisions.
Try it for free:

Logs screen