Enabling exponential backoff in the AWS SDK v2 for Java

Originally posted on 2020-11-10

The AWS SDKs support exponential backoff so you don't have to implement it yourself. What most people don't realize is that exponential backoff needs to be turned on, at least in the v2 Java SDK, so often I run into applications getting a throttled exception and immediately exiting. Or even worse I encounter a whole lot of code set up to do throttling manually. I'm guilty of this myself sometimes!

How do you set up exponential backoff in the AWS SDK v2 for Java quickly? This is an example of enabling exponential backoff when using the price list API:

RetryPolicy retryPolicy = RetryPolicy.builder()
    .numRetries(10)
    .backoffStrategy(BackoffStrategy.defaultStrategy())
    .build();
ClientOverrideConfiguration clientOverrideConfiguration = ClientOverrideConfiguration.builder()
    .retryPolicy(retryPolicy)
    .build();
PricingClient pricingClient = PricingClient.builder()
    .overrideConfiguration(clientOverrideConfiguration)
    .build();

You can do this for any other API as well. You just need to tell the builder to override the configuration with the ClientOverrideConfiguration that specifies a RetryPolicy. I opted for a simple backoff strategy and 10 retries.

So you don't have to go searching for the imports on your own here they are: