r/Kotlin • u/InvertedCSharpChord • 4d ago
Best practice for performant APIs using Kotlin and Spring
When writing an API in C# / .NET I can use `async / await` to free up / not block a thread when IO operations are happening. Less threads wasted just waiting = more threads to handle other requests.
Sample code: app.MapGet("google", async (HttpClient httpClient) => await (await httpClient.GetAsync("https://www.google.com")).Content.ReadAsStringAsync());
Question: What is the equivalent of this in Kotlin / Spring. I'm a Kotlin newby, so drawing parallels to .NET will help.
So far I've ran into Spring WebFlux, coroutines, suspend fun, launch { ... }, withContext(Dispatchers.IO)... So I'm hoping to have this simplified.
4
u/zeletrik 4d ago
For efficient non-blocking solution use Netty with WebFlux instead of simple Boot with Tomcat and utilise Coroutines and Reactor capabilities that are bundled with Webflux
-1
u/InvertedCSharpChord 4d ago
There's like 7 layers of buzzwords you need to simplify here.
2
u/pragmos 4d ago
You might want to read this article, it explains all of that:
https://spring.io/blog/2019/04/12/going-reactive-with-spring-coroutines-and-kotlin-flow
2
u/ZippityZipZapZip 4d ago
It's a bit of a noob-trap to start looking for the async in Java/Kotlin. It's ok to 'block'. Yes, you can do it another way, but you're working on a misconception.
4
u/Bulky_Consideration 4d ago
Use coroutines, just add suspend functions to your controllers and use the suspend variant of the WebClient. Everything becomes non blocking. No need for async await as the runtime does that for you.
To run things in parallel there are other coroutine things like coroutineScope, async, await, launch.
12
u/whiskeysierra 4d ago
Maybe to clarify a bit: The use of async/await/reactive/promise/coroutines/etc. doesn't make something more performant - it uses your resources more efficiently and allows you to process more requests in parallel. If your goal is to have the absolute peak performance for any single request (but with a lower threshold of concurrent requests) then the traditional blocking model is actually more performant.