Hello everyone, In order not to put a big descript...
# ktor
a
Hello everyone, In order not to put a big description here I am sending the discussion link to github so that people can get benefit there as well. https://github.com/ktorio/ktor/discussions/4790 My Questions for kotlin/ktor with netty: 1) Is this understanding correct — that even suspending functions (e.g., API or DB calls) should be moved to Dispatchers.IO to avoid tying up Netty threads? 2) Are there any cases where it’s safe to run I/O-bound suspend functions on the default Netty coroutine dispatcher? 3) What is the best practice for Ktor + Netty when dealing with request processing that includes external API or MongoDB calls? Appreciate any confirmation, corrections, or pointers to official Netty/Ktor docs or discussions (e.g., Slack, Discord, GitHub issues) that support this!
c
as with any blocking operations they should be moved elsewhere, ideally to a dedicated thread pool. The “best practice” is generally to avoid blocking calls to the extent possible - use async/suspending HTTP clients, for example, for outbound API calls, R2DBC for RDBMS connectivity, async/suspend versions of SDKs (e.g. AWS, Mongo), etc
that even suspending functions (e.g., API or DB calls) should be moved to Dispatchers.IO to avoid tying up Netty threads?
if these are already fully suspending they don’t need to be moved.
a
Thank you! Out of curiosity, Does using Dispatchers.IO brings any advantage over default coroutine context created by ktor route in the case that if all functions are already fully suspending
c
No. If everything is already fully suspending you will incur the overhead of a context switch to a different thread.
❤️ 1
a
Thank you so much!
👍 1
One more question I already know that all of the calls are suspended and non-blocking. But, in my case there are too many chain of api and db calls so it will take considerable amount time for request to complete (it is a async endpoint, communicates back via webhook). In that case, does it still make sense to stick to default coroutine?
c
It isn’t about the time that a request takes; when it hits a suspend point the coroutine is suspended, freeing up the thread to process other coroutines.
a
So after execution hits the suspended function call, the netty thread will be free from that point of execution and will be available to take new incoming requests. Please correct me If I misunderstood
a
After the current coroutine is suspended, the netty event executor should be able to start new coroutines or resume the execution of others on that thread.
Ktor defines the
NettyDispatcher
class implementing
CoroutineDispatcher
, which acts as a bridge between Netty's
EventExecutor
and the coroutines library.