skip to content

In an OkHttp Interceptor, what are the rules for calling chain.proceed(), and what breaks when an interceptor calls it twice or throws?

level: seniorimportance: should knowfreq 38%

answer

  1. where the HTTP work happens
  2. network side: exactly once
  3. close before you proceed again
  4. IOException versus anything else

basics

~20 s

chain.proceed() runs the rest of the chain. Network interceptors must call it exactly once; application interceptors may skip it, or repeat it after closing the prior response. A non-IOException cancels the call and, under enqueue() on Android, crashes the app.

solid answer

~40 s

`chain.proceed(request)` is where everything below an interceptor happens, so the contract matters. A **network interceptor** must call it exactly once and keep the request's host and port; OkHttp throws `IllegalStateException` otherwise. An **application interceptor** may return a synthetic `Response` without proceeding, or proceed again to retry, but it must close the previous response first, or OkHttp throws `IllegalStateException`: the previous response is still open. Failures should be signalled with an `IOException` or a synthetic error response. Any other exception cancels the call: `execute()` rethrows it to the caller, while for `enqueue()` the callback gets an `IOException` and the original exception goes to the thread's uncaught exception handler, which crashes the app on Android by default.

code

kotlin · 15 lines
kotlin
import java.io.IOException
import okhttp3.Interceptor
import okhttp3.Response

// Register with addInterceptor(): only application interceptors may proceed twice.
class RetryOnceOn503 : Interceptor {
  @Throws(IOException::class)
  override fun intercept(chain: Interceptor.Chain): Response {
    val request = chain.request()
    val first = chain.proceed(request)
    if (first.code != 503 || request.method != "GET") return first
    first.close() // without this, the second proceed() throws IllegalStateException
    return chain.proceed(request)
  }
}

go deeper

for a junior

Recall that proceed() sends the request onward and returns the response, and that an interceptor must return a response.

for a middle

Explain which side may short-circuit or repeat proceed(), and why the earlier response must be closed first.

for a senior

Diagnose the production failures: IllegalStateException from a second proceed(), leaked connections, and crashes from non-IO exceptions on async calls.

for a principal

Set the team's review bar for interceptors: IOException-only failures, closed responses, and no blocking work on dispatcher threads.

## What proceed() is An OkHttp `Interceptor` has one method, `intercept(chain: Interceptor.Chain): Response`. Inside it, `chain.request()` is the request so far and `chain.proceed(request)` hands a request to the next stage and returns that stage's response. OkHttp's interceptor guide calls `proceed()` the critical part of every interceptor: it is where DNS, connecting, writing and reading happen for everything below. An interceptor therefore does one of three things: proceed once and return the response, possibly rewritten; return its own `Response` without proceeding; or proceed more than once. Which of those is legal depends on where the interceptor is registered. ## The rules on each side | Rule | Application interceptor (`addInterceptor`) | Network interceptor (`addNetworkInterceptor`) | |---|---|---| | Skip `proceed()` and return a synthetic response | allowed | throws `IllegalStateException` | | Call `proceed()` more than once | allowed, after closing the earlier response | throws `IllegalStateException` | | Change the request's host or port | allowed, before proceeding | throws `IllegalStateException` | | Override timeouts or other settings on the chain | allowed | throws `IllegalStateException` | The network-side messages name the offending interceptor, for example *network interceptor ... must call proceed() exactly once* or *... must retain the same host and port*. The reason is structural: by the time a network interceptor runs, OkHttp has already chosen a connection for exactly one exchange, so it cannot be skipped, repeated or redirected. ## Proceeding twice on the application side Retrying a whole call from an application interceptor is legal, but each response holds a live resource: a socket for a network response or an open file for a cached one. If an interceptor calls `proceed()` again while the first response's body is still open, OkHttp refuses with `IllegalStateException`: *cannot make a new request because the previous response is still open: please call response.close()*. The guide's rule is the same in prose: if `proceed()` is called more than once, previous response bodies must be closed. Two more consequences of repeating: - The call timeout covers the whole call, so every attempt your interceptor makes shares one deadline. - Each attempt passes through OkHttp's own retry, redirect and cache stages again, so one interceptor retry can produce several network requests. ## Signalling failure The `Interceptor` documentation draws a hard line between exception types: - **`IOException`** is the expected way to fail: unreachable servers, but also synthetic failures such as an unexpected response type. It propagates to `execute()`'s caller or to `Callback.onFailure()` like any network error. - **Any other exception** cancels the call. For `execute()` it propagates to the caller. For `enqueue()`, the callback's `onFailure()` receives an `IOException` saying the call was canceled, and the original exception is delivered to the dispatcher thread's uncaught exception handler, which **crashes the app on Android** by default. - **A synthetic response** is often the cleanest signal: the documentation's own example returns a `400` with a message when the client's configuration is invalid, so callers handle it like any HTTP error. So a `require()` or a `!!` inside an interceptor is a latent crash for every asynchronous call, including the ones Retrofit makes for suspend functions, which use `enqueue()` underneath. ## Threads and leaks - Interceptors run on whatever thread runs the call: the caller's thread for `execute()`, a dispatcher thread for `enqueue()`. Blocking inside an interceptor holds one of the dispatcher's running slots for as long as it blocks. - A response body that is never closed keeps its connection out of the pool. OkHttp eventually logs *A connection to ... was leaked. Did you forget to close a response body?*, which often traces back to an interceptor that inspected a response and dropped it. ## A checklist for reviewing an interceptor 1. Does every path either return `proceed()`'s response or a deliberate synthetic one? 2. If it proceeds twice, is the first response closed before the second `proceed()`? 3. Is it registered on the side whose rules it follows? 4. Can anything in it throw something other than an `IOException`? 5. Does it block, for example on a lock or a disk read, while holding a dispatcher thread?

  • Why does a network interceptor have to keep the same host and port?
    Network interceptors run after OkHttp has acquired a connection for this exchange, and that connection is bound to one address. A different host or port would need a different connection, which only the stages above can choose, so OkHttp throws `IllegalStateException`. Rewriting the URL belongs in an application interceptor, before the connect step runs.
  • An interceptor validates a header with require(), and some users report crashes with no matching network error. What happened?
    `require()` throws `IllegalArgumentException`, which is not an `IOException`. For calls made with `enqueue()`, including Retrofit's suspend calls, OkHttp cancels the call, gives the callback an `IOException`, and rethrows the original on the dispatcher thread, where Android's default uncaught exception handler crashes the app. Throw an `IOException` or return a synthetic error response instead.

  • Any interceptor may skip proceed() and return its own response.
  • Calling proceed() twice is fine because OkHttp discards the first response.
  • A RuntimeException in an interceptor only fails that one call.
  • A network interceptor can rewrite the URL to point at another host.
  • Interceptors always run on an OkHttp background thread.