Networking cheat sheet
Key ideas
- Provide one
OkHttpClientor KtorHttpClientfrom DI; usenewBuilder()for per-call-site variants so the connection pool is shared. IOExceptionmeans no response (DNS, timeout, reset);HttpExceptionmeans a non-2xx answer;SerializationExceptionmeans a contract mismatch — map each to its own error type.- Never let
CancellationExceptionbecome an error result; re-throw it before anycatch (e: Exception)orrunCatching. - Set
connectTimeout,readTimeout,writeTimeout, andcallTimeoutdeliberately; the OkHttp defaults are 10 s each and no call limit. - Set
ignoreUnknownKeys = trueon everyJsoninstance used for server responses so a new field does not break old app versions. - Add auth headers in an application interceptor, not a network interceptor, because OkHttp strips
Authorizationon cross-host redirects. - Retry only idempotent methods (
GET,HEAD,PUT,DELETE,OPTIONS);POSTandPATCHneed an idempotency key the server honours. - Offline-first: the UI reads only from Room; the network result is written to Room; stale-while-revalidate emits cached data first and refreshes in the background.
HttpLoggingInterceptorand KtorLoggingbelong in debug builds only; always redact or sanitize theAuthorizationheader.errorBody()is one-shot: read it once withstring()and keep the result; a second read returns nothing.
APIs at a glance
| API or term | Use it for |
|---|---|
OkHttpClient | One per app from DI; call newBuilder() for variants that share the connection pool and dispatcher. |
Retrofit | Build once with baseUrl, client, addConverterFactory; create typed interfaces with create(). |
HttpClient (Ktor) | One per app; engines: OkHttp/Android on Android, Darwin on iOS, CIO on JVM and native. |
HttpLoggingInterceptor | Debug-only request/response logging; call redactHeader("Authorization") to hide tokens. |
ContentNegotiation | Ktor plugin: install with json(Json { ignoreUnknownKeys = true }) for forward-compatible parsing. |
Authenticator | OkHttp 401 handler; use synchronized + priorResponse check to refresh once and avoid loops. |
Auth / bearer | Ktor token plugin: loadTokens, refreshTokens with markAsRefreshTokenRequest(), sendWithoutRequest. |
@Serializable | kotlinx.serialization annotation; requires the org.jetbrains.kotlin.plugin.serialization compiler plugin. |
asConverterFactory | Retrofit converter for kotlinx.serialization; pass the request Content-Type media type. |
Cache | OkHttp disk cache with a mandatory size limit; evicts old entries when the limit is reached. |
CacheControl.FORCE_NETWORK / FORCE_CACHE | Bypass the cache for pull-to-refresh or return only cached data (504 if none usable). |
safeCall / ApiResult | Your own helper and sealed result type that map IOException, HTTP errors and SerializationException to typed branches. |
Snippets
OkHttp client with timeouts and debug-only logging
val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.apply {
if (BuildConfig.DEBUG) {
addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
redactHeader("Authorization")
})
}
}
.build()safeCall: map each failure type, re-throw cancellation
sealed interface ApiResult<out T> {
data class Ok<T>(val value: T) : ApiResult<T>
data class Http(val code: Int, val errorBody: String?) : ApiResult<Nothing>
data class Network(val cause: IOException) : ApiResult<Nothing>
data class Parse(val cause: SerializationException) : ApiResult<Nothing>
data class Unknown(val cause: Throwable) : ApiResult<Nothing>
}
suspend fun <T : Any> safeCall(block: suspend () -> Response<T>): ApiResult<T> =
try {
val r = block()
val body = r.body()
if (r.isSuccessful && body != null) ApiResult.Ok(body)
else ApiResult.Http(r.code(), r.errorBody()?.string())
} catch (e: CancellationException) {
throw e
} catch (e: IOException) {
ApiResult.Network(e)
} catch (e: SerializationException) {
ApiResult.Parse(e)
} catch (e: Exception) {
ApiResult.Unknown(e)
}TokenAuthenticator: refresh once, re-check token, limit retries
data class Tokens(val access: String, val refresh: String)
interface TokenStore {
val accessToken: String?
val refreshToken: String?
fun save(tokens: Tokens)
fun clear()
}
fun interface TokenRefresher { fun refresh(refreshToken: String): Tokens? } // blocking; null = rejected
class TokenAuthenticator(
private val tokens: TokenStore,
private val refresher: TokenRefresher,
) : Authenticator {
private val lock = Any()
override fun authenticate(route: Route?, response: Response): Request? {
if (response.priorResponse?.code == 401) return null // already retried once
val failedToken = response.request.header("Authorization")?.removePrefix("Bearer ")
synchronized(lock) {
val current = tokens.accessToken
if (current != null && current != failedToken) return response.request.withToken(current)
val refreshToken = tokens.refreshToken ?: return null
val fresh = refresher.refresh(refreshToken) ?: run { tokens.clear(); return null }
tokens.save(fresh)
return response.request.withToken(fresh.access)
}
}
private fun Request.withToken(token: String): Request =
newBuilder().header("Authorization", "Bearer $token").build()
}Ktor client with ContentNegotiation, HttpTimeout, and bearer Auth
fun createApiClient(tokens: TokenStore): HttpClient = HttpClient(OkHttp) {
expectSuccess = true
defaultRequest { url("https://api.example.com/") }
install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) }
install(HttpTimeout) { requestTimeoutMillis = 30_000; connectTimeoutMillis = 10_000 }
install(Auth) {
bearer {
loadTokens {
tokens.accessToken?.let { BearerTokens(it, tokens.refreshToken.orEmpty()) }
}
refreshTokens {
// Call the refresh endpoint with markAsRefreshTokenRequest(), save and return
// the new BearerTokens; returning null means the user must sign in again.
null
}
sendWithoutRequest { it.url.host == "api.example.com" }
}
}
}Rules of thumb
- Prefer one shared client from DI; use
newBuilder()for per-call-site variants instead of creating new instances. - Never swallow
CancellationException; re-throw it before anycatch (e: Exception)orrunCatching. - Prefer
ignoreUnknownKeys = trueon everyJsoninstance used for server responses. - Never add
HttpLoggingInterceptoror KtorLoggingin release builds; always redact or sanitizeAuthorization. - Prefer application interceptors for auth headers; never attach tokens in a network interceptor.
- Never retry
POSTorPATCHonIOExceptionwithout an idempotency key the server honours.
Gotchas
- Creating multiple OkHttpClient instances. Each instance owns its own connection pool and dispatcher, so calls cannot reuse each other's connections and pay extra TCP and TLS handshakes. Fix: share one client and use
newBuilder()for variants. - Catching CancellationException in a catch-all or runCatching. Cancellation becomes a fake failure and code after the catch (state updates, retries) runs for a screen that is gone. Fix: re-throw
CancellationExceptionbefore any general catch. - Adding the Authorization header in a network interceptor. OkHttp strips
Authorizationon cross-host redirects, and the network interceptor re-adds the token to the redirected host. Fix: add auth headers in an application interceptor. - Forgetting ignoreUnknownKeys = true on the Json instance. One new server field throws
SerializationExceptionin every app version that does not know it. Fix: setignoreUnknownKeys = trueand keep a test with extra keys. - Reading errorBody() twice. The error body stream is one-shot; the second call returns nothing or fails. Fix: read once with
string()and store the result. - Clearing the Room cache before the new data arrives. A delete-then-fetch leaves an empty screen if the fetch fails. Fix: fetch first, then upsert in one transaction.
Quick interview answers
Why should you create only one OkHttpClient (or Ktor HttpClient) per app?
Each client owns its own connection pool, dispatcher, and threads, so multiple clients prevent connection reuse and force a new TCP/TLS handshake per call. Provide one instance from DI and use newBuilder() when a call site needs different settings.
How do you handle a 401 token refresh without a thundering herd of refresh calls?
In OkHttp, wrap the refresh in synchronized inside the Authenticator and re-read the stored token after acquiring the lock; if another thread already refreshed, retry with the new token. In Ktor, the Auth plugin with bearer calls refreshTokens once even when several requests fail at the same time, and you mark the refresh request with markAsRefreshTokenRequest().
What is the difference between IOException and HttpException in Retrofit?
IOException means the request did not complete at all (no network, DNS failure, timeout, connection reset). HttpException means the server answered with a non-2xx status; it is thrown only when the suspend function returns the body type T directly, not when it returns Response<T>.
Why must you re-throw CancellationException instead of mapping it to an error result?
A catch-all or runCatching turns cancellation into a fake failure, and the code after the catch (state updates, retries) keeps running for a screen that is already gone. Re-throw CancellationException before any general catch (e: Exception) so the coroutine framework can cancel the chain cleanly.
How does stale-while-revalidate work in an offline-first architecture?
The UI observes a Room Flow and emits cached data immediately, then a background refresh writes the new result back to Room, and the Flow delivers the update. A failed refresh must not clear the cache, so the user still sees the last known data.
Why is ignoreUnknownKeys = true important for production apps?
Without it, kotlinx.serialization throws SerializationException when the server adds a field the app does not know, breaking every installed version that has not been updated. Setting ignoreUnknownKeys = true on the Json instance lets old apps ignore new fields and keeps the API forward-compatible.