Skip to content
javahacks.dev
Debugging

How to Debug Network and Timeout Issues in Java Clients

Debug Java HTTP client timeouts: separate connect, read and pool wait, check DNS and TLS, set explicit limits and log what each phase did.

5 min read
Summarize in AI
Flat illustration of a magnifier over lines of a log, with the OpenJDK, Spring, Apache Maven and JUnit5 logos.

A timeout is a symptom with several different causes. The first job is to name the phase that failed. This post uses java.net.http.HttpClient on JDK 25, and the reasoning applies to Spring RestClient and Apache HttpClient.

Name the phase

MessagePhase
UnknownHostExceptionDNS
ConnectException: Connection refusedNothing is listening, or a firewall rejects
HttpConnectTimeoutExceptionTCP connect did not complete
SSLHandshakeExceptionTLS negotiation
HttpTimeoutException: request timed outWaiting for a response
Pool "timeout waiting for connection"Client side, not network

Set explicit limits

java
HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(2))
        .build();

HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.example.com/orders"))
        .timeout(Duration.ofSeconds(5))
        .GET()
        .build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

The connect timeout covers the TCP and TLS setup. The request timeout covers the time until the response headers arrive, and a slow body needs its own handling. Defaults are infinite in many clients, which turns a stuck dependency into a stuck thread pool, as in Spring read timeouts.

Compare with curl

Run the same call from the same host:

Shell
curl -s -o /dev/null -w 'dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} first_byte=%{time_starttransfer} total=%{time_total}\n' https://api.example.com/orders

If curl is fast and Java is slow, the problem is in the JVM: DNS caching settings, a proxy configured only for Java, or a certificate store difference. If both are slow, the server or network is the cause.

Wire logging

For the JDK client:

Shell
java -Djdk.httpclient.HttpClient.log=errors,requests,headers,frames:control -jar app.jar

For Apache and Spring clients, raise the logger of the client package to DEBUG temporarily. Logging bodies in production leaks data, so keep that off.

Pool exhaustion

A connection pool that runs dry produces timeouts that look like a slow server. The cause is a response not closed, so the connection is never returned. The pattern matches JDBC connection leaks: find the unclosed resource, not a bigger pool.

DNS and TLS

The JVM caches successful DNS lookups. If an address changes behind a load balancer, networkaddress.cache.ttl in the security properties controls how long an old address is used. TLS failures often come from a missing intermediate certificate, which is the PKIX path building failure.

Retries

Retry only when the call is safe to repeat, with exponential backoff and a cap. A retry on a non-idempotent POST creates duplicates unless you add an idempotency key.

Reading the exception for what it says

Java's network exceptions are more specific than they look, and the exact class is the first clue. A ConnectException: Connection refused means the host answered and nothing listens on that port: wrong port, service down or a firewall that rejects actively. A ConnectException with a timeout message means packets vanished, usually a firewall that drops silently or a routing problem. A SocketTimeoutException: Read timed out means the connection was made and the server did not send data in time, so the server is slow or hung. A SocketException: Connection reset means the peer closed the connection abruptly, often a proxy or load balancer with an idle timeout shorter than yours, or a server that crashed mid-response. Each leads to a different next step, and reading the message first saves an hour of guessing.

The idle connection that dies quietly

A pooled client keeps connections open for reuse, and a load balancer or firewall between you and the server may close idle connections after a fixed period, commonly somewhere between a minute and a few minutes. The client does not learn about it until it tries to use the connection, and then the first request after a quiet period fails with a reset or an NoHttpResponseException, while the next one works. The fix is to make the pool's idle timeout shorter than the infrastructure's, evict idle connections, and enable a validate-after-inactivity check. If your errors cluster after quiet periods, such as the first request each morning, this is the cause nine times out of ten.

Measuring where the time goes

Add timing to the client so the log tells you which phase is slow: DNS resolution, TCP connect, TLS handshake, time to first byte and body transfer. With curl, the -w format string prints each of these as numbers, and a single run against the failing URL from the failing machine usually points at one phase. Run it from the same host or container as the Java process, since a laptop on a different network answers a different question. If curl is fast and Java is slow, the difference is in your client settings, such as a proxy configuration, a stale DNS cache or a pool that is exhausted.

Timeouts that match the caller

Every call should have a connect timeout and a read timeout, and the overall deadline should be shorter than whatever called you. If your endpoint promises an answer in two seconds and calls a service with a thirty-second default timeout, the user sees a failure at two seconds and your thread keeps waiting for twenty-eight more. Set the timeouts from the budget downward, and fail fast. Add a circuit breaker only after the basic limits are right, since a breaker on top of missing timeouts hides the problem instead of solving it.

A short runbook

When a timeout alert fires, follow the same steps in order. Find which phase is slow, from client metrics or a curl run on the same host. Check whether the problem is one target or all of them, which separates a server problem from a network or client one. Look at the pool, for exhausted connections and threads waiting. Check DNS for the name in question from inside the container. Only then change a setting. Writing the runbook down once means that the person on call at night follows a procedure, and does not rediscover it under stress.

Capture the traffic when logs are not enough

If the client logs and curl disagree with what you believe, capture packets with tcpdump on the host, or use a proxy such as mitmproxy for HTTP traffic you can decrypt. A capture settles questions that no log can: whether the request left the machine, whether the server replied, who closed the connection first, and how long each step took on the wire.

Where this does not apply

If the failure only happens under load, collect thread dumps first, since exhausted server threads look identical from outside. The HttpClient documentation and the curl manual on timing list the options used here.

Also inSpring MVC
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.