Skip to content
Tutorials Center
My learning

Topics

Lesson 112 of 134 ยท Testing and Tooling

Kotlin on the Server

Learn how Kotlin is used on the server: Ktor and Spring Boot, routing DSLs, middleware, JSON, and coroutines for concurrent requests, with runnable stand-ins and a real loopback HTTP server.

Kotlin is a first-class language for backend services. It runs on the JVM, so it inherits two decades of server libraries, monitoring tools, hosting options and performance engineering, and it adds a more concise, safer language on top. Companies write REST APIs, event processors and internal tools in Kotlin, often alongside Java in the same codebase (see Java Interoperability).

This lesson shows the shape of a Kotlin server: the two main frameworks, how routing, middleware and JSON work, and why coroutines fit servers so well. The runner on this site has no Gradle, no Ktor, no Spring and no network except the loopback address, so framework code appears as read-only snippets. For the runnable parts we use the JDK's built-in HTTP server and hand-written stand-ins that follow the same design as the frameworks. You will see a real request travel through a real server in the first example.

The smallest real server

The JDK ships a small HTTP server (com.sun.net.httpserver) and an HTTP client (java.net.http). They are plain Java classes, usable from Kotlin as they are. The following program starts a server on a free port of the loopback address, calls it with the client, prints the answer and stops it:

Kotlin A real HTTP server on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A request is a method (GET), a path, headers and an optional body; a response is a status code, headers and a body. That is all a server does: read the request, produce a response. Three things in this code are worth noticing. Port 0 asks the system for any free port. The handler is a Kotlin lambda where Java expects an HttpHandler (SAM conversion). And /missing returns 404 with no code of ours involved: unmatched paths are the server's job.

A raw server like this gets tedious fast: manual routing, manual parsing, manual headers, manual JSON. Frameworks remove that. In the Kotlin world there are two big families.

Ktor: the Kotlin-native framework

Ktor is built by JetBrains, written in Kotlin and designed around coroutines and DSLs. A server is a function that installs features and describes routes with lambdas. Read-only:

Kotlin
// read-only example: needs the Ktor dependencies and Gradle
fun main() {
    embeddedServer(Netty, port = 8080) {
        install(ContentNegotiation) { json() }          // JSON in and out

        routing {
            get("/") {
                call.respondText("Notes API")
            }
            get("/notes/{id}") {
                val id = call.parameters["id"]?.toIntOrNull()
                    ?: return@get call.respond(HttpStatusCode.BadRequest, "id must be a number")
                val note = notes.find(id)
                    ?: return@get call.respond(HttpStatusCode.NotFound)
                call.respond(note)                      // serialized to JSON
            }
            post("/notes") {
                val draft = call.receive<NewNote>()     // JSON parsed into a data class
                call.respond(HttpStatusCode.Created, notes.add(draft))
            }
        }
    }.start(wait = true)
}

The shape is plain Kotlin: routing { ... } takes a lambda with a receiver (see Type-Safe Builders and DSLs), each route's handler is a suspend lambda (so it can call suspending database or HTTP clients without blocking a thread), and call is the object representing the current request/response. Ktor is lightweight: you pick the features you want, and nothing else is loaded.

We can build the heart of that design ourselves in a few lines. This stand-in has a routing DSL with path parameters, handlers that return responses, and a router that matches a request to a handler. It runs entirely in memory, with no sockets, so it is also how you can test routing logic quickly:

Kotlin A tiny Ktor-style routing DSL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the shape: a function routing { ... } takes a lambda with a receiver, so inside it get(...) and post(...) are methods of the Routing object. That is exactly how Ktor (and Gradle's Kotlin DSL) feels. The return@get early exits use a label (see break, continue and Labels) to return from the handler lambda only.

Middleware: functions that wrap functions

Real servers do much more than routing. Every request should be logged, authenticated, timed and have errors turned into proper responses. Instead of repeating that in each handler, frameworks use middleware (Ktor calls them plugins, Spring calls them filters and interceptors): a function that takes a handler and returns a new handler that does something before and after calling it. In Kotlin this is just higher-order functions (see Higher-Order Functions):

Kotlin Middleware as function composition

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

with(logging, catchErrors, requireToken) builds an onion: the first layer sees the request first and the response last. The unauthorized call is stopped by requireToken before reaching the handler, but because logging is outermost it still logs both lines. The order of layers matters, and it is a common source of surprises (for example, an error handler placed inside the authentication layer will not catch authentication failures).

Spring Boot: the enterprise default

Spring Boot is the most widely used JVM framework, and Kotlin is an officially supported language for it, with many Kotlin-specific APIs. If your company already runs Spring, you can write the next controller in Kotlin. Read-only:

Kotlin
// read-only example: needs Spring Boot and the kotlin-spring Gradle plugin
@RestController
@RequestMapping("/notes")
class NoteController(private val service: NoteService) {

    @GetMapping("/{id}")
    fun get(@PathVariable id: Int): ResponseEntity<Note> =
        service.find(id)?.let { ResponseEntity.ok(it) }
            ?: ResponseEntity.notFound().build()

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    fun create(@RequestBody draft: NewNote): Note = service.add(draft)
}

@Service
class NoteService(private val repository: NoteRepository)   // constructor injection

data class Note(val id: Int, val text: String)
data class NewNote(val text: String)

Things Kotlin gives you here: constructor injection with val parameters (no boilerplate fields), ?.let { } ?: ... instead of Optional, data classes as request and response bodies, and nullable types in the signatures, which Spring maps to "optional parameter". There is one well-known catch. Spring creates proxies by subclassing your classes (for transactions, caching, security), but Kotlin classes are final by default. Without help, the proxy cannot extend them. This is the problem in a minimal form:

Kotlin Classes are final by default (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler rejects this with error: this type is final, so it cannot be extended (and a second error says that find in NoteService is final and cannot be overridden). The fix in plain Kotlin is open class NoteService and open fun find. In Spring projects you do not write open everywhere: the kotlin-spring compiler plugin (a Gradle plugin, read-only here) makes classes with Spring annotations open automatically, and kotlin-jpa generates the no-argument constructor that JPA entities need. Forgetting those plugins is the classic first-day Kotlin-with-Spring error.

JSON and data classes

Server code mostly turns JSON into objects and back. Kotlin data classes are ideal request and response types, and kotlinx.serialization (a compiler plugin plus library, read-only here) or Jackson with the Kotlin module do the conversion:

Kotlin
// read-only example: needs kotlinx.serialization and its Gradle plugin
@Serializable
data class Note(val id: Int, val text: String, val done: Boolean = false)

val json = Json.encodeToString(Note(1, "Buy milk"))              // {"id":1,"text":"Buy milk"}
val note = Json.decodeFromString<Note>("""{"id":2,"text":"Call Ana","done":true}""")

The type system catches mistakes that dynamic languages find in production: a missing required field is a decoding error, not a silent undefined. Default values (done = false) make fields optional. Use nullable types for values that really may be absent. See Working with JSON Text for what JSON looks like at the character level.

Coroutines: many requests, few threads

A classic server dedicates one thread to each request. Threads are heavy (memory and scheduling cost), and most of a request's life is spent waiting for a database or another service, with the thread blocked and idle. Coroutines make waiting cheap: a suspended coroutine releases its thread, so a few threads can serve thousands of requests in flight (see Suspend Functions).

Coroutines also make concurrency inside one request simple. A handler that needs a user and their orders from two services can ask for both at once instead of one after the other:

Kotlin Two backend calls in parallel inside one request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

We avoided timings (they vary between runs) and counted how many calls were in flight at once instead. The parallel version runs both at the same time, so the request takes about as long as the slowest call, not the sum. Because async lives inside coroutineScope, structured concurrency applies: if one call fails, its sibling is cancelled and the exception reaches the handler (see Structured Concurrency).

A suspend function must not call blocking code on a shared thread: a blocking JDBC call or Thread.sleep inside a handler ties up one of the few worker threads. Move blocking work to withContext(Dispatchers.IO) (see Dispatchers and Context), or use a non-blocking client. Spring MVC users on recent JDKs can also use virtual threads, which make blocking cheap again.

Choosing a stack

If you want... Consider
A Kotlin-native, small, coroutine-first service Ktor
The widest ecosystem, existing Spring team, enterprise integrations Spring Boot with Kotlin
Quarkus or Micronaut features (fast startup, native images) Both support Kotlin
Very small scripts or internal tools The JDK HTTP server shown above

Whichever you pick, the habits that make Kotlin servers good are the same: immutable data classes for DTOs, sealed results for expected failures, constructor injection, small suspending functions, and tests that use fakes instead of a running server (see Test Doubles).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does port 0 mean when creating a server socket?

    Port 0 asks the system for a free port, which you can read back from the server address. It avoids conflicts in tests.
  2. 2. What is Ktor's routing { ... } block technically?

    The receiver gives the lambda access to get, post and other functions, which is the type-safe builder pattern.
  3. 3. Why do Spring projects in Kotlin use the kotlin-spring plugin?

    The plugin opens classes carrying Spring annotations so the proxies for transactions and security can extend them.
  4. 4. Two independent backend calls are needed in one request. Which is the better coroutine approach?

    async starts both calls at once, and the surrounding coroutineScope keeps failure and cancellation tied to the request.
  5. 5. In the middleware example, logging is listed first in with(logging, catchErrors, requireToken). What does that mean?

    The layers wrap each other like an onion. The first listed layer is the outermost one, which is why it logs even rejected requests.

Summary

  • A server reads a request and produces a response; the JDK has a basic HTTP server, and frameworks add routing, parsing and plugins.
  • Ktor is Kotlin-native: routes are lambdas with receivers, handlers are suspend functions, JSON arrives as data classes.
  • Spring Boot is the enterprise default; use the kotlin-spring and kotlin-jpa plugins because Kotlin classes are final by default.
  • Middleware is function composition: each layer wraps the next handler, and layer order matters.
  • Data classes plus a serialization library give typed JSON handling; sealed types model expected failures.
  • Coroutines serve many requests on few threads, and async inside coroutineScope runs independent calls in parallel; keep blocking calls off the main worker threads.

Next: Kotlin Multiplatform