- Newest
- Most votes
- Most comments
When working with AWS clients in Lambda functions, you should not manually close them. Instead, you should initialize these clients outside the function handler to take advantage of execution context reuse.
Recreating AWS clients from scratch in each Lambda function invocation is expensive and can lead to availability risks. The recommended practice is to cache clients across invocations by initializing them in the global scope, outside the handler function.
AWS Lambda maintains the execution context for some time after a function has executed, in anticipation of another invocation. This allows you to use the global scope for one-off expensive operations like establishing connections, and then reuse these connections in subsequent invocations.
This applies to various AWS service clients including DynamoDB, S3, SNS, and others. The AWS SDK (both v2 and v3) maintains persistent connections by default for most services through connection pooling and keep-alive mechanisms.
It's important to note that while connections are reused within the same execution environment, persistent connections are not maintained across different Lambda invocations that run in separate execution environments.
Sources
AWS client not reused in a Lambda function | Amazon Q, Detector Library
AWS client not reused in a Lambda function | Amazon Q, Detector Library
AWS client not reused in a Lambda function | Amazon Q, Detector Library
Does All AWS SDK V3 Clients keep persistent connections? | AWS re:Post
AWS Lambda - Serverless Applications Lens
Relevant content
asked 5 years ago
- AWS OFFICIALUpdated a year ago
