Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java HttpClient deadlines: separate connection and request timeouts

Last updated: 5 Oct 20265 min read
tutorial
AdvancedBy AITrove Editorial

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.

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

Java
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
http request and response boundaries
http-connect-request-deadlines
Storage details