Kest
Concurrency model
How Kest uses threads, virtual threads, Kotlin coroutines and several processes, and what that means for your code.
A Node.js application runs your JavaScript on one thread and scales by starting more processes. On the JVM one process can run thousands of requests truly in parallel, and processes can still be added. Kest is written for that, and it supports Kotlin coroutines as a first-class way to write the code inside.
Threads in one process
| Where | What runs | Thread |
|---|---|---|
| HTTP on Netty (default) | each request | a virtual thread, so it may block (JDBC, HTTP calls) without costing an operating-system thread |
@NonBlocking routes | the handler | the Netty I/O thread, for the cheapest possible dispatch |
suspend handlers, guards, interceptors | the coroutine | the thread of the request, so it may suspend without losing its place |
| Queue workers | @Process methods | one virtual thread per worker, concurrency of them per queue per instance |
@Async methods | the method | a new virtual thread per call |
| Messaging, WebSocket, gRPC handlers | each message or call | virtual threads |
| Scheduled jobs | @Cron, @Interval | the scheduler, overlap off by default |
Because handlers run in parallel, providers are shared between threads. A singleton must not keep per-request state in fields.
The one rule
A singleton is used by many threads at once. Keep it stateless, or protect what it holds: AtomicInteger, ConcurrentHashMap, immutable data classes. Use Scope.REQUEST for state that belongs to one request.
@Injectable
class Counter {
private val hits = java.util.concurrent.atomic.AtomicLong() // fine: atomic
fun hit() = hits.incrementAndGet()
}What the framework itself does to stay safe: the metrics registry uses lock-free adders, the cache stores and Redis pools are thread-safe, the router is immutable after start, and event streams in CQRS synchronise their stateful operators. These are covered by tests that hammer them from 8 to 16 threads and check that nothing is lost or doubled.
Blocking is fine, until it is not
On a virtual thread, blocking costs almost nothing, so write straightforward code. Two cases are different:
@NonBlockingputs a handler on the I/O thread. If it blocks, every connection on that thread stalls. Kest watches for this: a route that holds the thread longer than 10 ms is logged with the stack it was stuck in and moved to virtual threads from then on. See Engines and performance.- CPU-heavy work occupies a core whatever the thread type. Run it with a bounded pool, or on a worker process.
Kotlin coroutines
Any Kest method can be a suspend function: route handlers, guards, interceptors, exception filters, provider factories, repository methods, queue and event handlers, and methods with @Retry or @Transactional. Kest depends on kotlinx-coroutines-core, so coroutineScope, async, delay and Flow are available without adding anything.
@Controller("/orders")
class OrderController(private val orders: OrderService) {
@Get("/{id}")
suspend fun find(@Param id: String): Order {
val order = orders.find(id) // suspends, the thread is free meanwhile
return order ?: throw NotFoundException("No order $id")
}
@Get("/{id}/summary")
suspend fun summary(@Param id: String): Summary = coroutineScope {
val order = async { orders.find(id) } // two calls in parallel, inside the request
val customer = async { customers.forOrder(id) }
Summary(order.await(), customer.await())
}
}How it runs. suspend code runs on the thread that handles the request, so when it suspends (a delay, an await, a Flow waiting for its next item) the thread serves other work and the coroutine resumes on the same thread. That is why the request context and open transactions keep working across suspension points.
Request context follows the coroutine. Values set by useRequestContext are visible after delay, after await, and after withContext(Dispatchers.IO) { ... }. They are copied to whatever thread runs the coroutine.
Transactions do not change threads. A @Transactional method may suspend, and the transaction stays open across the suspension. Do database work on the request's coroutine. A withContext(Dispatchers.IO) { repo.save(x) } inside a transaction runs on another thread, outside the transaction, and is committed on its own. Keep those calls out of the transaction, or call them before it starts.
Cancellation. When the client disconnects, the request's coroutine is cancelled. A handler waiting in delay, await or a Flow stops at once, and its finally blocks run. A tight loop that never suspends stops only if it checks ensureActive() or isActive. Requests on one connection are answered one after another, so a pipelining client never has two running at once.
Retries wait without blocking. @Retry on a suspend function waits with delay, so other coroutines keep running while it waits. See Resilience.
Streaming with Flow. A handler that returns a Flow<T> streams it as newline-delimited JSON (application/x-ndjson), one value per line, each sent as soon as it is produced. When the client stops reading, the next write fails and the flow is cancelled.
@Get("/prices") fun prices(): Flow<Price> = flow {
while (true) { emit(feed.next()); delay(1_000) }
}Background coroutines. To start work that is not tied to a request, use a scope that the application cancels when it stops:
@Injectable
class Background : CoroutineScope by CoroutineScope(SupervisorJob() + Dispatchers.Default), OnApplicationShutdown {
override fun onApplicationShutdown(signal: String?) = cancel()
}The HTTP client is blocking. HttpClientService calls block the request's thread, which is cheap on a virtual thread. A coroutine-native client that suspends while the response is in flight is not in this release. Use @Retry and @TimeLimit around its calls as usual.
Parallel work without coroutines works too: @Async methods that return a CompletableFuture, and CompletableFuture.supplyAsync run on virtual threads.
Several processes
Two ways to use more than one process, depending on the goal.
Several processes on one machine
For more throughput on one machine, the application can supervise copies of itself. Add --processes=N to the command line, or set KEST_PROCESSES:
java -jar build/libs/shop.jar --processes=4
KEST_PROCESSES=4 ./gradlew runThe process you started becomes a supervisor. It starts N copies of the same program with the same JVM options and class path, and each copy runs the application normally. The copies listen on the same port (Netty sets SO_REUSEPORT), and the operating system spreads connections between them. Then:
- A worker that exits is started again, after 1 s, then 2 s, then 4 s, up to 30 s between tries. A worker that fails ten times in a row, each within a minute of starting, is given up and the supervisor reports it.
- SIGTERM or Ctrl-C stops every worker, which shut down through their own shutdown hooks. The supervisor exits when they have all stopped.
- Each worker sees
KEST_WORKER_ID(0 to N-1) andKEST_WORKERS, throughio.kest.core.Cluster.
Every worker is a full instance: each runs its own schedules, queue consumers and event listeners, as separate servers would. Work that must run once for the whole machine needs a distributed lock or a repeatable queue job. The supervisor is not a substitute for a process manager in production: if the supervisor itself is killed with SIGKILL, the workers keep running. Use systemd, Docker or Kubernetes to run the supervisor, and to restart it.
Port sharing needs the Netty HTTP adapter. The JDK adapter cannot share a port, so a second worker would fail to start.
Several servers
For more capacity across machines, or for isolation, run more instances. Anything that must be shared between them has a Redis (or database) backed implementation, so instances behave as one:
- Sessions, cache, rate limits and queues in Redis.
- Repeatable jobs and the queue rate limit are claimed in the shared store, so two instances never run the same occurrence twice.
- Migrations take a database lock, so instances can start together.
- The
workertemplate (kest new jobs --template worker) starts the container without an HTTP server, for queue processors and schedules. Start as many as you need.
Parallel work inside a request
Use ordinary JVM tools; they all work with Kest's virtual threads:
@Async open fun sendReceipt(order: Order): CompletableFuture<Unit> = ... // open class, open method
val (a, b) = coroutineScope { awaitAll(async { users.find(id) }, async { orders.forUser(id) }) } // coroutines
val results = listOf(::one, ::two).map { f -> java.util.concurrent.CompletableFuture.supplyAsync(f) }.map { it.join() }Transactions are bound to the thread that opened them: work you start on another thread does not join the transaction. Inside a coroutine that suspends, the transaction stays with the coroutine, as described above.