Skip to content

Lesson 4 of 9 · 23m

Ktor Service Design Without Framework Fairy Dust

Structure a Ktor service around routing, plugins, serialization, status pages, and testable application modules.

Ktor feels small, which is precisely why teams get into trouble. They mistake fewer framework opinions for fewer architectural decisions. Ktor will happily let you build a service whose configuration, validation, persistence, and error handling are tangled into route handlers. Keep it small on purpose.

The application module is composition, not business logic

A healthy Ktor application function wires plugins and delegates behavior:

fun Application.module() {
    install(ContentNegotiation) {
        json(Json {
            ignoreUnknownKeys = true
            explicitNulls = false
        })
    }
    install(StatusPages) {
        exception<NotFoundException> { call, cause ->
            call.respond(HttpStatusCode.NotFound, ErrorResponse(cause.message ?: "not found"))
        }
    }
    routing { orderRoutes(orderService) }
}

Routes should translate HTTP into application calls and responses. They should not become transaction scripts with annotations missing.

Routing is an API contract

fun Route.orderRoutes(service: OrderService) {
    route("/v1/orders") {
        get("/{id}") {
            val id = call.parameters["id"]?.let(::OrderId)
                ?: throw BadRequestException("missing order id")
            val order = service.get(id) ?: throw NotFoundException("order not found")
            call.respond(order.toResponse())
        }
    }
}

Validation in the route should answer transport questions: missing parameter, malformed UUID, unsupported content type. Business validation belongs deeper. Mixing the two makes reuse and testing painful.

Clients need production tuning too

val upstream = HttpClient(CIO) {
    install(HttpTimeout) {
        requestTimeoutMillis = 2_000
        connectTimeoutMillis = 500
    }
    install(ContentNegotiation) { json() }
}

Configure connection limits, timeouts, retries, and JSON behavior. Retrying non-idempotent POSTs can create duplicate side effects. Test through testApplication for contract behavior, but keep service-level unit tests fast and separate.

Field notes

  • ignoreUnknownKeys = true helps compatibility but can hide mass-assignment mistakes; validate input models explicitly.
  • receive<T>() failure behavior depends on serialization and content type. Test malformed JSON, not just happy paths.

Was this lesson helpful?

Sign in to rate