Sub topic 17
Retries and backoff: what you must build yourself
Assume you know Java 11 syntax, HTTP status codes, checked exceptions, and basic HttpClient usage. This chapter focuses on resilience: deciding when to retry a failed request and how long to wait.
HttpClient does not provide automatic retries. A call to send returns an HttpResponse for HTTP failures such as 429 Too Many Requests or 503 Service Unavailable. Network failures and timeouts arrive as exceptions. Your application must classify both kinds of failure.
Decide whether a retry is safe
Retrying repeats the operation. Repeating a GET is usually safe because it should only read data. Repeating a POST can create duplicate records unless the server supports an idempotency key. An operation is idempotent when repeating it has the same intended effect as performing it once.
| Failure | Common retry decision |
|---|---|
| `429` or `503` | Retry after a delay |
| Other `5xx` | Often retry, depending on the service |
| `400` or `401` | Do not retry without changing the request |
| Connection timeout | Retry only when the operation is safe |
A retry policy normally includes a maximum attempt count, a delay, and a list of retryable failures.
Exponential backoff with jitter
Exponential backoff increases the delay after each failed attempt. Jitter adds a random amount so many clients do not retry simultaneously.
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
public class RetryingGet {
static HttpResponse<String> sendWithRetry(
HttpClient client, HttpRequest request, int maxAttempts)
throws IOException, InterruptedException {
IOException lastException = null;
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
try {
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
int status = response.statusCode();
if (status >= 200 && status < 300) {
return response;
}
boolean retryable = status == 429 || status >= 500;
if (!retryable || attempt == maxAttempts) {
return response;
}
} catch (IOException e) {
lastException = e;
if (attempt == maxAttempts) {
throw e;
}
}
long baseDelay = 200L * (1L << (attempt - 1));
long jitter = ThreadLocalRandom.current().nextLong(100);
Thread.sleep(Math.min(baseDelay + jitter, 5_000L));
}
throw lastException;
}
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
HttpResponse<String> response =
sendWithRetry(client, request, 4);
System.out.println(response.statusCode());
}
}The policy retries selected statuses and IOException, but returns non-retryable responses immediately. It also stops after four attempts. In production, cap the total time spent retrying and log the final failure with request context.
Asynchronous retries
With sendAsync, each retry must begin in a later CompletableFuture stage, usually after a scheduled delay. Avoid calling Thread.sleep inside an asynchronous callback because it blocks the callback thread. A ScheduledExecutorService can complete a future after the backoff delay.
Exercise
Why should a client avoid automatically retrying every POST request?
Show answer
Repeating a POST can perform the side effect twice, such as creating duplicate records. Retry it only when the operation is known to be safe or uses an idempotency mechanism.