BackendBench
Coffee

Home โ€บ Java exceptions โ€บ SocketTimeoutException

Checked exception ยท java.net

SocketTimeoutException: causes and fixes

A network read or connect took longer than the configured timeout.

What it looks like

java.net.SocketTimeoutException: Read timed out

Extends InterruptedIOException in java.net.

What it means

Two messages share the class: Connect timed out (the TCP connection was not established in time) and Read timed out (the connection was open but no data arrived in time). The first points at network reachability, firewalls or a wrong address; the second means the remote service is slow or stuck. Both usually mean the timeout you set (or the default, which may be infinite) is shorter than the other side needs.

Common causes

How to fix it

  1. Set explicit connect and read timeouts on every client (RestClient, WebClient, HttpClient, JDBC) and make them deliberate.
  2. Tell connect from read: connect means check network paths and DNS; read means check the remote service.
  3. Add retries only for idempotent calls and with backoff, and use circuit breakers to protect threads.
  4. Measure the remote latency before raising a timeout.

Broken and fixed

fails
HttpClient client = HttpClient.newHttpClient(); // no connect timeout, no request timeout
works
HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(3)).build();
HttpRequest req = HttpRequest.newBuilder(uri)
        .timeout(Duration.ofSeconds(10)).build();

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Spring's RestTemplate and RestClient have no timeouts by default unless the underlying request factory sets them. Always configure them.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is SocketTimeoutException a checked or unchecked exception?

SocketTimeoutException is a checked exception (it extends InterruptedIOException), so the compiler forces you to catch it or declare it with throws.

Which package is SocketTimeoutException in?

It lives in java.net, so the import is import java.net.SocketTimeoutException;.

What is the first thing to check when I see SocketTimeoutException?

Read the message and the first stack trace line in your own code. The usual causes are: A slow downstream service or a long query behind the endpoint; and A firewall or security group silently dropping packets, which looks like a connect timeout.

Related exceptions

More tools you might need