Retrofit and OkHttp
Why it matters
- Timeouts that are missing or wrong make screens spin for a long time on bad networks, or fail requests that would have finished.
- Building a new
OkHttpClientfor each request or screen throws away connection reuse and creates extra thread and connection pools. - Handling 401 badly (no retry limit, refresh call going through the same authenticator) leads to refresh loops.
- Interviewers test the OkHttp interceptor chain and the difference between
HttpExceptionandIOExceptionto see if you understand what happens below the Retrofit interface.
The simple explanation
- The API is a restaurant kitchen.
- Retrofit is the waiter who takes your order and brings the food.
- OkHttp is the kitchen staff and the delivery driver.
- Interceptors are the quality control inspectors checking the food before it leaves or arrives.
Retrofit turns an annotated Kotlin interface into HTTP calls. At runtime it creates a dynamic proxy for the interface, reads the annotations, and uses a converter (kotlinx.serialization, Moshi, Gson) to turn bodies into objects. OkHttp does the actual transport: connection pooling, HTTP/2, TLS, redirects, retries on failed connections and caching.
Share one OkHttpClient across the app. Each client has its own connection pool and dispatcher, so a client per request or per screen means no connection reuse and a new TLS handshake for every call. If one call site needs different settings (for example a longer timeout for uploads), derive a client with okHttpClient.newBuilder(); the derived client shares the pool and dispatcher.
OkHttp has two interceptor layers:
| Type | Added with | Runs | Typical use |
|---|---|---|---|
| Application interceptor | addInterceptor | Once per call, even if the response comes from the cache | Auth header, logging, custom headers |
| Network interceptor | addNetworkInterceptor | Once per network request, including each redirect and retry; not for cache hits | Observing the exact bytes and headers on the wire, the connection used |
OkHttp's default timeouts are 10 s for connect, read and write, and no limit for the whole call (callTimeout is 0). Read and write timeouts apply to each individual socket operation, so a server that sends a few bytes every few seconds can keep a call open for a long time; callTimeout caps the whole call.
A Retrofit suspend function is main-safe: Retrofit enqueues the call on OkHttp's own threads and resumes the coroutine with the result. If the coroutine is cancelled, Retrofit cancels the OkHttp call. There are two return styles:
| Return type | On 2xx | On non-2xx | On connection failure |
|---|---|---|---|
suspend fun get(): User | Returns the body | Throws HttpException | Throws IOException |
suspend fun get(): Response<User> | isSuccessful is true, body() holds the object | Returned normally; body() is null, read errorBody() | Throws IOException |
A body that cannot be parsed throws the converter's exception (SerializationException for kotlinx.serialization, JsonDataException for Moshi), which is neither an HttpException nor, in most cases, an IOException.
Notes
- Provide one
OkHttpClientand oneRetrofitinstance from DI. UsenewBuilder()when a call site needs different settings; it shares the connection pool. - Add
HttpLoggingInterceptoronly in debug builds, and callredactHeader("Authorization")so tokens do not end up in logcat. - Set
connectTimeout,readTimeoutandwriteTimeoutdeliberately, and add acallTimeoutif you need an upper bound for the whole call. The defaults are 10 s, 10 s, 10 s and no call limit. - A
suspendfunction returningTthrowsHttpExceptionon non-2xx. ReturningResponse<T>gives you the status code without an exception; checkisSuccessfulbefore usingbody(). - Application interceptors run once per call; network interceptors run once per network request, so a redirect runs them twice and a cache hit does not run them at all.
IOExceptionmeans the request did not complete (no network, DNS failure, timeout, connection reset).HttpExceptionmeans the server answered with a non-2xx status.- Parse failures are a third category. Map them separately; retrying will not fix a contract mismatch.
- Do not wrap the call in a catch-all that swallows
CancellationException. Catch the specific exceptions you map, or re-throwCancellationExceptionfirst.
Code example
This shows one shared OkHttpClient with explicit timeouts and debug-only logging, a Retrofit service with both return styles, and a repository that maps each failure type to a sealed result.
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.HttpException
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.kotlinx.serialization.asConverterFactory
import retrofit2.create
import retrofit2.http.GET
import retrofit2.http.Path
import java.io.IOException
import java.util.concurrent.TimeUnit
@Serializable
data class User(val id: Long, val name: String)
interface UserService {
@GET("users/{id}")
suspend fun getUser(@Path("id") id: Long): User // non-2xx throws HttpException
@GET("users/{id}")
suspend fun getUserResponse(@Path("id") id: Long): Response<User> // non-2xx is returned
}
// One client for the whole app; provide it as a singleton from DI.
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS) // whole call; the default is no limit
.apply {
if (BuildConfig.DEBUG) { // needs buildFeatures { buildConfig = true }
addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
redactHeader("Authorization")
})
}
}
.build()
private val json = Json { ignoreUnknownKeys = true }
val userService: UserService = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.client(okHttpClient)
.addConverterFactory(json.asConverterFactory("application/json".toMediaType()))
.build()
.create()
sealed interface NetworkResult<out T> {
data class Success<T>(val data: T) : NetworkResult<T>
data class HttpError(val code: Int) : NetworkResult<Nothing>
data object NetworkError : NetworkResult<Nothing>
data class ParseError(val cause: SerializationException) : NetworkResult<Nothing>
}
class UserRepository(private val api: UserService) {
suspend fun fetchUser(id: Long): NetworkResult<User> =
try {
NetworkResult.Success(api.getUser(id))
} catch (e: HttpException) {
NetworkResult.HttpError(e.code()) // server answered 4xx or 5xx
} catch (e: IOException) {
NetworkResult.NetworkError // no connection, timeout, reset
} catch (e: SerializationException) {
NetworkResult.ParseError(e) // body did not match the model
}
}HttpExceptionlives inretrofit2, not in OkHttp. It is only thrown for the bareUserreturn type;getUserResponsewould return the error response instead.- There is no catch-all
Exception, soCancellationExceptionpasses through untouched and cancellation keeps working. retrofit2.createis the reified Kotlin extension, so.create()needs no class argument.
Run the idea in plain Kotlin
This models OkHttp's interceptor chain: the application interceptor runs once, while the network interceptor runs once per network request, so a redirect runs it twice.
data class Request(val path: String, val headers: Map<String, String> = emptyMap())
data class Response(val code: Int, val location: String? = null)
fun interface Interceptor {
fun intercept(request: Request, proceed: (Request) -> Response): Response
}
fun runChain(interceptors: List<Interceptor>, request: Request, last: (Request) -> Response): Response {
fun step(i: Int, r: Request): Response =
if (i == interceptors.size) last(r) else interceptors[i].intercept(r) { next -> step(i + 1, next) }
return step(0, request)
}
// Pretend server: /old redirects to /new
fun server(r: Request): Response {
println(" server: " + r.path + " auth=" + r.headers["Authorization"])
return if (r.path == "/old") Response(301, location = "/new") else Response(200)
}
fun main() {
var appCalls = 0
var networkCalls = 0
val app = listOf(Interceptor { r, proceed ->
appCalls++
println("app interceptor: " + r.path)
proceed(r.copy(headers = r.headers + ("Authorization" to "Bearer abc")))
})
val network = listOf(Interceptor { r, proceed ->
networkCalls++
println("network interceptor: " + r.path)
proceed(r)
})
// Follows redirects between the two layers, like OkHttp's RetryAndFollowUpInterceptor
val followUps = Interceptor { r, _ ->
var current = r
var response = runChain(network, current, ::server)
while (response.code in 300..399) {
current = current.copy(path = response.location!!)
response = runChain(network, current, ::server)
}
response
}
val result = runChain(app + followUps, Request("/old")) { error("unreachable") }
println("final code: " + result.code)
println("app interceptor calls: " + appCalls + ", network interceptor calls: " + networkCalls)
}Expected output:
app interceptor: /old
network interceptor: /old
server: /old auth=Bearer abc
network interceptor: /new
server: /new auth=Bearer abc
final code: 200
app interceptor calls: 1, network interceptor calls: 2
In production
- Users reported the app becoming unresponsive after being logged in for a long time, with heavy traffic to the refresh endpoint.
- The OkHttp
Authenticatorrefreshed the token on every 401 and never gave up. - The refresh token itself had expired, and the refresh request went through the same client, so every refresh got a 401 that triggered another refresh.
- Sent the refresh request through a separate client without the authenticator, so a 401 from the refresh endpoint is just a failed refresh.
- In
authenticate, returnednullwhen the response already had a prior 401 (response.priorResponse), so each call retries at most once. - When the refresh fails with 401, cleared the session and sent the user to login.
- Memory grew over long sessions and LeakCanary reported a destroyed
MainActivitystill referenced. - A custom interceptor took a
Contextto read string resources, and it was created with the Activity as that context. - The interceptor was installed on the app-wide
OkHttpClient, which lives as long as the process, so it kept the first Activity alive.
- Passed
applicationContextinstead, through a smallResourceProviderinterface provided by DI. - Kept the single client and interceptor in the DI singleton graph.
- Confirmed with LeakCanary that the Activity was no longer retained after rotation and back navigation.
Common mistakes
- Creating multiple OkHttpClient instances. Each instance has its own connection pool and dispatcher, so connections are not reused and every call pays for a new TCP and TLS handshake. Share one client and use
newBuilder()for variants. - Swallowing CancellationException. A catch-all
catch (e: Exception)that returns an error result turns cancellation into a fake failure, and the code after it keeps running (updating state, retrying) after the screen is gone. - Adding the auth header in a network interceptor. OkHttp removes
Authorizationwhen it follows a redirect to a different host; a network interceptor runs again for the redirected request and would put the token back, sending it to that other host. Add auth headers in an application interceptor. - Logging bodies and headers in release.
HttpLoggingInterceptoratBODYorHEADERSprints tokens and personal data to logcat. Add it only in debug and redactAuthorization. - Relying on default timeouts without thinking. The 10 s defaults may be too short for uploads and there is no limit on the whole call. Set the four timeouts for your traffic.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between an Application Interceptor and a Network Interceptor in OkHttp?”
“How do you handle a 401 Unauthorized error to refresh an access token?”
“Why should you avoid a catch-all catch (e: Exception) around a suspend network call?”
“What is the purpose of a connection pool in OkHttp?”
Quiz
Which interceptor type should you use to add a 'User-Agent' header to every outgoing request?
A coroutine is cancelled while a Retrofit suspend call is in progress, and your code wraps the call in catch (e: Exception) that returns an error result. What happens?
What is the main cost of creating a new OkHttpClient for every request?
A Retrofit function is declared as suspend fun getUser(): User (not Response<User>). What happens when the server returns 500?
0 of 4 answered
Mini task
Task: Implement a Secure Network Result Wrapper
- Create a
sealed interfacenamedNetworkResult<out T>withSuccess(val data: T),HttpError(val code: Int),NetworkErrorandParseErrorsubtypes. - Create an interface
ApiServicewith a singlesuspendfunctionfetchData(): Stringannotated with@GET("test"), and registerScalarsConverterFactory(fromconverter-scalars) so Retrofit can return a plainString. - Build one
OkHttpClientwith explicit connect, read, write and call timeouts, andHttpLoggingInterceptoronly in debug withredactHeader("Authorization"). - Implement a
Repositoryclass that takesApiServiceas a constructor parameter, with a functionsafeApiCall()that callsfetchData(). - Map
HttpExceptiontoHttpError(e.code())andIOExceptiontoNetworkError. Do not add a catch-all, or if you do, re-throwCancellationExceptionfirst. - Add a second function using
Response<String>and mapisSuccessful == falsetoHttpError(response.code()).
Done Condition: You have functions that return a NetworkResult, correctly distinguish a network failure from a server error in both return styles, and do not break coroutine cancellation.