Skip to content

Lesson 7 of 9 · 27m

Networking with Retrofit and OkHttp: Resilience Over Happy Path

Model API failure honestly, configure timeouts and interceptors, handle offline behavior, and avoid leaking credentials or corrupting state.

Mobile networking is not distributed systems with smaller screens. It is distributed systems while the network interface flaps in an elevator, the user switches from Wi-Fi to cellular, TLS interception breaks certificates, and the process can die after the server committed the write. The happy path is the least interesting part of the design.

Timeouts are product requirements

Retrofit delegates transport behavior to OkHttp. Defaults are not necessarily your product's defaults:

val client = OkHttpClient.Builder()
    .connectTimeout(5, TimeUnit.SECONDS)
    .readTimeout(10, TimeUnit.SECONDS)
    .writeTimeout(10, TimeUnit.SECONDS)
    .retryOnConnectionFailure(true)
    .build()

val api = Retrofit.Builder()
    .baseUrl("https://api.sudosecurity.org/")
    .client(client)
    .addConverterFactory(MoshiConverterFactory.create())
    .build()
    .create(OrderApi::class.java)

A splash screen that waits a minute because someone omitted a read timeout is not robust; it is frozen with extra steps.

Model outcomes, not exceptions in a trench coat

Avoid throwing every transport and API failure through the same path:

sealed interface ApiResult<out T> {
    data class Ok<T>(val value: T) : ApiResult<T>
    data class HttpError(val code: Int, val body: String?) : ApiResult<Nothing>
    data object Offline : ApiResult<Nothing>
    data object Unauthorized : ApiResult<Nothing>
}

A 401 means re-authentication or revocation handling. A 409 means state conflict. Offline means queue or stale data. Collapsing these into "Something went wrong" teaches users to retry destructive operations blindly.

Interceptors are powerful and dangerous

Authentication refresh belongs in a carefully serialized interceptor or authenticator, not a copy-pasted callback circus. Logging belongs behind debug configuration:

if (BuildConfig.DEBUG) {
    addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.HEADERS))
}

Never ship body logging of authorization headers, cookies, tokens, payment details, or personal data. Redact before logging. Redacting after the leak is not a strategy.

TLS and certificate decisions have consequences

Use HTTPS and the platform trust store. Certificate pinning can reduce some interception risk but creates operational fragility when keys rotate. If pinning is required, plan backup pins and emergency release paths. Do not disable hostname verification to accommodate a staging certificate; that one-line workaround has a way of escaping into production.

Offline behavior is a state machine

Decide whether reads can be stale, whether writes queue, and how conflicts resolve:

network unavailable      -> show cached data and pending-state banner
POST accepted locally    -> durable outbox row, enqueue upload
server returns 4xx       -> permanent failure; do not retry blindly
server returns 5xx/timeout -> retry with backoff and idempotency key

Retries without idempotency keys create duplicate orders, duplicate messages, and duplicate payments. Mobile clients are exactly where at-least-once delivery appears.

Field notes

  • Test airplane mode, captive portals, 2G throttling, network switching, and process death between request and response.
  • ETag/cache behavior can save bandwidth but must respect privacy and authentication boundaries.
  • Cancellation of the client coroutine does not imply the server transaction was rolled back.
  • HTTP response bodies can be large; streaming and pagination matter on constrained memory.
  • retryOnConnectionFailure(true) is not permission to retry non-idempotent business operations forever.

Was this lesson helpful?

Sign in to rate