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.


This rule reports an issue when the SDK client or the database connection is initialized locally inside a Lambda function.


== Noncompliant Code Example

----
public class App {
    public void doSomething() {
         S3Client s3Client = S3Client.builder().region(region).build();
         s3Client.listBuckets();
         // ...
    }
}
----


== Compliant Solution

----
public class App {
    private final S3Client s3Client;

    public App() {
        s3Client = DependencyFactory.s3Client();
    }

    public void doSomething() {
         s3Client.listBuckets();
         // ...
    }
}
----


== See

* https://aws.amazon.com/fr/blogs/developer/tuning-the-aws-java-sdk-2-x-to-reduce-startup-time/[Tuning the AWS Java SDK 2.x to reduce startup time]
* https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html[Best practices for working with AWS Lambda functions]
* https://aws.amazon.com/fr/blogs/compute/container-reuse-in-lambda/[Understanding Container Reuse in AWS Lambda]


ifdef::env-github,rspecator-view[]
== Comments And Links
(visible only on this page)

include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]
