- Newest
- Most votes
- Most comments
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:
-
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.
-
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.
-
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
Relevant content
- asked 2 years ago
- asked 7 years ago
- asked 3 years ago
- asked 5 years ago
