skip to content

An app enqueues 40 concurrent OkHttp calls to one slow API host that speaks HTTP/2; why do most of them wait, and how do you measure and tune it?

level: seniorimportance: should knowfreq 32%

answer

  1. not the connections
  2. 64 overall, 5 per host
  3. queue time is outside callTimeout
  4. dispatcherQueueStart and dispatcherQueueEnd

basics

~20 s

OkHttp's Dispatcher runs at most 5 asynchronous calls per host and 64 overall by default, so 35 calls queue even though one HTTP/2 connection could multiplex them. Measure the wait with an EventListener and tune Dispatcher.maxRequestsPerHost.

solid answer

~40 s

The bottleneck is the `Dispatcher`, not the network. Calls made with `enqueue()`, which includes Retrofit's suspend and `enqueue` calls, run only while the dispatcher has room: 64 in total and **5 per host name** by default. Over HTTP/2 those 5 typically share one multiplexed connection, so connections are not scarce; the other 35 calls sit in the dispatcher's ready queue. The `ConnectionPool` doesn't limit this either: its default of 5 idle connections for 5 minutes caps only connections at rest. The queue wait is easy to miss, because `callStart` fires on enqueue but the call timeout only starts when the call runs. Measure it with an `EventListener.Factory`: OkHttp 5.2.0 added `dispatcherQueueStart` and `dispatcherQueueEnd`. Then raise `maxRequestsPerHost` on the shared client's dispatcher to what the server can take, and cancel calls whose screen is gone.

code

kotlin · 28 lines
kotlin
import java.util.concurrent.TimeUnit
import okhttp3.Call
import okhttp3.Dispatcher
import okhttp3.EventListener
import okhttp3.OkHttpClient

class QueueTimingListener(
  private val report: (host: String, waitedMs: Long) -> Unit,
) : EventListener() {
  @Volatile private var queuedAtNanos = 0L

  override fun dispatcherQueueStart(call: Call, dispatcher: Dispatcher) {
    queuedAtNanos = System.nanoTime()
  }

  override fun dispatcherQueueEnd(call: Call, dispatcher: Dispatcher) {
    val waitedMs = (System.nanoTime() - queuedAtNanos) / 1_000_000
    report(call.request().url.host, waitedMs)
  }
}

val dispatcher = Dispatcher().apply { maxRequestsPerHost = 16 }

val client = OkHttpClient.Builder()
  .dispatcher(dispatcher)
  .eventListenerFactory { QueueTimingListener { host, ms -> println("$host waited $ms ms") } }
  .callTimeout(10, TimeUnit.SECONDS)
  .build()

go deeper

for a junior

Recall that OkHttp limits concurrent asynchronous calls, 64 in total and 5 per host by default, and that extra calls wait in a queue.

for a middle

Explain how the dispatcher's limits differ from the connection pool's idle limit and how HTTP/2 multiplexing changes what a connection costs.

for a senior

Diagnose queueing as the hidden latency: callStart versus the late call timeout, per-call listeners, dispatcherQueueStart, and a sized per-host limit.

for a principal

Decide per-host concurrency for each backend with its owners, balancing the app's latency against server capacity and rate limits.

## Where the 35 calls are waiting OkHttp separates **how many calls run** from **how many connections exist**: - The **`Dispatcher`** decides when an asynchronous call made with `enqueue()` may start. It allows `maxRequests` calls at once, **64** by default, and `maxRequestsPerHost` per host name, **5** by default. A call that would exceed either limit is held in an in-memory ready queue until a running call finishes. - The **`ConnectionPool`** keeps finished connections for reuse. Its defaults, **5 idle connections evicted after 5 minutes**, bound what is kept at rest. It never caps how many connections are in use. With 40 calls enqueued to one host, the dispatcher starts 5 and queues 35. Each queued call waits for one of the five to finish; with a slow API, that wait can dwarf the request itself. Calls made with `execute()` are different: the dispatcher records them but never queues them, because the calling thread runs them directly. Retrofit's suspend functions and its `Call.enqueue()` both go through OkHttp's `enqueue()`, so they meet these limits. ## Dispatcher and pool side by side | | `Dispatcher` | `ConnectionPool` | |---|---|---| | What it limits | running asynchronous calls: 64 in total, 5 per host name | idle connections kept for reuse: 5, each for up to 5 minutes | | What it applies to | calls made with `enqueue()` | connections once no call is using them | | What happens to the excess | calls wait in the ready queue | the pool closes and evicts idle connections | | How you tune it | `maxRequests`, `maxRequestsPerHost` | `ConnectionPool(maxIdleConnections, keepAliveDuration, timeUnit)` | ## Why HTTP/2 doesn't help on its own OkHttp's default protocol list is `HTTP_2` then `HTTP_1_1`, negotiated with ALPN on HTTPS connections. Over HTTP/1.1, every in-flight call needs its own connection. Over HTTP/2, one connection **multiplexes** many streams, up to the server's advertised limit on concurrent streams, so 40 calls could share a single connection. The dispatcher doesn't know about any of that. Its per-host limit counts **calls by host name**, whatever the protocol. So on an HTTP/2 API the five running calls are typically five streams on one connection, and the connection sits mostly idle while 35 calls queue. That is the main reason a team raises `maxRequestsPerHost` for an HTTP/2 backend: the cost of more concurrent calls is streams, not sockets. Against an HTTP/1.1 host, the same change opens more connections. ## Why the timeouts don't reveal it - `EventListener.callStart` fires when the call is enqueued, so a call's total duration includes its time in the queue. - The **call timeout** of an enqueued call starts only when the dispatcher runs it. A call can wait in the queue for longer than the configured `callTimeout` and still succeed afterwards. So a screen can feel slow while every call reports a healthy timeout budget. You need a measurement that separates queueing from network time. ## Measuring it - **`EventListener.Factory`** creates one listener per call, so per-call state such as start times is safe. A single shared `EventListener` would mix concurrent calls together. - **`dispatcherQueueStart` and `dispatcherQueueEnd`**, added in **OkHttp 5.2.0**, fire only for calls that had to wait. Their difference is queue time. - **`connectionAcquired(call, connection)`** reports the connection a call got; `connection.protocol()` confirms whether the call is multiplexed over `HTTP_2`. - **`Dispatcher.queuedCallsCount()`** and **`runningCallsCount()`** give a point-in-time view without a listener, which is what an app still on OkHttp 4.12 has, since Retrofit 3.0.0 depends on that line. Event methods must be fast: no blocking, no external locking, no exceptions and no calls back into the client. Do any I/O, such as shipping metrics, asynchronously. ## Tuning it 1. **Raise the per-host limit on the shared client's dispatcher**, for example `maxRequestsPerHost = 16`, sized to what the server and its rate limits can take. A new value applies at once, and calls already running keep running. 2. **Keep one dispatcher.** The limits only mean something if every client shares it, which `newBuilder()` does. 3. **Cancel work nobody will see.** `call.cancel()` for a screen that has gone, or `dispatcher.cancelAll()` on sign-out, frees slots for calls that still matter. 4. **Set a call timeout anyway**, knowing it starts after queueing, so a slow call cannot hold a slot forever. 5. **If you supply your own executor**, follow the `Dispatcher` documentation: it must accept new tasks while up to `maxRequests` calls run, and a pool sized exactly to `maxRequests` on a `SynchronousQueue` is not enough.

  • Would raising the ConnectionPool's maxIdleConnections shorten that queue?
    No. The pool's limit applies only to idle connections kept for reuse; it never caps connections in use. The queue exists because the dispatcher allows 5 running asynchronous calls per host. Over HTTP/2 those calls typically share one connection already, so a bigger pool changes nothing; raising `maxRequestsPerHost` is the knob.
  • Why does a single EventListener set with eventListener() give wrong queue times under load?
    `eventListener()` installs one listener instance for every call on the client, so a field like a start time is overwritten by whichever call fired last. `eventListenerFactory()` creates a listener per call, which keeps per-call state separate. The factory can also return `EventListener.NONE` for calls you don't want to sample.
  • Do synchronous execute() calls count against maxRequestsPerHost?
    No. The dispatcher tracks synchronous calls so it can cancel them and report idleness, but only asynchronous calls are limited and queued. A thread calling `execute()` runs immediately, so an app mixing both styles can exceed the per-host number it configured.

  • HTTP/2 multiplexing means OkHttp runs all enqueued calls to a host at once.
  • The ConnectionPool's limit of 5 is what makes the extra calls wait.
  • callTimeout counts the time a call spends waiting in the dispatcher queue.
  • maxRequestsPerHost also limits synchronous execute() calls.
  • One EventListener instance is enough to time concurrent calls.

Assumes OkHttp 5.5; EventListener.dispatcherQueueStart() and dispatcherQueueEnd() arrived in 5.2.0, so an app resolving OkHttp 4.12 through Retrofit 3.0.0 must sample Dispatcher.queuedCallsCount() instead.