i’m trying to do some async processing in the scop...
# ktor
j
i’m trying to do some async processing in the scope of a ktor web request, our server is expecting to receive a payload and upon receiving the payload, the server is supposed to return a http 200 immediately and then do some processing on the payload (which will involve making some API calls), any ideas on how to best do this in a ktor app?
n
schedule/launch the next tasks in GlobalScope or similar , maybe wrap them in a timeout or so, then return 200
j
launching them in the globalscope will ensure they won’t get canceled when the server returns a response?
n
yes
its the easiest and most straightforward way to start a task outside of structured concurrency
j
cool, i’ll give it a shot, thanks
j
Did you consider using multipart to receive and process the payload? In any case, check the example as they reflect here how to do async ops to copy to a file. This may be in the scope of the request, so maybe what @Nikky says will seal the deal. But remember that GlobalScope is discouraged. https://ktor.io/docs/multipart-support.html#receiving-files-using-multipart
j
this is for a webhook integration with a third party service and the third party recommends returning a 200 response as fast as possible, so i don’t have control over the request body
j
Yeah, I was expecting something similar. So then you need to go out of request scope. https://api.ktor.io/1.1.4/io.ktor.application/-application/index.html Application has a coroutine scope. Maybe you can inject some BackgroundOperationProvider where you want to process your payload, and this provider can get application scope injected inside, so you can launch inside this scope. Just a quick idea...
👍 1
It is written there "application coroutine scope that is cancelled immediately at application stop so useful for launching background coroutines". Seems matching what you want
👍 1