Resources that can be reused across multiple invocations of the Lambda function should be initialized at construction time. For example in the constructor of the class, or in field initializers. This way, when the same container is reused for multiple function invocations, the existing instance can be reused, along with all resources stored in its fields. It is a good practice to reuse SDK clients and database connections by initializing them at class construction time, to avoid recreating them on every lambda invocation. Failing to do so can lead to performance degradation, and when not closed properly, even out of memory errors.
In this sentence, I think the phrase "outside of the Lambda function" is not clear or precise enough. And I find the sentence a bit complicated:
____When initializing an SDK client or database connection outside of the Lambda function, you optimize your chances to benefit from context reuse, when the same container is reused for multiple function invocations.
____
Here's an attempt to make it more precise and clear:
____Resources that can be reused across multiple invocations of the Lambda function should be initialized at construction time. For example in the constructor of the class, or in field initializers. This way, when the same container is reused for multiple function invocations, the existing instance can be reused, along with all resources stored in its fields. It is a good practice to reuse SDK clients and database connections by initializing them at class construction time, to avoid recreating them on every lambda invocation. Failing to do so can lead to performance degradation, and when not closed properly, even out of memory errors.
____
(That last remark about performance degradation and out of memory errors come from real-life experience in SonarCloud ;))
=== on 27 May 2021, 14:09:12 Janos Gyerik wrote:
I think the title could be better. Instead of "AWS Clients and Database connections should be declared outside of the Lambda function.", how about: Reusable resources should be initialized at construction time of Lambda functions
That is, declaration would not be enough, it's the initialization that's the most important (declaration is implied), and "outside" is more specifically at construction time.
=== on 31 May 2021, 11:28:23 Quentin Jaquier wrote:
Sounds good to me, thanks for the suggestions [~janos.gyerik].