javaamazon-web-servicesaws-lambdaautocloseable

How to close aws client in aws lambda


I am trying to correctly write an aws lambda using Java that will use aws sdk SqsClient and SnsClient. I see that these clients implement close() method, and it is generally a good practice to call this method when client is no longer required. And the best practices for lambda (https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html) advices to

Initialize SDK clients and database connections outside of the function handle

So, my question is: is aws lambda wise enough to close aws sdk clients automatically, so that I can write something like this, and do not worry about closing the client explicitly when lambda container is closed.

public class SQSProcessingHandler implements RequestHandler<String, String> {

    private SqsClient sqsClient = SqsClient.create();

    @Override
    public String handleRequest(final String event, final Context context) {
        ListQueuesResponse response = sqsClient.listQueues();
        return response.queueUrls().stream().collect(Collectors.joining(","));
    }
}

If explicit close is still required, could you please help me to find out how can I know that the lambda container is about to close, so that I should call close() on the client?


Solution

  • For best practice, you should explicitly close the client unless you have reasons not to.

    Service clients in the SDK are thread-safe. For best performance, treat them as long-lived objects. Each client has its own connection pool resource that is released when the client is garbage collected. The clients in the AWS SDK for Java 2.0 now extend the AutoClosable interface. For best practices, explicitly close a client by calling the close method.

    Reason not to explicitly close the client:

    For best performance, do not explicitly close the client. This is because unclosed client maintains socket with the service by remaining in a reusable connection pool after it is opened. So, the client may be reused when lambda is invoked again. Lambda can and will close the client for you automatically at a later time even if you're not closing it explicitly.

    ref: https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/creating-clients.html