Ktor client

Learn Ktor HttpClient for Android and Kotlin Multiplatform, covering engines, plugins like Auth and Logging, error handling, and KMP networking. About 25 minutes.

Why it matters

  • Ktor client is the usual HTTP client in Kotlin Multiplatform: the client code lives in commonMain and only the engine differs per platform, so Android and iOS share one networking layer.
  • Interviewers at KMP shops ask you to compare Ktor's plugin model with Retrofit's interface + converter model and explain when each wins.
  • Misconfigured plugins (logging in release, no timeouts, a client per request, expectSuccess left at its default) cause real production incidents.
  • Ktor's Auth plugin covers the same job as an OkHttp Interceptor + Authenticator pair: attach the token, refresh it on 401, retry.

The simple explanation

  • A Ktor HttpClient is a restaurant kitchen with a fixed line of stations (plugins) in front of the stove (the engine).

You create one HttpClient with an engine and install plugins that each handle one concern. The engine does the actual I/O: OkHttp or Android on Android, Darwin (NSURLSession) on iOS, CIO (pure Kotlin coroutines) on JVM, Android and native targets. Plugins hook into fixed phases of the request and response pipelines, so their effect depends on those phases, not only on the order you install them.

The main difference from Retrofit: there is no service interface. You call client.get("users/1") and get an HttpResponse; response.body<User>() converts the body through the ContentNegotiation plugin, which wraps a kotlinx.serialization Json instance. Retrofit builds a dynamic proxy from an annotated interface at runtime and needs a converter factory. Neither library checks your URLs at compile time.

Ktor pluginResponsibilityRetrofit / OkHttp equivalent
ContentNegotiation + json()Serialize and deserialize bodies with kotlinx.serializationConverter factory (kotlinx.serialization, Moshi)
HttpTimeoutRequest, connect and socket timeoutscallTimeout, connectTimeout, readTimeout / writeTimeout
HttpRequestRetryRetry on server errors or exceptions with a delayCustom interceptor (OkHttp only retries failed connections)
Auth with bearerAttach tokens, refresh on 401, retryInterceptor + Authenticator
LoggingLog requests and responsesHttpLoggingInterceptor (debug only)

expectSuccess is false by default: a 404 or 500 is returned as a normal HttpResponse, and calling body<User>() on it tries to parse the error body as a User. Set expectSuccess = true to make non-2xx responses throw ClientRequestException (4xx), ServerResponseException (5xx) or RedirectResponseException (3xx), all subclasses of ResponseException, or check response.status yourself.

Use one HttpClient for the app, provided by DI. Creating a client is expensive (engine, connection pool, threads). A client you create for a shorter scope, such as a test, should be closed with close() or use { }.

Notes

  • One HttpClient per app, provided as a DI singleton. A client per request or per ViewModel wastes connections and threads; close short-lived clients with close() or use { }.
  • Engines: OkHttp or Android on Android, Darwin on iOS, CIO on JVM, Android and native. OkHttp is a JVM library, so its engine artifact cannot be added to iosMain at all.
  • In KMP you can write HttpClient { ... } in common code without an engine argument; Ktor uses the engine dependency added to each platform's source set.
  • ContentNegotiation with json(Json { ignoreUnknownKeys = true }) lets a server add fields without breaking old app versions. It needs the ktor-client-content-negotiation and ktor-serialization-kotlinx-json artifacts.
  • HttpTimeout has requestTimeoutMillis (whole call), connectTimeoutMillis and socketTimeoutMillis (maximum gap between data packets). If you do not set them, the plugin adds no limits and only the engine's own defaults apply (OkHttp's are 10 s connect, read and write).
  • expectSuccess = true makes non-2xx responses throw ResponseException subclasses. With the default false, check response.status before calling body().
  • HttpRequestRetry with retryOnServerErrors(maxRetries = 3) and exponentialDelay() retries 5xx responses. It does not look at the HTTP method, so limit it to idempotent requests with retryIf or disable it for a POST with retry { noRetry() } on that request.
  • Auth with bearer { loadTokens { } ; refreshTokens { } } caches the tokens, and on 401 calls refreshTokens once even when several requests fail at the same time, then retries them. Inside refreshTokens, call markAsRefreshTokenRequest() on the refresh request so its own 401 does not start another refresh.
  • sendWithoutRequest { request -> ... } decides whether the token is attached before any 401. Restrict it to your API host so the token is never sent to other hosts.
  • Install Logging only in debug builds and call sanitizeHeader { it == HttpHeaders.Authorization }. LogLevel.BODY or ALL logs bodies, which can contain personal data.
  • Ktor calls are suspend functions and cancel cleanly. Do not wrap them in a catch-all or runCatching that turns CancellationException into a failure.

Code example

This shows a production-style Ktor 3 client with the OkHttp engine, JSON, timeouts, retry for server errors, bearer auth with refresh, debug-only logging, and a typed call.

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.engine.okhttp.OkHttp
import io.ktor.client.plugins.ClientRequestException
import io.ktor.client.plugins.HttpRequestRetry
import io.ktor.client.plugins.HttpTimeout
import io.ktor.client.plugins.auth.Auth
import io.ktor.client.plugins.auth.providers.BearerTokens
import io.ktor.client.plugins.auth.providers.bearer
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.defaultRequest
import io.ktor.client.plugins.logging.ANDROID
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.forms.submitForm
import io.ktor.client.request.get
import io.ktor.http.HttpHeaders
import io.ktor.http.parameters
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
 
interface TokenStore {
    suspend fun load(): BearerTokens?
    suspend fun save(tokens: BearerTokens)
    suspend fun clear() // also triggers the app's logout flow
}
 
@Serializable
data class TokenResponse(val accessToken: String, val refreshToken: String)
 
@Serializable
data class User(val id: Long, val name: String, val email: String? = null)
 
// Create once and provide as a singleton from DI.
fun createApiClient(tokens: TokenStore, debug: Boolean): HttpClient = HttpClient(OkHttp) {
    expectSuccess = true // 4xx -> ClientRequestException, 5xx -> ServerResponseException
    defaultRequest { url("https://api.example.com/") }
 
    install(ContentNegotiation) {
        json(Json { ignoreUnknownKeys = true })
    }
    install(HttpTimeout) {
        requestTimeoutMillis = 30_000
        connectTimeoutMillis = 10_000
        socketTimeoutMillis = 15_000
    }
    install(HttpRequestRetry) {
        retryOnServerErrors(maxRetries = 2)
        exponentialDelay()
    }
    install(Auth) {
        bearer {
            loadTokens { tokens.load() }
            refreshTokens {
                try {
                    val fresh: TokenResponse = client.submitForm(
                        url = "https://api.example.com/oauth/token",
                        formParameters = parameters {
                            append("grant_type", "refresh_token")
                            append("refresh_token", oldTokens?.refreshToken.orEmpty())
                        }
                    ) { markAsRefreshTokenRequest() }.body()
                    BearerTokens(fresh.accessToken, fresh.refreshToken).also { tokens.save(it) }
                } catch (e: ClientRequestException) {
                    tokens.clear() // refresh token rejected: log out
                    null // Ktor gives up and the original 401 reaches the caller
                }
            }
            sendWithoutRequest { request -> request.url.host == "api.example.com" }
        }
    }
    if (debug) {
        install(Logging) {
            logger = Logger.ANDROID
            level = LogLevel.HEADERS
            sanitizeHeader { header -> header == HttpHeaders.Authorization }
        }
    }
}
 
suspend fun fetchUser(client: HttpClient, id: Long): User =
    client.get("users/$id").body() // throws ResponseException on non-2xx because of expectSuccess
  • Dependencies: ktor-client-core, ktor-client-okhttp, ktor-client-content-negotiation, ktor-serialization-kotlinx-json, ktor-client-auth and ktor-client-logging, plus the Kotlin serialization compiler plugin.
  • HttpRequestRetry here retries any method on 5xx. In a real app add a retryIf that checks for idempotent methods, or call retry { noRetry() } on POST requests.
  • The refresh call catches only ClientRequestException, so cancellation and network errors are not mistaken for a rejected refresh token.

Run the idea in plain Kotlin

This models two client settings: a retry rule that only retries idempotent methods on 5xx, and expectSuccess, which decides whether a non-2xx status throws or is returned.

import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking

class ResponseException(val status: Int) : Exception("HTTP " + status)

// Fake engine: answers from a script of status codes
class FakeEngine(private val script: MutableList<Int>) {
  suspend fun execute(method: String, path: String): Int {
      delay(1)
      val status = script.removeAt(0)
      println("  engine: " + method + " " + path + " -> " + status)
      return status
  }
}

class MiniClient(
  private val engine: FakeEngine,
  private val expectSuccess: Boolean,
  private val maxRetries: Int,
) {
  suspend fun request(method: String, path: String): Int {
      var attempt = 0
      while (true) {
          val status = engine.execute(method, path)
          // Our own retryIf rule: only 5xx, only idempotent methods
          val retryable = status in 500..599 && method in setOf("GET", "PUT", "DELETE")
          if (retryable && attempt < maxRetries) {
              val wait = 100L shl attempt // exponential: 100, 200, 400 ms (not actually waited here)
              println("  retry " + (attempt + 1) + " after " + wait + " ms")
              attempt++
              continue
          }
          if (expectSuccess && status !in 200..299) throw ResponseException(status)
          return status
      }
  }
}

fun main() = runBlocking {
  println("GET with two 503s:")
  val a = MiniClient(FakeEngine(mutableListOf(503, 503, 200)), expectSuccess = true, maxRetries = 3)
  println("result: " + a.request("GET", "/users/1"))

  println("POST with a 503 (not retried):")
  val b = MiniClient(FakeEngine(mutableListOf(503)), expectSuccess = true, maxRetries = 3)
  try {
      b.request("POST", "/orders")
  } catch (e: ResponseException) {
      println("error: " + e.message)
  }

  println("expectSuccess = false, 404:")
  val c = MiniClient(FakeEngine(mutableListOf(404)), expectSuccess = false, maxRetries = 3)
  println("result: " + c.request("GET", "/users/999") + " (no exception, check the status yourself)")
}

Expected output:

GET with two 503s:
  engine: GET /users/1 -> 503
  retry 1 after 100 ms
  engine: GET /users/1 -> 503
  retry 2 after 200 ms
  engine: GET /users/1 -> 200
result: 200
POST with a 503 (not retried):
  engine: POST /orders -> 503
error: HTTP 503
expectSuccess = false, 404:
  engine: GET /users/999 -> 404
result: 404 (no exception, check the status yourself)

In production

Socket and thread growth from per-screen clients
  • After long sessions with many screen navigations, the app slowed down and some devices hit "Too many open files" errors.
  • Each ViewModel created its own HttpClient(OkHttp) in init and never closed it, so every screen added another engine with its own connection pool and threads.
  • Idle connections and threads from old clients stayed alive long after the screens were gone.
The fix
  • Reproduced on a debug build by navigating repeatedly and counting open descriptors with adb shell run-as <package> ls /proc/<pid>/fd | wc -l.
  • Moved client creation into a DI singleton module and injected the one client into repositories.
  • Added a lint or code-review rule that flags HttpClient( outside the networking module.
Error pages parsed as data
  • After a backend incident, crash reports showed JsonConvertException from body<User>() calls instead of a clean error screen.
  • The client used the default expectSuccess = false, so a 503 HTML page was returned as a normal response.
  • The repository called body<User>() without checking the status, so the HTML was fed to the JSON parser, and only IOException was mapped to an error state.
The fix
  • Set expectSuccess = true on the shared client so non-2xx responses throw ClientRequestException or ServerResponseException.
  • Mapped ResponseException to an HTTP error state with the status code, and ContentConvertException (the parent of JsonConvertException, which wraps the kotlinx.serialization error) to a separate parse error state.
  • Added tests with Ktor's MockEngine returning 404, 503 with an HTML body, and malformed JSON.

Common mistakes

  • Creating a new HttpClient per request or per ViewModel. Each client owns an engine, connection pool and threads. Create one in DI and share it; close clients you create for a short scope.
  • Trying to use the OkHttp engine on iOS. OkHttp is a JVM library, so the engine artifact cannot be used from iosMain or commonMain for native targets. Use Darwin on iOS, or let each source set add its own engine dependency.
  • Leaving the Logging plugin in release builds. It writes headers and possibly bodies to logcat. Install it only for debug and sanitize Authorization.
  • Not setting ignoreUnknownKeys on the Json instance. By default kotlinx.serialization throws on unknown keys, so a new server field breaks every app version that does not know it.
  • Calling body() without expectSuccess or a status check. With the default expectSuccess = false, an error response is parsed as if it were data. Turn expectSuccess on or check response.status first.
  • Retrying every request. HttpRequestRetry does not check the HTTP method. Retrying a POST after a timeout can create a duplicate order. Restrict retries to idempotent requests or use an idempotency key.
  • Catching CancellationException and mapping it to a failure result. A catch-all or runCatching around a Ktor call turns cancellation into a fake error. Re-throw it.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Why would a team choose Ktor over Retrofit for a Kotlin Multiplatform project?”

“How does ContentNegotiation work, and what happens if you forget to install it?”

“How does Ktor's Auth plugin handle a 401, and how does that compare to an OkHttp Authenticator?”

“What are the three timeouts in HttpTimeout and why are they separate?”

Quiz

What happens if you call body<User>() on an HttpResponse but ContentNegotiation is not installed?

Which Ktor engine is the usual choice for the iOS target of a Kotlin Multiplatform app?

A Ktor client uses the default expectSuccess = false. The server returns 500 with an HTML error page and your code calls response.body<User>(). What happens?

What does markAsRefreshTokenRequest() do inside the bearer refreshTokens block?

0 of 4 answered

Mini task

Add Ktor client to an existing Android module (15 min)

  1. Add dependencies in app/build.gradle.kts, using one Ktor 3 version for all of them (or platform("io.ktor:ktor-bom:<version>")):

    • io.ktor:ktor-client-core
    • io.ktor:ktor-client-okhttp
    • io.ktor:ktor-client-content-negotiation
    • io.ktor:ktor-serialization-kotlinx-json
    • io.ktor:ktor-client-auth
    • io.ktor:ktor-client-logging
    • Apply the serialization compiler plugin org.jetbrains.kotlin.plugin.serialization with the same version as your Kotlin plugin.
  2. Create ApiClient.kt in the network package. Build a single HttpClient(OkHttp) with expectSuccess = true, ContentNegotiation (using Json { ignoreUnknownKeys = true }), HttpTimeout (30 s request, 10 s connect, 15 s socket), and Auth with bearer { loadTokens { ... } } reading from a token store. Install Logging only when BuildConfig.DEBUG is true, with sanitizeHeader for Authorization.

  3. Provide the client as a singleton from your DI setup (or a lazy property in an app container).

  4. Write a suspend function fetchUsers(): List<User> that calls client.get("https://api.example.com/users").body(). Define User with @Serializable.

  5. Map errors in the repository: ResponseException to an HTTP error with e.response.status.value, IOException to a network error, ContentConvertException (Ktor wraps parse failures in JsonConvertException) to a parse error. Do not catch CancellationException.

  6. Test it with MockEngine from ktor-client-mock: return 200 with JSON, 404, and malformed JSON, and assert each mapped result.

Done condition: The app builds, the call returns a list or a mapped error, the three MockEngine tests pass, and the Logging plugin is not installed in the release build.

Next: Serialization: kotlinx vs Moshi