HttpClient.connectTimeout bounds connection establishment; HttpRequest.timeout bounds the request's response wait. Neither replaces an overall business deadline that spans retries, parsing, and downstream work.
Java HttpClient deadlines: separate connection and request timeouts
Operational contract
Create a reusable client with a connection timeout and a request with its own timeout. The client default for redirects is NEVER, but this example states that policy explicitly so the owner sees it beside the deadlines. A connection reused from a pool may not establish a new connection, so the connection setting is not the only timer that matters. On a timeout, classify the attempt as uncertain if the server may already have processed a mutation. The outer retry policy must subtract elapsed time from one operation budget.
Failure case
A warehouse lookup allows 47 seconds end to end. Three attempts each allowed 47 seconds could exceed that budget even before the sleeps between attempts. The factory below sets per-attempt limits; its caller still needs a clock-based overall deadline and must avoid retrying a non-idempotent write without a deduplication rule.
Java code
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.time.Duration;
public class WarehouseHttpDeadlines {
public static HttpClient client() {
return HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(3))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
public static HttpRequest lookup(URI inventoryUri) {
if (!"https".equalsIgnoreCase(inventoryUri.getScheme())) {
throw new IllegalArgumentException("HTTPS inventory URI required");
}
return HttpRequest.newBuilder(inventoryUri)
.timeout(Duration.ofSeconds(7))
.GET()
.build();
}
}Performance and ownership cost
Builder work is O(1) relative to payload size. Reuse one client rather than rebuilding it for every call so connections can be reused. Timeouts bound waiting in specific phases; they do not cap the total cost of multiple attempts or downstream processing.
Common Mistakes
- Do not multiply a full business budget across retries.
- Do not assume connectTimeout applies to a reused connection.
- Do not interpret a write timeout as proof the server made no change.
Connected lessons
- Java HttpClient: request policy, deadlines, and response size
- Java HTTP retry project: bounded attempts and one wait budget
- Java cancellation: timed waits and cooperative interruption
- Java HTTP query values: encode data without changing URI structure
- Java HttpClient redirects: check the next origin before resending
- Java streaming HTTP bodies: close the stream and cap retained bytes
- Java Retry-After: parse a bounded server delay without inventing a retry
- Java HttpClient cookies: make session storage an owned policy
- Java HTTP and fork/join decisions quiz
- Advanced Java
