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 implements RequestHandler<Object, Object> {
@Override
public Object handleRequest(final Object input, final Context context) {
S3Client s3Client = DependencyFactory.s3Client();
s3Client.listBuckets();
// ...
}
}
Compliant solution
public class App implements RequestHandler<Object, Object> {
private final S3Client s3Client;
public App() {
s3Client = DependencyFactory.s3Client();
}
@Override
public Object handleRequest(final Object input, final Context context) {
s3Client.listBuckets();
// ...
}
}