Java Concurrency Program · CD12
Retry with Exponential Backoff in Java
Retrying at once hammers a service that is already struggling. Doubling the wait after each failure gives it time to recover.
Problem Statement
Write retry(call, maxAttempts, baseDelayMs). It returns the first successful result, waiting base, 2 × base, 4 × base, and so on between attempts.
After maxAttempts failures, throw an exception that keeps the last error. For testing, the sleeping must be replaceable.
Input/Output Examples
fails twice, then OK; base 100OutputOK on attempt 3, waited [100, 200]Explanation: two failures, two waits.always fails; 4 attemptsOutputwaited [100, 200, 400]Explanation: no wait after the final attempt.OK at onceOutputwaited []Explanation: success needs no delay.Visual Explanation
- Attempt 1resultfailwait 100 ms retry
- Attempt 2resultfailwait 200 ms retry
- Attempt 3resultOKreturn the value success
- DoneOK after 300 ms of waiting
The programs record the delays instead of sleeping, through a small Sleeper interface. That makes the output exact and the tests fast.
Approaches
Both approaches produce the same delays. The first is a loop; the second is recursive.
Approach 1: Retry Loop (Recommended)
Idea: loop from 1 to maxAttempts; on failure, sleep for base << (attempt - 1) unless it was the last attempt.
- Try the call and return its result on success.
- Remember the exception on failure.
- Sleep for the doubled delay if attempts remain.
- After the loop, throw an exception with the last error as its cause.
Time: O(a) · Space: O(1). a is the number of attempts, not counting the time spent waiting.
Approach 2: Recursive Retry
Idea: try once; on failure, sleep and call yourself with the attempt number plus one and the delay doubled.
- Try the call.
- If it fails on the last attempt, throw.
- Otherwise sleep for the current delay and recurse with
delay * 2.
Time: O(a) · Space: O(a).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Retry Loop (Recommended)
Easy to read and to extend with jitter or a maximum delay.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class RetryLoop {
interface Sleeper {
void sleep(long ms) throws InterruptedException;
}
// Try, and on failure wait 100, 200, 400, ... ms before the next try, up to maxAttempts
static <T> T retry(Callable<T> call, int maxAttempts, long baseDelayMs, Sleeper sleeper) throws Exception {
Exception last = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
return call.call();
} catch (Exception e) {
last = e;
if (attempt < maxAttempts) {
sleeper.sleep(baseDelayMs << (attempt - 1)); // doubles every time
}
}
}
throw new Exception("failed after " + maxAttempts + " attempts: " + last.getMessage(), last);
}
public static void main(String[] args) throws Exception {
List<Long> slept = new ArrayList<>();
Sleeper recorder = slept::add; // records delays instead of really sleeping
int[] attempts = {0};
Callable<String> flaky = () -> {
attempts[0]++;
if (attempts[0] <= 2) {
throw new IllegalStateException("service unavailable");
}
return "OK";
};
System.out.println("result: " + retry(flaky, 5, 100, recorder) + " on attempt " + attempts[0]);
System.out.println("waited (ms): " + slept);
slept.clear();
Callable<String> broken = () -> { throw new IllegalStateException("always down"); };
try {
retry(broken, 4, 100, recorder);
} catch (Exception e) {
System.out.println("gave up: " + e.getMessage());
}
System.out.println("waited (ms): " + slept);
}
}
result: OK on attempt 3 waited (ms): [100, 200] gave up: failed after 4 attempts: always down waited (ms): [100, 200, 400]
Time complexity: O(a) · Space complexity: O(1).
Approach 2: Recursive Retry
Compact, but uses a stack frame per attempt, which is fine for a handful of retries.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class RetryRecursive {
interface Sleeper {
void sleep(long ms) throws InterruptedException;
}
static <T> T retry(Callable<T> call, int maxAttempts, long baseDelayMs, Sleeper sleeper) throws Exception {
return attempt(call, 1, maxAttempts, baseDelayMs, sleeper);
}
// Each failed attempt sleeps for the current delay and recurses with the delay doubled
private static <T> T attempt(Callable<T> call, int n, int max, long delay, Sleeper sleeper) throws Exception {
try {
return call.call();
} catch (Exception e) {
if (n == max) {
throw new Exception("failed after " + max + " attempts: " + e.getMessage(), e);
}
sleeper.sleep(delay);
return attempt(call, n + 1, max, delay * 2, sleeper);
}
}
public static void main(String[] args) throws Exception {
List<Long> slept = new ArrayList<>();
Sleeper recorder = slept::add; // records delays instead of really sleeping
int[] attempts = {0};
Callable<String> flaky = () -> {
attempts[0]++;
if (attempts[0] <= 2) {
throw new IllegalStateException("service unavailable");
}
return "OK";
};
System.out.println("result: " + retry(flaky, 5, 100, recorder) + " on attempt " + attempts[0]);
System.out.println("waited (ms): " + slept);
slept.clear();
Callable<String> broken = () -> { throw new IllegalStateException("always down"); };
try {
retry(broken, 4, 100, recorder);
} catch (Exception e) {
System.out.println("gave up: " + e.getMessage());
}
System.out.println("waited (ms): " + slept);
}
}
result: OK on attempt 3 waited (ms): [100, 200] gave up: failed after 4 attempts: always down waited (ms): [100, 200, 400]
Time complexity: O(a) · Space complexity: O(a).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Retry Loop | O(a) | O(1) |
| Recursive Retry | O(a) | O(a) |
The work is one call per attempt. The total waiting time is base × (2a-1 - 1) for a attempts, so it grows quickly.
Interview Tips and Recommended Approach
- Add jitter in production. A random part of the delay stops many clients from retrying at the same moment.
- Cap the delay so a long outage does not produce waits of minutes.
- Retry only safe failures. Timeouts and 503s are good candidates; a validation error will fail again.
- Make the call idempotent, or a retried payment may be charged twice.
Recommended Approach: Retry Loop
Why: a loop is easy to read and test, and it is where jitter, a delay cap and per-exception rules are simplest to add.