Are all requests coming to an ktor application han...
# ktor
h
Are all requests coming to an ktor application handled on the same Application's coroutine? Since when I print out the CoroutineContext when a request hit an endpoint I get the same context. Thanks in advance
s
The
Application
doesn't run inside a coroutine, but is a
CoroutineScope
that has a
SupervisorJob
. This
Job
has an optional parent which can be supplied through
embeddedServer
, but if using
EngineMain
it's always
null
. The
Routing
plugin has another
CoroutineScope
which is a child of the
Application
scope. Most engines don't run in a coroutine (except CIO), but they create a new coroutine for every request that is being handled. So every coroutine that is created to handle a request is a grandchild of the
Application
scope, and a child of the
Routing
scope. Depending on how you print the
CoroutineContext
you will indeed always see the same thing. For Netty: https://github.com/ktorio/ktor/blob/828e6978166adf2ed73a01702d57958372d3dc4b/ktor-[…]er-netty/jvm/src/io/ktor/server/netty/NettyApplicationEngine.kt
e
fyi @Viktoriya Nikolova
h
Thanks for the info, @simon.vergauwen. I think it would be beneficial if the fact that "a new coroutine is created for every request that is being handled" is stated in the official docs, for situation like a singleton object which being shared between different request-handler functions, can cause the code to be racy since likely that it's being shared between different threads. What do you think
1
s
Yes, absolutely. We're working on a tutorial explaining in detail how coroutines work in Ktor, this will be released soon-ish during the summer. I am giving a lighting talk @ KotlinConf on this topic as well, you can catch it on the livestream or afterwards. Later in the year I hope to give a longer talk on this topic as well, or perhaps in a webinar.
kodee loving 2
h
Nice! Anw I might as well just open a pr to add that line to the doc later (assuming that no one is already on it yet). Thanks again, Simon
kodee loving 1