Fixing nested runBlockings in Spring Boot

The short question is: do I really need to mark the entire call stack as “suspend”?

The longer question and context:

I have a Spring Boot application in Kotlin, and I have a number of concurrent tasks around various external HTTP endpoints and database requests.

In my original implementation, I had zero suspend functions, and used runBlocking whenever I needed concurrency. However, as things evolved, I ended up with cases where one runBlocking was calling a function which also contained runBlocking, and the thread ended up parked. I’m trying to work my way out of that.

My current path is to replace every existing runBlocking with coroutineScope, and then mark the functions as suspend, all the way up the call stack to the Controller. The controller then has a runBlocking block in every relevant endpoint.

Is there a less invasive way to do that, or is that the correct model?

I’m afraid this is the way to go. Generally, asynchronous code always propagate to the caller. And asynchronous application servers work best if your code is asynchronous from the top to the bottom.

And by saying “top to bottom” I mean that you shouldn’t use runBlocking() even at the top level. In order to let the application server use threads in the most optimal way, you should not block its threads. I didn’t try it myself, but use WebFlux and implement your endpoints as suspend functions.

Spring fits well with coroutines, so it is possible to avoid rinBlocking at all.

Mixing synchronous and asynchronous code is a workaround, not a best practice.

Thank you.

Ok, so we’ve been using Spring Boot, so we have some current limitations. However, it looks like we can probably migrate to Spring Webflux which will allow us to use suspend functions directly in our Controller. Until then, I will constrain the runBlockings to the highest level they can go (i.e., handlers for the various rest methods in the controller).

I have further questions, but I’m going to break it off to a different thread, since they’re somewhat out of scope of this topic.