Networking cheat sheet

Revise Android networking: Retrofit, OkHttp, Ktor, kotlinx.serialization, error handling, auth interceptors, and offline caching with Room.

Key ideas

  1. Provide one OkHttpClient or Ktor HttpClient from DI; use newBuilder() for per-call-site variants so the connection pool is shared.
  2. IOException means no response (DNS, timeout, reset); HttpException means a non-2xx answer; SerializationException means a contract mismatch — map each to its own error type.
  3. Never let CancellationException become an error result; re-throw it before any catch (e: Exception) or runCatching.
  4. Set connectTimeout, readTimeout, writeTimeout, and callTimeout deliberately; the OkHttp defaults are 10 s each and no call limit.
  5. Set ignoreUnknownKeys = true on every Json instance used for server responses so a new field does not break old app versions.
  6. Add auth headers in an application interceptor, not a network interceptor, because OkHttp strips Authorization on cross-host redirects.
  7. Retry only idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS); POST and PATCH need an idempotency key the server honours.
  8. 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.
  9. HttpLoggingInterceptor and Ktor Logging belong in debug builds only; always redact or sanitize the Authorization header.
  10. errorBody() is one-shot: read it once with string() and keep the result; a second read returns nothing.

APIs at a glance

API or termUse it for
OkHttpClientOne per app from DI; call newBuilder() for variants that share the connection pool and dispatcher.
RetrofitBuild 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.
HttpLoggingInterceptorDebug-only request/response logging; call redactHeader("Authorization") to hide tokens.
ContentNegotiationKtor plugin: install with json(Json { ignoreUnknownKeys = true }) for forward-compatible parsing.
AuthenticatorOkHttp 401 handler; use synchronized + priorResponse check to refresh once and avoid loops.
Auth / bearerKtor token plugin: loadTokens, refreshTokens with markAsRefreshTokenRequest(), sendWithoutRequest.
@Serializablekotlinx.serialization annotation; requires the org.jetbrains.kotlin.plugin.serialization compiler plugin.
asConverterFactoryRetrofit converter for kotlinx.serialization; pass the request Content-Type media type.
CacheOkHttp disk cache with a mandatory size limit; evicts old entries when the limit is reached.
CacheControl.FORCE_NETWORK / FORCE_CACHEBypass the cache for pull-to-refresh or return only cached data (504 if none usable).
safeCall / ApiResultYour 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 any catch (e: Exception) or runCatching.
  • Prefer ignoreUnknownKeys = true on every Json instance used for server responses.
  • Never add HttpLoggingInterceptor or Ktor Logging in release builds; always redact or sanitize Authorization.
  • Prefer application interceptors for auth headers; never attach tokens in a network interceptor.
  • Never retry POST or PATCH on IOException without 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 CancellationException before any general catch.
  • Adding the Authorization header in a network interceptor. OkHttp strips Authorization on 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 SerializationException in every app version that does not know it. Fix: set ignoreUnknownKeys = true and 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.

Go deeper