Bob Chesley

Bob Chesley's Blog

Java exponential backoff and retry

Bob Chesley,softwarejava

Exponential backoff and retry in a Java API call

Here's an example of a Java method that makes an API call with exponential backoff and retry, allowing you to specify the number of tries before throwing an error:

import java.io.IOException;
 
public class ApiCaller {
    private static final int MAX_RETRIES = 3;
    private static final long INITIAL_BACKOFF_DELAY = 1000; // 1 second
 
    public void makeApiCallWithRetry(String url) throws IOException {
        int numTries = 0;
        long backoffDelay = INITIAL_BACKOFF_DELAY;
 
        while (numTries < MAX_RETRIES) {
            try {
                makeApiCall(url);
                return; // API call succeeded, exit the method
            } catch (IOException e) {
                numTries++;
                if (numTries >= MAX_RETRIES) {
                    throw e; // Max retries exceeded, throw the exception
                }
                System.out.println("API call failed. Retrying in " + backoffDelay + " milliseconds...");
                waitBeforeRetry(backoffDelay);
                backoffDelay *= 2; // Exponential backoff: double the delay
            }
        }
    }
 
    private void makeApiCall(String url) throws IOException {
        // Your API call implementation here
    }
 
    private void waitBeforeRetry(long backoffDelay) {
        try {
            Thread.sleep(backoffDelay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

In this example, the makeApiCallWithRetry method takes a url parameter and attempts to make an API call. If the call fails due to an IOException, it will retry the call with exponential backoff, up to a maximum of MAX_RETRIES times. After each failed attempt, it waits for the specified backoffDelay (which doubles after each failure) before retrying.

You can adjust the MAX_RETRIES constant and INITIAL_BACKOFF_DELAY value according to your requirements. The makeApiCall method should be implemented with your actual API call logic.

Please note that this implementation uses the Thread.sleep method to pause the execution before retrying, which may not be suitable for all scenarios. Consider using a more advanced library or framework if you need additional features or customization.