Ktor client
Why it matters
- Ktor client is the usual HTTP client in Kotlin Multiplatform: the client code lives in
commonMainand 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,
expectSuccessleft at its default) cause real production incidents. - Ktor's
Authplugin covers the same job as an OkHttpInterceptor+Authenticatorpair: attach the token, refresh it on 401, retry.
The simple explanation
- A Ktor
HttpClientis 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 plugin | Responsibility | Retrofit / OkHttp equivalent |
|---|---|---|
ContentNegotiation + json() | Serialize and deserialize bodies with kotlinx.serialization | Converter factory (kotlinx.serialization, Moshi) |
HttpTimeout | Request, connect and socket timeouts | callTimeout, connectTimeout, readTimeout / writeTimeout |
HttpRequestRetry | Retry on server errors or exceptions with a delay | Custom interceptor (OkHttp only retries failed connections) |
Auth with bearer | Attach tokens, refresh on 401, retry | Interceptor + Authenticator |
Logging | Log requests and responses | HttpLoggingInterceptor (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
HttpClientper app, provided as a DI singleton. A client per request or per ViewModel wastes connections and threads; close short-lived clients withclose()oruse { }. - Engines:
OkHttporAndroidon Android,Darwinon iOS,CIOon JVM, Android and native. OkHttp is a JVM library, so its engine artifact cannot be added toiosMainat 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. ContentNegotiationwithjson(Json { ignoreUnknownKeys = true })lets a server add fields without breaking old app versions. It needs thektor-client-content-negotiationandktor-serialization-kotlinx-jsonartifacts.HttpTimeouthasrequestTimeoutMillis(whole call),connectTimeoutMillisandsocketTimeoutMillis(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 = truemakes non-2xx responses throwResponseExceptionsubclasses. With the defaultfalse, checkresponse.statusbefore callingbody().HttpRequestRetrywithretryOnServerErrors(maxRetries = 3)andexponentialDelay()retries 5xx responses. It does not look at the HTTP method, so limit it to idempotent requests withretryIfor disable it for a POST withretry { noRetry() }on that request.Authwithbearer { loadTokens { } ; refreshTokens { } }caches the tokens, and on 401 callsrefreshTokensonce even when several requests fail at the same time, then retries them. InsiderefreshTokens, callmarkAsRefreshTokenRequest()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
Loggingonly in debug builds and callsanitizeHeader { it == HttpHeaders.Authorization }.LogLevel.BODYorALLlogs bodies, which can contain personal data. - Ktor calls are suspend functions and cancel cleanly. Do not wrap them in a catch-all or
runCatchingthat turnsCancellationExceptioninto 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-authandktor-client-logging, plus the Kotlin serialization compiler plugin. HttpRequestRetryhere retries any method on 5xx. In a real app add aretryIfthat checks for idempotent methods, or callretry { 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
- 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)ininitand 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.
- 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.
- After a backend incident, crash reports showed
JsonConvertExceptionfrombody<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 onlyIOExceptionwas mapped to an error state.
- Set
expectSuccess = trueon the shared client so non-2xx responses throwClientRequestExceptionorServerResponseException. - Mapped
ResponseExceptionto an HTTP error state with the status code, andContentConvertException(the parent ofJsonConvertException, which wraps the kotlinx.serialization error) to a separate parse error state. - Added tests with Ktor's
MockEnginereturning 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
iosMainorcommonMainfor native targets. UseDarwinon 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. TurnexpectSuccesson or checkresponse.statusfirst. - Retrying every request.
HttpRequestRetrydoes 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
runCatchingaround 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)
-
Add dependencies in
app/build.gradle.kts, using one Ktor 3 version for all of them (orplatform("io.ktor:ktor-bom:<version>")):io.ktor:ktor-client-coreio.ktor:ktor-client-okhttpio.ktor:ktor-client-content-negotiationio.ktor:ktor-serialization-kotlinx-jsonio.ktor:ktor-client-authio.ktor:ktor-client-logging- Apply the serialization compiler plugin
org.jetbrains.kotlin.plugin.serializationwith the same version as your Kotlin plugin.
-
Create
ApiClient.ktin thenetworkpackage. Build a singleHttpClient(OkHttp)withexpectSuccess = true,ContentNegotiation(usingJson { ignoreUnknownKeys = true }),HttpTimeout(30 s request, 10 s connect, 15 s socket), andAuthwithbearer { loadTokens { ... } }reading from a token store. InstallLoggingonly whenBuildConfig.DEBUGis true, withsanitizeHeaderforAuthorization. -
Provide the client as a singleton from your DI setup (or a lazy property in an app container).
-
Write a suspend function
fetchUsers(): List<User>that callsclient.get("https://api.example.com/users").body(). DefineUserwith@Serializable. -
Map errors in the repository:
ResponseExceptionto an HTTP error withe.response.status.value,IOExceptionto a network error,ContentConvertException(Ktor wraps parse failures inJsonConvertException) to a parse error. Do not catchCancellationException. -
Test it with
MockEnginefromktor-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.