Search code examples
javaamazon-web-servicesamazon-dynamodbinversion-of-controlcdi

AWS Java SDK - What's faster? A single instance of DynamoDB client (@ApplicationScoped) or creating a new one for every request?


We have a server application that read/write a lot and in parallel in DynamoDB.

Today we inject a new DynamoDB with new AmazonDynamoDBClient for every injection point (CDI dependent scope). Mostly, a new request in our app, injects a DynamoDB instance.

I know DynamoDB is thread-safe and I can change it's scope to @ApplicationScoped, but the requests to the DynamoDB endpoint will be serial, killing the performance of my application? Or even having a single instance of DynamoDB it can handle simultanious requests to AWS DynamoDB endpoint?

Thanks


Solution

  • The clients for all the AWS services use HTTP calls under the hood. So irrespective of which service you are working with, DynamoDB in case of this question, the answer is the same, that AWS recommends using a single client instance for multiple requests.

    Here is an AWS forums question https://forums.aws.amazon.com/thread.jspa?messageID=247661 (might need sign in), that discusses this. To quote from the answer.

    Each instance of one of the SDK clients (ex: AmazonS3Client) creates its own client object for sending HTTP requests, which can be relatively expensive since it manages resources like HTTP connection pools.

    You'll get more efficient use of your resources by reusing the same S3 client object.

    As you put more load through the client, you might also take a quick look at the configuration options available through the ClientConfiguration class

    If you need more control on how the clients should behave, like whether they should use a common http connections pool or a separate one, then you can use the approaches described here https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/creating-clients.html

    So, to answer the question, what would be faster, creating separate clients for each requests would be wasteful on resources like connection pools and hence wont be faster. To get things to work faster one should look at client tuning options as detailed here https://aws.amazon.com/blogs/developer/tuning-the-aws-sdk-for-java-to-improve-resiliency/