You are currently viewing Is this a scenario where I would benefit from coroutines?

Is this a scenario where I would benefit from coroutines?

So at my job we primarily use Java/SpringBoot, but in some cases have started using Kotlin/SpringBoot. I have done a lot with Kotlin in side projects and I’m quite fond of it, however I have done almost nothing with coroutines. With this current project in front of me, I think they might be beneficial, but I’m may be misunderstanding things.

The project in question is a validation service. Other services are going to consume a particular type of data, and we need to have a re-usable micro-service that can validate that the content of the data payload is accurate. The Validation Service (as I will be calling it) exposes an API that receives the data payload, and then it performs a series of IO-heavy operations to validate it. Those IO operations are a combination of calls to other APIs and lookups in SQL databases. If everything is valid, it returns a success responses, otherwise returns an error.

I am going to use SpringBoot for this. Out of all the reasons I could give, the biggest is probably that my company has a lot of pre-built SpringBoot libraries for integrating with enterprise things like our network security, and not leveraging that would make my life hell. So please don’t suggest alternatives to SpringBoot, I’m far from a Spring fanatic but the costs of going any other direction are just too high in this case.

Spring automatically has its thread pool and each request coming into the API will get its own thread. However, each request then does all of those IO-heavy lookups for the validation, which will contribute most of the cost to the overall execution time of the API operation. While this doesn’t need to be an exceptionally fast service, it probably can’t take more than a few seconds to complete its work.

This is what got me thinking about coroutines. While I could certainly leverage the existing built-in thread pool to parallel the lookups in the request, I feel coroutines might be a better option.

I’ve always understood coroutines as being a Java version of the JavaScript event loop. Rather than blocking a thread, the coroutine code is split up into the equivalent of JavaScript event functions and executed on a shared thread pool. Any time that the code has to wait (I believe “suspend” is the Kotlin term), it is just moved to the back of the line, so to speak, so the shared pool can keep being used.

I’m wondering if the scenario I described is a good use for this. The only concern that I have is that with a high volume of requests, the coroutine thread pool could become a bottleneck.

Anyway, feedback is appreciated.

submitted by /u/Droid2Win
[link] [comments]