Kotlin › Practice

Choosing Kotlin Coroutines or Virtual Threads in Spring Boot

Compare Kotlin Coroutines and Java 21 Virtual Threads in Spring Boot 3.4, covering blocking JDBC, pinning, MDC propagation, and combining both.

Choosing Kotlin Coroutines or Virtual Threads in Spring Boot

While speeding up a club schedule dashboard API, I had to decide between Kotlin Coroutines and Java 21 Virtual Threads. This post breaks down how each yields threads, where blocking JDBC and MDC trip you up in Spring MVC, and why I ended up combining both.

Tested with Spring Boot 3.4.1, Java 21, Kotlin 2.1.0, and kotlinx.coroutines 1.9.0. Spring Boot 3.4 manages kotlinx.coroutines 1.8.1 by default, so I overrode it with extra["kotlin-coroutines.version"] = "1.9.0".

Background

The dashboard endpoint in our club schedule service fetched data from three places one after another: the member profile via JPA, recent notices from an external bulletin board API, and upcoming events from a Google Calendar sync server. Each call took 100 to 300 ms, so total response time regularly crossed 600 ms. When event registration opened and traffic spiked, the Tomcat thread pool filled up with threads sitting idle on I/O.

Two fixes stood out right away. I could set spring.threads.virtual.enabled=true so Tomcat runs requests on Virtual Threads and stops paying for blocked OS threads. Or I could fan out the three calls in parallel using Coroutines’ async. At first I treated this as an either-or choice. Once I looked at what each mechanism actually solves under the hood, combining them made much more sense.

How they work under the hood

Kotlin Coroutines operate at the compiler and library level. The Kotlin compiler rewrites every suspend function to accept a trailing Continuation parameter and compiles the body into a state machine with a label for each suspension point. When a suspending call like delay() or await() returns COROUTINE_SUSPENDED, the coroutine releases its carrier thread and keeps local variables in the heap-allocated Continuation object. That means a coroutine only yields at suspend points. If it hits a regular blocking call such as JDBC, it holds onto the underlying thread until the database responds.

Virtual Threads operate inside the JVM runtime. When code reaches a JDK blocking point—socket I/O, LockSupport.park(), or a blocking queue—the JVM copies the virtual thread’s stack frames to the heap and unmounts it from the OS carrier thread. Your existing blocking code runs unchanged without adding suspend anywhere. For a closer look at carrier scheduling and pinning diagnostics, see my earlier post on Java 21 Virtual Threads scheduling and pinning.

Put simply, Virtual Threads make waiting threads cheap, while Coroutines give you structured concurrency to start, cancel, and fail a group of tasks together. Java 21 ships StructuredTaskScope as a preview API, which I didn’t want to depend on in this service. Using Coroutines’ coroutineScope gave me stable structured concurrency for parallel calls today.

Comparison and decision guide

CriteriaCoroutinesVirtual ThreadsCombined (Coroutines + VT Dispatcher)
Execution layerCompiler and libraryJVM runtimeBoth
Blocking JDBC callsHolds thread (needs Dispatchers.IO)Automatic unmountRuns on VT for automatic unmount
Parallel fan-out and cancellationStructured via async and coroutineScopeManual Executor and Future handlingHandled by Coroutines
Code changes requiredsuspend propagates up the call stackSingle property togglesuspend only around parallel sections
ThreadLocal and MDCNeeds explicit context elementsPreserved per threadNeeds explicit context elements
flowchart TD
    A["Choose request concurrency model"] --> B{"Parallel calls per request?"}
    B -->|"No"| C["Enable Virtual Threads only"]
    B -->|"Yes"| D{"Using WebFlux and R2DBC?"}
    D -->|"Yes"| E["Use Coroutines alone"]
    D -->|"No"| F["Combine Coroutines with VT Dispatcher"]

Knowing when not to use them matters just as much. If an endpoint is straightforward CRUD with no parallel fan-out, introducing Coroutines just spreads suspend across controllers, services, and repositories for no real gain—enabling Virtual Threads alone is simpler and cleaner. Neither model speeds up CPU-bound work like image resizing, where adding more concurrent tasks only adds context-switching overhead; keep CPU work on Dispatchers.Default or a fixed pool sized to your core count. Finally, if a downstream API enforces strict per-second rate limits, letting Virtual Threads open thousands of simultaneous requests will trigger 429 errors or trip circuit breakers, so cap concurrency explicitly with a Semaphore.

Combining both in Spring MVC

When kotlinx-coroutines-reactor is on the classpath, Spring MVC adapts suspend controller methods into a Reactor Mono and executes them through Servlet async support. Inside the parallel fan-out, I dispatch each blocking call onto a Virtual Thread-backed CoroutineDispatcher. That avoids hitting Dispatchers.IO’s default parallelism cap (max(64, CPU cores)) when many requests wait on slow JDBC or HTTP calls at once.

1
2
3
4
5
6
7
8
9
10
// build.gradle.kts (excerpt)
extra["kotlin-coroutines.version"] = "1.9.0"

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-data-jpa")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-slf4j")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// src/main/kotlin/com/example/club/dashboard/DashboardService.kt
package com.example.club.dashboard

import java.util.concurrent.Executors
import kotlinx.coroutines.ExecutorCoroutineDispatcher
import kotlinx.coroutines.async
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.slf4j.MDCContext
import kotlinx.coroutines.withContext
import kotlinx.coroutines.withTimeout
import org.springframework.beans.factory.DisposableBean
import org.springframework.stereotype.Service
import org.springframework.web.client.RestClient
import org.springframework.web.client.body

data class Dashboard(val profile: MemberProfile, val notices: List<String>, val schedules: List<String>)

@Service
class DashboardService(
    private val memberQueryService: MemberQueryService,
    restClientBuilder: RestClient.Builder,
) : DisposableBean {
    private val restClient = restClientBuilder.baseUrl("https://club-api.example.com").build()
    private val vtDispatcher: ExecutorCoroutineDispatcher =
        Executors.newVirtualThreadPerTaskExecutor().asCoroutineDispatcher()

    suspend fun load(memberId: Long): Dashboard = withTimeout(2_000) {
        withContext(MDCContext()) {
            val profile = async(vtDispatcher) { memberQueryService.findProfile(memberId) }
            val notices = async(vtDispatcher) { fetchList("/notices") }
            val schedules = async(vtDispatcher) { fetchList("/members/$memberId/schedules") }
            Dashboard(profile.await(), notices.await(), schedules.await())
        }
    }

    private fun fetchList(uri: String): List<String> =
        restClient.get().uri(uri).retrieve().body<List<String>>().orEmpty()

    override fun destroy() = vtDispatcher.close()
}
1
2
3
4
5
6
7
8
9
10
11
12
// src/main/kotlin/com/example/club/dashboard/DashboardController.kt
package com.example.club.dashboard

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RestController

@RestController
class DashboardController(private val dashboardService: DashboardService) {
    @GetMapping("/api/members/{memberId}/dashboard")
    suspend fun dashboard(@PathVariable memberId: Long): Dashboard = dashboardService.load(memberId)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/main/kotlin/com/example/club/dashboard/MemberQueryService.kt
package com.example.club.dashboard

import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

data class MemberProfile(val id: Long, val name: String)

@Service
class MemberQueryService(private val memberRepository: MemberRepository) {
    @Transactional(readOnly = true)
    fun findProfile(memberId: Long): MemberProfile {
        val member = memberRepository.findById(memberId).orElseThrow()
        return MemberProfile(requireNotNull(member.id), member.name)
    }
}

Notice that MemberQueryService.findProfile() stays a plain blocking method rather than becoming suspend. All three async calls run as children of the withContext scope, so if any call throws an exception or the total runtime crosses the 2-second timeout, the sibling tasks cancel right away instead of leaking work in the background. Implementing DisposableBean also ensures vtDispatcher.close() shuts down the executor cleanly when the Spring context stops. After deploying this setup, dashboard response times dropped from over 600 ms down to the 300 ms range, matching the slowest single downstream call.

Production pitfalls and checklist

Warning: JPA transactions and EntityManager instances bind to ThreadLocal. Annotating a suspend function with @Transactional and switching dispatchers inside it breaks transaction boundaries. Keep the entire transaction inside a regular blocking function and call that function as a unit from your dispatcher. SLF4J MDC is also ThreadLocal, so switching dispatchers without MDCContext() drops request IDs from logs; pass any custom ThreadLocal values using ThreadLocal.asContextElement(). Finally, on Java 21, blocking I/O inside a synchronized block pins the carrier thread, so test older JDBC drivers and connection pools with -Djdk.tracePinnedThreads=full before rolling out.

On the Kotlin side, calling a suspend function such as delay() inside a synchronized block fails to compile, so your own coroutine code rarely triggers carrier pinning. In practice, pinning almost always hides inside third-party Java libraries that your coroutines invoke.

  • Did you check whether spring.threads.virtual.enabled=true alone is enough for endpoints without parallel calls?
  • Are parallel tasks grouped inside coroutineScope or withContext with async so failures and timeouts cancel sibling work?
  • Do blocking JDBC and HTTP calls run on a Virtual Thread dispatcher or Dispatchers.IO instead of Dispatchers.Default?
  • Does @Transactional live on a plain blocking method, with all dispatcher switches kept outside the transaction boundary?
  • Did you verify that MDCContext() preserves request IDs in logs and that -Djdk.tracePinnedThreads=full shows no pinning events?
This post is licensed under CC BY 4.0 by the author.