In AWS lambda context, I am just wondering if it is good practice to move the S3 client creation out of the handler, and what benefits or performance improvement it can get?
For the following two examples,
Will the later one (with s3 object creation out of handler) benefit from sharing keep-alive connections across invocations. And the later one also provides connection pool?
Thank you, Ron
import { S3 } from 'aws-sdk';
export const handleEvent: SQSHandler = async (event: SQSEvent, context: Context) => {
const s3Client = S3();
s3Client.getObject(...);
s3Client.putObject(...);
}
Vs.
import { S3 } from 'aws-sdk';
const s3Client = S3(); // move the S3 object creation out of handler
export const handleEvent: SQSHandler = async (event: SQSEvent, context: Context) => {
s3Client.getObject(...);
s3Client.putObject(...);
}
CodePudding user response:
Yes, its a good practice, since lambda may reuse your execution environment:
Objects declared outside of the function's handler method remain initialized, providing additional optimization when the function is invoked again.
Thus in your case, lambda may simply reuse your s3Client
, since its outside the handler, rather then instantiate new one all the time, if it ware inside the handler.