Skip to content

AWS clients in Amazon Lambda - should I close them manually?

0

Hello there,

I am searching for an official resource of AWS where is written that:

  • Option 1 - "You should never close manually the lightweight AWS clients inside a lambda function"
  • Option 2 - "Manual closing of DynamoDB client is needed, for example.."

I know it is recommended this: "Take advantage of execution environment reuse to improve the performance of your function. Initialize SDK clients and database connections outside of the function handler, and cache static assets locally in the /tmp directory. Subsequent invocations processed by the same instance of your function can reuse these resources. This saves cost by reducing function run time."

I hope somebody help me with this.

I can NOT see in any official AWS documentation the following statement: "When the Lambda container is shut down (e.g., due to inactivity or scaling down), any initialized resources, including AWS SDK clients, are automatically destroyed by the container lifecycle."

asked 10 months ago277 views

1 Answer
1

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

answered 10 months ago

AWS
EXPERT

reviewed 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.