Sub topic 18
Retries and backoff: what you must build yourself
This chapter assumes you know how to send requests with send and sendAsync. It also assumes you can catch the checked exceptions from the previous chapters and have used CompletableFuture. The java.net.http.HttpClient has no retry feature. Nothing in the builder, the request or the response replays a failed call. If a server answers 503 or a connection drops, you get that result once, and any retry is code you write.
Deciding what is worth retrying
A retry helps only when the failure is probably temporary and repeating the request is safe. Applying a retry rule to every failure wastes time and can cause damage.
| Outcome | Retry? | Reason |
|---|---|---|
| `200`-`299` | No | The call succeeded. |
| `400`, `401`, `403`, `404`, `422` | No | The request itself is wrong. Sending it again gives the same answer. |
| `429 Too Many Requests` | Yes, after waiting | The server is rate limiting you. It may send a `Retry-After` header. |
| `502`, `503`, `504` | Yes | The server or a gateway in front of it is temporarily unavailable. |
| `500` | Sometimes | Often a bug that repeats. Retry only if you know the API treats it as transient. |
| `HttpTimeoutException`, `ConnectException` | Yes | The network or server was slow or unreachable. |
| `InterruptedException` | No | Someone asked your thread to stop. Let it propagate. |
The second question is whether the request is safe to repeat. GET, HEAD, PUT, DELETE and OPTIONS are idempotent by definition, so sending them twice has the same effect as sending them once. POST is not. If a POST times out, the server may have already created the item, and a retry can create a duplicate. Retry POST only when the API supports an idempotency key, which is a unique value you send in a header so the server can recognize a repeat.
Backoff and jitter
If a server is overloaded and every client retries immediately, the retries add to the overload. Backoff means waiting longer after each failure. Exponential backoff doubles the wait: 200 ms, 400 ms, 800 ms and so on, up to a maximum.
Many clients that fail together will also retry together, in synchronized waves. Jitter adds randomness to break this up. The "full jitter" strategy picks a random delay between zero and the exponential cap. It is simple and spreads load well.
When the server sends a Retry-After header with a number of seconds, prefer it over your own calculation. That header can also contain an HTTP date. The code below ignores that form and falls back to backoff.
A synchronous retry wrapper
The class below wraps a shared HttpClient. It retries only idempotent methods, uses full jitter, honors Retry-After (capped at maxDelay), and lets InterruptedException escape.
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.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class RetryingSender {
private static final Set<Integer> RETRYABLE_STATUSES = Set.of(429, 502, 503, 504);
private static final Set<String> IDEMPOTENT_METHODS =
Set.of("GET", "HEAD", "PUT", "DELETE", "OPTIONS");
private final HttpClient client;
private final int maxAttempts;
private final Duration baseDelay;
private final Duration maxDelay;
public RetryingSender(HttpClient client, int maxAttempts,
Duration baseDelay, Duration maxDelay) {
this.client = client;
this.maxAttempts = maxAttempts;
this.baseDelay = baseDelay;
this.maxDelay = maxDelay;
}
public HttpResponse<String> send(HttpRequest request)
throws IOException, InterruptedException {
int attempts = IDEMPOTENT_METHODS.contains(request.method()) ? maxAttempts : 1;
for (int attempt = 1; ; attempt++) {
Duration delay;
try {
HttpResponse<String> response =
client.send(request, HttpResponse.BodyHandlers.ofString());
if (!RETRYABLE_STATUSES.contains(response.statusCode())
|| attempt >= attempts) {
return response;
}
delay = delayFor(attempt, response);
} catch (IOException e) {
if (attempt >= attempts) {
throw e;
}
delay = backoff(attempt);
}
Thread.sleep(delay.toMillis());
}
}
public CompletableFuture<HttpResponse<String>> sendAsync(HttpRequest request, int attempt) {
int attempts = IDEMPOTENT_METHODS.contains(request.method()) ? maxAttempts : 1;
return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.handle((response, error) -> {
boolean retry = attempt < attempts
&& (error != null
|| RETRYABLE_STATUSES.contains(response.statusCode()));
if (!retry) {
return error == null
? CompletableFuture.completedFuture(response)
: CompletableFuture.<HttpResponse<String>>failedFuture(error);
}
Duration delay = error == null ? delayFor(attempt, response) : backoff(attempt);
Executor later = CompletableFuture.delayedExecutor(
delay.toMillis(), TimeUnit.MILLISECONDS);
return CompletableFuture.supplyAsync(() -> null, later)
.thenCompose(ignored -> sendAsync(request, attempt + 1));
})
.thenCompose(future -> future);
}
private Duration delayFor(int attempt, HttpResponse<?> response) {
return response.headers().firstValue("Retry-After")
.map(String::trim)
.flatMap(RetryingSender::parseSeconds)
.map(seconds -> Duration.ofSeconds(seconds))
.map(d -> d.compareTo(maxDelay) > 0 ? maxDelay : d)
.orElseGet(() -> backoff(attempt));
}
private static java.util.Optional<Long> parseSeconds(String value) {
try {
return java.util.Optional.of(Long.parseLong(value));
} catch (NumberFormatException e) {
return java.util.Optional.empty(); // HTTP-date form: fall back to backoff
}
}
private Duration backoff(int attempt) {
long exponential = baseDelay.toMillis() << Math.min(attempt - 1, 20);
long cap = Math.min(maxDelay.toMillis(), exponential);
return Duration.ofMillis(ThreadLocalRandom.current().nextLong(cap + 1));
}
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.build();
RetryingSender sender = new RetryingSender(
client, 4, Duration.ofMillis(200), Duration.ofSeconds(5));
HttpRequest request = HttpRequest.newBuilder(URI.create("https://example.com/"))
.timeout(Duration.ofSeconds(5))
.GET()
.build();
HttpResponse<String> response = sender.send(request);
System.out.println("sync: " + response.statusCode());
System.out.println("async: " + sender.sendAsync(request, 1).join().statusCode());
}
}How the code behaves
- Timeouts are retried through
IOException.HttpTimeoutExceptionandHttpConnectTimeoutExceptionboth extendIOException, so the singlecatch (IOException e)covers them. This is broad. It also retries failures such as a TLS handshake error, which will never succeed. For stricter control, test the exception type inside the catch block and rethrow the ones you do not want to retry. - The last result is returned, not hidden. On the final attempt, a
503is returned as a normal response so the caller can inspect it. A finalIOExceptionis rethrown. - The request object is reused.
HttpRequestis immutable, so sending it again is fine. The body is replayed only if the publisher supports it.BodyPublishers.ofStringandofByteArraycan be read again.BodyPublishers.ofInputStreamreads from the supplier each time, so the supplier must return a fresh stream on every call. - Async waiting uses no thread.
CompletableFuture.delayedExecutorschedules the next attempt after the delay. The code does not callThread.sleepon a pool thread. Thehandlestage produces a future, andthenCompose(future -> future)flattens it. - Interruption is never swallowed. The synchronous method does not catch
InterruptedException. A thread asked to stop leaves the loop immediately, even in the middle of a backoff sleep.
Limits you should still set
Attempts times timeout can grow large. With four attempts, a 10-second request timeout and delays up to 5 seconds, the worst case is about 55 seconds. Decide on a total time budget and pass it into your loop. Stop retrying when the deadline would pass, even if attempts remain. Also check whether a gateway, a load balancer or a library above you already retries. Retries stack, and three layers of three attempts each send up to 27 requests.
Use a library such as Resilience4j if you need circuit breakers, which stop calls to a failing service for a period, or bulkheads, which limit concurrent calls. For a single API client, a small wrapper like the one above is usually enough.
Exercise
A client sends POST /orders with a JSON body. The call throws HttpTimeoutException after 10 seconds. The wrapper above has maxAttempts set to 4. How many times does it send the request, and why? What would you add so that retrying becomes safe?
Show answer
It sends the request once. POST is not in IDEMPOTENT_METHODS, so attempts is set to 1, and the timeout exception is rethrown. The server may have created the order before the response was lost, so a blind retry could create a duplicate. To make retries safe, send an idempotency key header, with the same unique value on every attempt, if the API supports one, and then allow POST for that request.
Exercise
The server answers 429 with the header "Retry-After: 120", and the sender is built with maxDelay of 5 seconds. How long does the code wait before the next attempt, and what is the trade-off of that choice?
Show answer
It waits 5 seconds. delayFor reads the 120 seconds, then caps it at maxDelay. The trade-off is that the client retries earlier than the server asked, so it may get another 429 and use up an attempt. Raising maxDelay respects the server more closely but makes the caller wait longer, so a total deadline should limit the overall time.