Kotlin Coroutines + Spring MVC

I have been using Kotlin with Spring MVC (and Spring Boot) for 6 months or so, and now I have been looking into making non-blocking REST API based on Spring MVC and Kotlin Coroutines. I am well aware that Spring is synchronous by default (1 request per thread and other mechanisms), and I am aware that WebFlux has support for using concepts from Kotlin coroutines and it works really good. However, what if, for one reason or another, I had to use Spring MVC (job requirement let’s say). How would I go about integrating Spring MVC (Spring Boot) with Kotlin coroutines in the most effective way?
I could use some help here, since all of resources I’ve found are with regards to WebFlux rather than Spring MVC.
Thank you in advance.

Have a look at spring-webmvc-kotlin-coroutine module, maybe this would help

I did, but it didn’t and it’s really old.

I’m not sure whether using coroutines with a synchronous framework (Spring MVC) is worth it. In the end coroutines are just a means to use threads efficiently while the processing waits for something like a remote system (e. g. a database server). But if you would use coroutines with a synchronous framework you would need to block a native thread per request anyway. So, I would say async programming is an all-or-nothing approach and you wouldn’t gain much with coroutines in this case…

1 Like

Thank you, yes, I got to that conclusion mostly myself. Just, for an example, what if I have communication with external service (let’s say remote API), and I am contacting it, getting results, etc, and for whole that time, my thread is frozen just waiting for request to remote server to finish. Would there be any benefit at all using coroutines there or not? That’s kind of specific problem I am having.

If you need to wait for the result, then, no, there wouldn’t be any benefit of using coroutines. But if you can implement it in a “fire and forget” manner, then you could decouple the actual processing from the request handling in the web framework. But the user wouldn’t receive a http response with the (business) result then. This limitation could possibly by mitigated by using some other kind of response channel, like web sockets or message queues. However, depending on the actual circumstances it could be cheaper to just pay for more hardware.

1 Like

Thank you so much, you clarified some things and verified others for me.
Wish you good luck! :slight_smile: