Search code examples
amazon-web-servicesamazon-kms

AWS: KMSClient vs KMSClientBuilder


In the AWS SDK https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/kms/package-summary.html the KMS has two different types of clients. A regular client and a client builder. What is the purpose of them both? When do you choose one over the other?

I'm trying to implement envelope encryption using KMS. I want to be able to hit the KMS endpoint and encrypt the payload. Which client library should I be using?


Solution

  • There is only one client type: KmsClient.

    It can be created in 2 ways:

    1. Using the KmsClientBuilder returned by KmsClient.builder() to modify properties and ultimately do .Build for your customised version of the client - this KmsClientBuilder is an instance of DefaultKmsClientBuilder, which is currently the only class that implements the client builder interface.

    2. Using the KmsClient returned by KmsClient.create(), which is exactly the equivalent (and a shortcut) to new DefaultKmsClientBuilder().build() - this method returns a client set up with the region & credentials already loaded from the respective default provider chain, for applications that don't require further customisation.

    This is how the above looks like in code:

    final KmsClient defaultKmsClient = KmsClient.create();
    final KmsClient alsoDefaultKmsClientButLonger = KmsClient.builder().build();
    final KmsClient customisedKmsClient = KmsClient.builder()
            .region(...)
            .credentialsProvider(...)
            .httpClient(...)
            .endpointOverride(...)
            ...
    

    In conclusion, use KmsClient.create() if you do not require a particular configuration, as the default region and creds should be sufficient in most cases.

    If not, then customise it via an instance of the builder (which can only be accessed via the KmsClient.builder() method since KmsClientBuilder is an interface).

    They are not 'different'.
    The builder ultimately is what creates the client.