AWS client not reused in a Lambda function Medium

Recreating AWS clients from scratch in each Lambda function invocation is expensive and can lead to availability risks. Clients should be cached across invocations.

Detector ID
java/lambda-client-reuse@v1.0
Category

Noncompliant example

1public class LambdaClientReuseNoncompliant implements RequestHandler<String, Void> {
2
3    private AmazonS3 s3Client;
4
5
6    public Void handleRequest(String requestEvent, Context context) {
7        System.err.println("Nothing to see here");
8        createBucketNoncompliant();
9        return null;
10    }
11
12    private void createBucketNoncompliant() {
13        s3Client.createBucket("bucketName");
14        // Noncompliant: recreates AWS clients in each lambda invocation.
15        this.s3Client = AmazonS3ClientBuilder.standard()
16                .withRegion(Regions.US_EAST_1).build();
17    }
18}

Compliant example

1public class LambdaClientReuseCompliant implements RequestHandler<String, Void> {
2
3    private AmazonS3 s3Client;
4    
5    public LambdaClientReuseCompliant() {
6        // Compliant: creates the client only once.
7        this.s3Client = AmazonS3ClientBuilder.standard()
8                .withRegion(Regions.US_EAST_1).build();
9    }
10
11    public Void handleRequest(String requestEvent, Context context) {
12        System.err.println("Nothing to see here");
13        createBucketCompliant();
14        insertObjectCompliant("storeOject");
15        return null;
16    }
17
18    private void createBucketCompliant() {
19        // Compliant: uses the cached client.
20        s3Client.createBucket("storeObject");
21    }
22
23    private void insertObjectCompliant(String s3Folder) {
24        AmazonS3URI amazonS3URI = new AmazonS3URI(s3Folder);
25        // Compliant: uses the cached client.
26        s3Client.putObject(amazonS3URI.getBucket(), amazonS3URI.getKey(), "hello");
27    }
28}