Network Programming
Java Networking
ConnectionTimeout
SocketTimeout
Exception Handling

Connection timeout vs socket timeout (read timeout) explained

Codemia Knowledge Hub ·

Connection timeout and socket timeout cover two different phases of a network request. The connection timeout limits how long the client waits to establish the TCP connection (the three-way handshake). The socket timeout limits how long it waits for data once the connection exists. Set both well and a service fails fast on unreachable hosts without dropping requests to servers that are slow but working.

Both usually surface as similar exceptions (typically SocketTimeoutException in Java), which makes them easy to confuse, but they guard against completely different failures.

The phases of a request

 
11. DNS resolution      (resolve hostname to IP)
22. TCP connect          (three-way handshake: SYN, SYN-ACK, ACK)
33. TLS handshake        (if HTTPS)
44. Send request         (write HTTP headers and body)
55. Wait for response    (server processing time)
66. Read response        (receive HTTP headers and body)

The connection timeout covers phase 2 (and, depending on the HTTP client, sometimes phases 1 and 3). The socket timeout covers phases 5 and 6, specifically the gap between data packets.

Connection timeout

The connection timeout is the maximum time to wait for the TCP connection to be established. If the remote server is unreachable, overloaded or firewalled, the handshake stalls and eventually times out.

Java HttpURLConnection

java
1URL url = new URL("https://api.example.com/data");
2HttpURLConnection conn = (HttpURLConnection) url.openConnection();
3conn.setConnectTimeout(3000);  // 3 seconds to establish connection
4conn.setReadTimeout(10000);    // 10 seconds to read response
5conn.connect();

Apache HttpClient 5

java
1RequestConfig config = RequestConfig.custom()
2    .setConnectTimeout(Timeout.ofSeconds(3))
3    .setResponseTimeout(Timeout.ofSeconds(10))
4    .build();
5
6CloseableHttpClient client = HttpClients.custom()
7    .setDefaultRequestConfig(config)
8    .build();

OkHttp (Kotlin/Java)

kotlin
1val client = OkHttpClient.Builder()
2    .connectTimeout(3, TimeUnit.SECONDS)
3    .readTimeout(10, TimeUnit.SECONDS)
4    .writeTimeout(10, TimeUnit.SECONDS)
5    .build()

Python Requests

python
1import requests
2
3# (connect_timeout, read_timeout)
4response = requests.get(
5    "https://api.example.com/data",
6    timeout=(3, 10)  # 3s connect, 10s read
7)

What a connection timeout tells you

  • The server is down or not listening on that port.
  • A firewall is silently dropping SYN packets (no RST comes back).
  • DNS resolved to a wrong or unreachable IP.
  • The server's connection backlog is full and it can't accept new connections.

3 to 5 seconds is a reasonable default. If a handshake takes longer, the server is probably unreachable and waiting more rarely helps.

Socket timeout (read timeout)

The socket timeout, called the read timeout in many libraries, is the maximum wait between consecutive data packets after the connection is up. It does not limit total transfer time; it limits the idle gap.

It is per gap, not per response

This is the most misunderstood part. A 10-second socket timeout does not mean the whole response must arrive within 10 seconds. It means the read fails if 10 seconds pass with no new data.

A large response streaming steadily at 1 byte per second never trips a 10-second socket timeout. A server that goes quiet for 10 seconds trips it, even after sending 99% of the response.

java
1// Server sends data in chunks with pauses
2// Chunk 1 at t=0s, Chunk 2 at t=3s, Chunk 3 at t=6s
3// SocketTimeout of 10s: succeeds (no gap > 10s)
4
5// Server sends Chunk 1 at t=0s, then pauses for 15s
6// SocketTimeout of 10s: fails at t=10s (gap > 10s)

What a socket timeout tells you

  • The server is processing the request and taking too long to answer.
  • The server started responding but stalled mid-stream (garbage collection pause, deadlock, resource exhaustion).
  • Network congestion is causing packet loss and retransmission delays.
  • The server accepted the connection but is neither reading nor writing (a connection leak on the server side).

Timeout settings by library

Library/FrameworkConnection TimeoutSocket/Read TimeoutWrite Timeout
Java HttpURLConnectionsetConnectTimeout(ms)setReadTimeout(ms)N/A
Apache HttpClient 5setConnectTimeout()setResponseTimeout()N/A
OkHttp.connectTimeout().readTimeout().writeTimeout()
Python requeststimeout=(connect, read)timeout=(connect, read)N/A
Go net/httpTransport.DialContext deadlineClient.Timeout (total)Part of Client.Timeout
Node.js (Axios)N/A (OS default)timeout (total)N/A
cURLCURLOPT_CONNECTTIMEOUTCURLOPT_TIMEOUT (total)N/A

Some libraries (Go, Axios, cURL) use a total timeout instead of per-phase timeouts. A total timeout caps the entire request, which is easier to reason about but less precise.

Choosing values

ScenarioConnectionTimeoutSocketTimeout
Internal microservice calls1-3 seconds5-15 seconds
External third-party APIs3-5 seconds15-30 seconds
File downloads / large responses3-5 seconds30-60 seconds
Health checks1-2 seconds2-5 seconds
Database connections2-5 seconds30-60 seconds

Keep the connection timeout shorter

The connection timeout should almost always be shorter than the socket timeout. The TCP handshake is a fixed, fast operation, so if it takes more than a few seconds, waiting longer is pointless. Once connected, though, the server may legitimately need more time to run a complex query, build a report or stream a large dataset.

java
1// Good: fast connect, patient read
2config.setConnectTimeout(3000);
3config.setReadTimeout(30000);
4
5// Bad: patient connect, fast read
6config.setConnectTimeout(30000);  // Why wait 30s for a handshake?
7config.setReadTimeout(3000);      // Server barely has time to process

Retries and timeouts

A connection timeout is usually safe to retry right away against another server instance, because the request was never received. A socket timeout is riskier to retry, because the server may already be processing the request.

python
1import requests
2from requests.adapters import HTTPAdapter
3from urllib3.util.retry import Retry
4
5session = requests.Session()
6retry = Retry(
7    total=3,
8    backoff_factor=0.5,
9    status_forcelist=[502, 503, 504],
10    allowed_methods=["GET", "HEAD"],  # Only retry idempotent methods
11)
12adapter = HTTPAdapter(max_retries=retry)
13session.mount("https://", adapter)
14
15response = session.get(
16    "https://api.example.com/data",
17    timeout=(3, 10),
18)

For non-idempotent operations (POST, PUT), retrying after a socket timeout risks duplicate processing. Use idempotency keys or check the operation's status before retrying.

Connection pool timeout

Many HTTP clients add a third timeout: how long to wait for a connection from the pool. It is separate from the connection timeout (TCP) and the socket timeout (data):

java
1// Apache HttpClient: connection pool timeout
2PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
3cm.setMaxTotal(100);
4cm.setDefaultMaxPerRoute(20);
5
6RequestConfig config = RequestConfig.custom()
7    .setConnectTimeout(Timeout.ofSeconds(3))
8    .setConnectionRequestTimeout(Timeout.ofSeconds(1))  // Pool wait
9    .setResponseTimeout(Timeout.ofSeconds(10))
10    .build();

When every pooled connection is busy, a new request waits up to connectionRequestTimeout for one to free up. If this timeout fires, the pool is usually too small or downstream services are slow.

Mistakes to avoid

  • Same value for both timeouts. The connection timeout should be much shorter. A 30-second connection timeout wastes time on unreachable hosts.
  • Zero or no timeout. The client then waits forever. On a server handling concurrent requests, one stuck downstream call can exhaust the thread pool and cascade into a full outage. Configure both timeouts on every outbound call in production.
  • Treating the socket timeout as a total request timeout. It resets with every packet, so a slow but continuous stream won't trigger it even if the transfer takes minutes.
  • Retrying non-idempotent requests after a socket timeout. The timeout only means the client didn't get the response, not that the server didn't act.
  • Ignoring the pool timeout. Under load, requests can time out waiting for a pooled connection rather than for the network. The symptoms look alike, but the fix (a bigger pool or lower downstream latency) differs.
  • Not logging which timeout fired. Both throw SocketTimeoutException in Java. Log the phase (connect vs. read) so you can tell "server unreachable" from "server too slow" in production.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design