skip to content

What do OkHttp's connectTimeout, readTimeout, writeTimeout and callTimeout each bound, and which one makes a call to a slow API fail fast?

level: middleimportance: must knowfreq 62%

answer

  1. three per-operation, one per-call
  2. ten seconds versus zero
  3. a gap between bytes, not a total
  4. the whole call, retries included

basics

~20 s

connectTimeout bounds opening a TCP connection; readTimeout and writeTimeout bound each socket read or write; all default to 10 seconds. callTimeout bounds the whole call, retries included, defaults to no limit, and is what makes calls fail fast.

solid answer

~40 s

OkHttp has three per-operation timeouts and one per-call timeout. `connectTimeout` applies while connecting the TCP socket; `readTimeout` applies to each individual read, including reads of the response body, and `writeTimeout` to each individual write; all three default to **10 seconds**. Because they bound a single operation, a server that trickles a byte every few seconds never trips them. `callTimeout` spans the entire call: DNS, connecting, writing the body, server processing, reading the body, and every redirect or retry inside the call. It defaults to **0, no limit**, so a slow API only fails fast once you set it, on the client, on one call with `call.timeout()`, or on a derived client. When it fires, OkHttp cancels the call and the caller gets an `InterruptedIOException` with the message `timeout`.

code

kotlin · 19 lines
kotlin
import java.util.concurrent.TimeUnit
import okhttp3.OkHttpClient
import okhttp3.Request

val client = OkHttpClient.Builder()
  .connectTimeout(5, TimeUnit.SECONDS)
  .readTimeout(10, TimeUnit.SECONDS)
  .writeTimeout(10, TimeUnit.SECONDS)
  .callTimeout(15, TimeUnit.SECONDS)
  .build()

fun searchCode(query: String): Int {
  val request = Request.Builder()
    .url("https://api.example.com/search?q=$query")
    .build()
  val call = client.newCall(request)
  call.timeout().timeout(3, TimeUnit.SECONDS) // this call only
  return call.execute().use { response -> response.code }
}

go deeper

for a junior

Recall the four names and the defaults: 10 seconds for connect, read and write, and no call timeout unless you set one.

for a middle

Explain why a per-read timeout never bounds total latency and how callTimeout covers redirects and retries inside one call.

for a senior

Show how silent retries multiply worst-case latency, why queued async calls start their call timeout late, and how you'd scope deadlines per endpoint.

for a principal

Decide the client-wide defaults a team ships, which endpoints get their own deadline, and where retries of non-idempotent requests must be disabled.

## Four timeouts, two kinds OkHttp's `OkHttpClient.Builder` exposes four timeouts. Three bound a **single I/O operation**; one bounds the **whole call**. | Setting | What it bounds | Default | |---|---|---| | `connectTimeout` | connecting a TCP socket to the target host | 10 seconds | | `readTimeout` | each individual read on the socket, including reads of the response body's `Source` | 10 seconds | | `writeTimeout` | each individual write, such as a chunk of the request body | 10 seconds | | `callTimeout` | the entire call from DNS to the last byte of the body, redirects and retries included | 0, meaning no timeout | For every one of them a value of 0 means no timeout; otherwise the value must fit in a positive `Int` of milliseconds. ## Why the per-operation timeouts don't make a call fast The read timeout is easy to misread as "the response must arrive within 10 seconds". It actually limits **how long one read may wait for data**. A server that sends a byte every 8 seconds keeps a call alive indefinitely with the defaults, and a large download over a slow but steady connection can take minutes without ever tripping it. The same holds for writes of a large upload. The connect timeout is narrower still: it covers establishing the TCP connection, not the server's processing time. Once a request is written, waiting for the first response byte is a read, governed by the read timeout. These limits are still worth tuning: a short connect timeout stops a call from hanging on an unreachable address, and a read timeout catches a server that has stopped sending altogether. They just don't bound total latency. ## The call timeout `callTimeout` was added in OkHttp 3.12 as a **full-operation timeout**. It covers resolving DNS, connecting, writing the request body, server processing and reading the full response body, and if the call follows redirects or retries, all of them must finish within the one period. When it expires OkHttp cancels the call: an in-flight read or write fails, and the caller receives an `InterruptedIOException` whose message is `timeout`. Ways to set it: - **Client default**: `OkHttpClient.Builder().callTimeout(15, TimeUnit.SECONDS)`. - **One call**: `call.timeout().timeout(3, TimeUnit.SECONDS)` before executing or enqueueing it. - **A family of calls**: a client derived with `sharedClient.newBuilder().callTimeout(...)`, which keeps the shared pool and dispatcher. An application interceptor can also shorten the per-operation timeouts for one request with `chain.withReadTimeout()` and its siblings. ## Retries and other details that change the arithmetic - **Silent retries.** `retryOnConnectionFailure` defaults to `true`. OkHttp then recovers from an unreachable IP address by trying the host's next address, from a stale pooled connection by opening a new one, and from an unreachable proxy by trying the next. Each route attempt can spend its own connect timeout, and each redirect is another full exchange, so worst-case latency is a multiple of the per-operation limits. The call timeout is the only setting that caps the total. - **Non-idempotent requests.** Those retries can resend a request that has a body unless the body is one-shot. The builder's documentation advises setting `retryOnConnectionFailure(false)` when a retry would be destructive, and doing your own recovery. - **Queued asynchronous calls.** For a call made with `enqueue()`, the call timeout starts when the dispatcher actually runs the call, not when it was enqueued, so time spent waiting for a dispatcher slot is not counted. - **Exceptions.** A connect or read that times out typically surfaces as a `SocketTimeoutException`, a subclass of `InterruptedIOException`; the call timeout surfaces as an `InterruptedIOException` with the message `timeout`. Code that catches `IOException` sees all of them. ## Putting it together for a slow API For a client that must fail fast, keep the per-operation timeouts as guards against dead connections and set a call timeout that matches the screen's patience: 1. Set `callTimeout` on the shared client to the longest any call should take. 2. Give the few slow endpoints their own deadline with `call.timeout()` or a derived client, rather than raising the default for everyone. 3. Decide whether non-idempotent requests should be retried at all, and turn `retryOnConnectionFailure` off on a derived client if not.

  • How do you give one endpoint a shorter deadline without building a second client from scratch?
    Three options keep the shared pool and dispatcher. Set `call.timeout().timeout(...)` on that one call before running it. Derive a client with `sharedClient.newBuilder().callTimeout(...)` for a family of calls. Or, for the per-operation limits, have an application interceptor pass `chain.withReadTimeout(...)` for matching requests. Building a fresh `OkHttpClient.Builder()` would lose the warm connections.
  • Why might a team set retryOnConnectionFailure(false) on some client?
    With the default `true`, OkHttp silently retries after route failures and stale pooled connections, and it can resend a request with a body unless that body is one-shot. For a request where a duplicate is harmful, such as a payment POST, the documentation suggests disabling it and letting the caller decide how to recover. A derived client keeps that choice scoped to those calls.

  • readTimeout limits how long the whole response download may take.
  • callTimeout defaults to 10 seconds, the same as the other timeouts.
  • connectTimeout covers the time the server spends processing the request.
  • OkHttp never retries on its own, so the connect timeout is the worst case.
  • OkHttp has no overall deadline, so calls need an external timer.