OkHttp & Interceptors Interview Questions
DATA › Networking
What is OkHttp, and how does it relate to Retrofit?
What a strong answer covers: OkHttp is the HTTP client that actually makes the requests: connection pooling, HTTP/2, transparent GZIP, caching, retries on certain failures, and TLS. Retrofit sits on top and turns interface methods into OkHttp requests. You configure timeouts, interceptors, the cache and certificate pinning on the OkHttpClient.
What's the difference between application interceptors and network interceptors?
What a strong answer covers: Application interceptors (addInterceptor) run once per call, see the original request, aren't called for cached responses or redirects, and can short-circuit. Network interceptors (addNetworkInterceptor) run for every actual network request, including redirects and retries, see the final headers OkHttp adds, and are skipped for cache hits.
How does HTTP caching work in OkHttp?
What a strong answer covers: Configure a Cache with a directory and size. OkHttp follows standard HTTP caching headers: Cache-Control max-age, ETag with If-None-Match, and Last-Modified, serving fresh cached responses and revalidating stale ones with conditional requests (304 Not Modified). You can force behaviour with CacheControl.FORCE_CACHE or an interceptor that rewrites headers when offline.
How would you implement token refresh so concurrent requests don't all refresh at once?
What a strong answer covers: Use an Authenticator, called on 401. Synchronise the refresh (a lock or Mutex): the first request refreshes the token, and others waiting on the lock check whether the token changed since their request and just retry with the new one. Give up after a retry limit to avoid loops, and log out if the refresh token is invalid. Don't call the refresh endpoint through the same client with the authenticator, or you'll recurse.
Requests are slow on mobile networks. What OkHttp settings and network-level techniques would you check?
What a strong answer covers: Reuse one client so connections are pooled; make sure HTTP/2 is used for multiplexing; enable caching and compression; check timeouts aren't too high and that retries aren't stacking; use EventListener to measure DNS, connect, TLS and time to first byte; consider a faster DNS, preconnecting at startup, reducing payload size (pagination, smaller fields), and batching requests. HTTP/3 (QUIC) through Cronet can help on lossy networks.