ktor server question regarding coroutines - When ...
# ktor
c
ktor server question regarding coroutines - When creating a simple HTTP API for retrieving an object, should suspend functions and await be used when interacting with the database? My understanding is that ktor routing creates a PipelineContext for each call with its own coroutine scope. Is that sufficient to protect the server from thread exhaustion from a sudden influx of requests? Or do I also need to use suspend and await when interacting with "slow" resources in order for any of the PipelineContext coroutine scopes to actually suspend?
c
Using coroutines, you almost never use
await
.
suspend
functions only return their results when they're done. I'm not exactly sure what you're asking for. The big question is whether your database driver supports coroutines or if it's blocking.
c
Ok after some more reading, I think the typical execution of an API request on a ktor server looks like this - • ktor server creates a coroutine to handle the call • repository layer calls a suspend func to retrieve db objects • the coroutine is suspended (freeing server threads to do other work) • the coroutine is resumed when the suspend func completes However, when using a database driver that is blocking, the thread bottleneck is moved to the threadpool for I/O. Some drivers like R2DBC are non-blocking and follow a reactive pattern to solve this. However, I'm not as concerned about the database connection pool being exhausted. As long as the server can keep accepting new requests and suspending their respective coroutines until the db eventually works its way through them all.