AWS Lambda optimization tip - reuse TCP connections in Node.js
- Tomasz Łakomy
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.
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?
How do I make sure that I'm getting those benefits in my AWS Lambda functions?
You can either:
truefor 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.
NodejsFunctionAWS CDK construct, where
awsSdkConnectionReuseoption is set to
If you'd like to learn more about AWS Lambda environment variable, check out our guide to default AWS Lambda environment variables.