Skip to content

Best Practice for lifecycle management of JavaScript client

0

I have pretty much same question as here: https://stackoverflow.com/questions/66964900/best-practices-for-aws-sdk-clients-lifecycle-in-javascript

and wondering if I should create a singleton instance of the client that gets reused and lives forever or if I should create a new instance per request. Since the question has already been asked on SO and did not get a definitive answer, I am asking it here.

asked 10 months ago258 views
1 Answer
0

In AWS Lambda functions, it's a best practice to create and reuse AWS SDK clients outside the handler function rather than creating new instances for each invocation. This approach offers several benefits:

  1. Performance Improvement: Initializing AWS SDK clients involves establishing connections and setting up resources, which can be time-consuming. By creating clients outside the handler function, these resources are initialized once and reused across multiple invocations within the same execution environment.

  2. Connection Pooling: AWS SDK v3 for JavaScript/TypeScript maintains persistent connections by default for most services through connection pooling and keep-alive mechanisms. This applies to most HTTP/HTTPS services like S3, SNS, SQS, and DynamoDB.

  3. Avoiding Availability Risks: Recreating clients from scratch in each invocation can lead to availability issues, especially under high load.

Important notes:

  • Persistent connections are not maintained across different Lambda invocations - each execution environment maintains its own connections.
  • In AWS SDK v3, there is no longer a global configuration managed by the SDK. Configuration must be passed to each service client that is instantiated.
  • You can share configuration across multiple clients, but it won't be automatically merged with a global state.

Example of proper client initialization:

// Initialize outside the handler function
const s3Client = new S3Client({ region: 'us-east-1' });

export const handler = async (event) => {
// Reuse the client inside the handler
const result = await s3Client.send(new GetObjectCommand(params));
// Process result
};

This singleton pattern for AWS SDK clients is the recommended approach for Lambda functions to optimize performance and resource usage.
Sources
Does All AWS SDK V3 Clients keep persistent connections? | AWS re:Post
Configuration per service - AWS SDK for JavaScript
AWS client not reused in a Lambda function | Amazon Q, Detector Library

answered 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.