OkHttp & Interceptors Interview Questions
DATA › Networking
When would you reach for an application interceptor instead of a network interceptor, and can you think of a case where picking the wrong one causes a real bug?
What a strong answer covers: Application interceptors see the request/response exactly once per call, before redirects or cache, so they're right for cross-cutting concerns like adding auth headers or logging what the app actually asked for; network interceptors see every physical hop including redirects and retries, so they're right for observing what actually went over the wire, like measuring real bytes transferred or logging Content-Encoding. A common bug is putting cache-inspection logic in an application interceptor and being confused when it never fires on a cache hit, since application interceptors are skipped entirely when OkHttp serves a response straight from the Cache.
OkHttp can automatically retry a request on connection failure when retryOnConnectionFailure is true. What's dangerous about that for a POST, and how would you guard against it?
What a strong answer covers: OkHttp only retries when it believes the request was never actually transmitted, but that guarantee gets murkier with connection reuse and certain failure timings, so a non-idempotent POST (like creating an order) can occasionally be sent twice with the client only aware of one attempt. The real fix isn't disabling the retry, it's making the operation idempotent server-side with a client-generated idempotency key, so a duplicate delivery is a no-op rather than a duplicate charge or duplicate row.
Fifty screens in your app fire off requests to the same slow, expensive endpoint within a few hundred milliseconds of each other. How would you design request de-duplication so that turns into one network call, not fifty?
What a strong answer covers: OkHttp doesn't coalesce identical in-flight requests for you, so you need a layer above it, typically a map keyed by request signature holding a shared Deferred or Flow that late callers attach to instead of issuing a new call, torn down once the result lands. The trap is getting cancellation right: one caller navigating away and cancelling its coroutine must not cancel the underlying call for the other 49 still waiting on it.