skip to content

In a Retrofit app's OkHttpClient, where does a custom retry interceptor belong, and what must it do between attempts?

level: seniorimportance: should knowfreq 38%

answer

  1. OkHttp already retries some failures
  2. proceed() more than once
  3. network slot forbids it
  4. close, check cancel, back off
  5. identity failures are permanent

basics

~20 s

A retry interceptor must be added with addInterceptor, because a network interceptor may call proceed() only once. Between attempts it closes the failed response, stops if the call was cancelled, backs off, and never retries a certificate-pin or hostname failure.

solid answer

~50 s

OkHttp already recovers from some connection failures while `retryOnConnectionFailure` is true, its default, but a 429, a 503 that asks for a delay, or a read timeout after the request was sent reach the app. A custom retry loop calls `chain.proceed()` more than once, so it must be added with `addInterceptor`: a network interceptor that calls `proceed()` twice fails with `IllegalStateException`. Between attempts it closes the previous response, rethrows when `chain.call().isCanceled()` (Retrofit cancels the OkHttp call when the coroutine is cancelled), sleeps with backoff, and rethrows `SSLPeerUnverifiedException` at once, since a pin or hostname mismatch meets the same certificates on every attempt. I retry only idempotent requests. I add it before the auth-header interceptor, so every attempt picks up the current token. The sleep also holds an OkHttp dispatcher thread and one of the five per-host slots the dispatcher allows by default, so attempts and delays stay small.

code

kotlin · 33 lines
kotlin
import java.io.IOException
import javax.net.ssl.SSLPeerUnverifiedException
import okhttp3.Interceptor
import okhttp3.Response

class RetryInterceptor(
    private val maxAttempts: Int = 3,
    private val baseDelayMillis: Long = 300,
) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        if (request.method != "GET") return chain.proceed(request) // only idempotent reads

        var attempt = 1
        while (true) {
            try {
                val response = chain.proceed(request)
                if (response.code !in RETRYABLE_CODES || attempt >= maxAttempts) return response
                response.close() // must be closed before proceed() is called again
            } catch (e: SSLPeerUnverifiedException) {
                throw e // pin or hostname mismatch: retrying cannot help
            } catch (e: IOException) {
                if (chain.call().isCanceled() || attempt >= maxAttempts) throw e
            }
            Thread.sleep(baseDelayMillis shl (attempt - 1)) // 300 ms, then 600 ms
            attempt++
        }
    }

    private companion object {
        val RETRYABLE_CODES = setOf(429, 502, 503, 504)
    }
}

go deeper

for a junior

Recall that OkHttp retries some connection failures itself and that an app-level retry is an interceptor added to the client Retrofit uses.

for a middle

Explain why a retry loop must be an application interceptor, and what closing the failed response and checking cancellation each prevent.

for a senior

Choose what is retried and where the interceptor sits relative to auth and logging. Account for blocked dispatcher threads and per-host slots, and keep identity-check failures and non-idempotent writes out of the loop.

for a principal

Decide whether retries belong in a shared client interceptor at all or with each caller, and how much hidden waiting the team accepts behind one network call.

## What OkHttp already retries Before writing a retry interceptor, know what the client does by itself. With `retryOnConnectionFailure` left at its default of `true`, OkHttp silently recovers from a few **connectivity** problems: an unreachable IP address when the host has several, a stale pooled connection, and an unreachable proxy. It also follows redirects and authentication challenges. It does **not** wait and retry when the server answers 429 Too Many Requests, a 503 that asks the client to wait, or a 502 or 504 from a gateway. It does not recover from a read timeout once the request has been sent, and it treats some failures as permanent, such as a certificate-pinning mismatch. Those are the cases an app-level retry interceptor exists for. ## Why it must be an application interceptor A retry loop calls `chain.proceed()` more than once. OkHttp has two interceptor slots, and only one of them allows that: | Slot | Added with | Calling `proceed()` twice | |---|---|---| | application | `addInterceptor` | allowed; the documentation only requires closing earlier response bodies | | network | `addNetworkInterceptor` | fails with `IllegalStateException`: a network interceptor must call `proceed()` exactly once | The network slot also sits below OkHttp's own connection setup, which is the wrong level for an app-wide policy. A retry interceptor therefore always goes in the application list. ## What it must do between attempts 1. **Close the failed response.** OkHttp's interceptor documentation says that when `proceed()` is called more than once, previous response bodies must be closed. An unclosed body holds its connection. 2. **Check for cancellation.** Retrofit's suspend support cancels the underlying OkHttp call when the coroutine is cancelled, and the next `proceed()` then throws an `IOException`. Test `chain.call().isCanceled()` and rethrow, so a screen the user left does not keep sleeping and retrying. 3. **Rethrow permanent failures.** `SSLPeerUnverifiedException` is an `IOException`, so a generic catch would retry it, yet OkHttp throws it when the server's identity check fails: a certificate-pin mismatch, or a certificate that does not match the hostname. The next attempt meets the same certificates, and OkHttp's own recovery treats it as unrecoverable for the same reason. 4. **Back off.** Sleep between attempts, growing the delay, and respect a server's `Retry-After` header where present. 5. **Cap the attempts.** On the last attempt, return the response or rethrow the exception, so Retrofit reports it normally. ## Where it sits among the other interceptors Application interceptors run in the order they were added, outermost first. - **Before the auth-header interceptor**: every attempt passes through the auth interceptor again, so a retry after a token refresh carries the new token. - **After the auth-header interceptor**: the attempts reuse the request that already has the old header. - **Logger outside it**: one log entry per call, showing the final outcome. - **Logger inside it**: one entry per attempt, which is usually what you want in a debug build. The usual order is retry, then auth, then logging. ## Which calls to retry - Retry `GET`, `HEAD` and other requests the server treats as idempotent. - Do not blindly retry a `POST`: the first attempt may have succeeded on the server before the connection broke. Making writes safe to retry, for example with idempotency keys, is request-pipeline design rather than client composition. - To opt individual service methods in or out, read the method from the `Invocation` tag Retrofit attaches to each request and check an annotation on it. ## Testing it - Drive it with a scripted server response sequence (503, 503, 200) and assert that the call succeeds and that exactly three requests arrived. - Cancel the call during the backoff and assert that it fails promptly with an `IOException` instead of finishing its attempts. - Make the pin check fail and assert that only one attempt was made. - Send a `POST` and assert that it was not retried. ## What it costs - For Retrofit's suspend and `enqueue` calls, the interceptor runs on an OkHttp dispatcher thread, so `Thread.sleep` blocks that thread for the whole backoff. - The dispatcher counts the sleeping call as running. Its defaults allow 64 concurrent calls in total and 5 per host, so a few long backoffs to one host queue every other call to it. - Keep attempts low (two or three) and delays short, and let anything longer be the caller's decision, for example a retry button or a scheduled background job.

  • Why put the retry interceptor before the auth-header interceptor rather than after it?
    Application interceptors run in the order added, so one added earlier wraps the ones after it. With retry outermost, each attempt passes through the auth interceptor again and picks up a token that was refreshed in the meantime. Added after auth, every attempt resends the header from the first pass.
  • Should you turn off retryOnConnectionFailure when you add your own retry interceptor?
    Usually not. Its recoveries (trying another IP address of the host, replacing a stale pooled connection, moving to another proxy) happen below the interceptor and are cheap. Turn it off only when even those silent retries would be destructive for this client, and then the app must handle connectivity failures itself.

  • Add the retry loop with addNetworkInterceptor so it sees each connection attempt.
  • OkHttp retries 503 and 429 responses itself, so no interceptor is needed.
  • No need to close the failed response; the next proceed() reuses its connection.
  • Catch IOException and retry everything, including SSLPeerUnverifiedException.
  • A cancelled call stops by itself, so the loop needs no cancellation check.
  • Retry every POST the same way as a GET.