https://kotlinlang.org logo
#ktor
Title
# ktor
j

Justin Moy

12/22/2020, 8:19 PM
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

Nikky

12/22/2020, 8:27 PM
schedule/launch the next tasks in GlobalScope or similar , maybe wrap them in a timeout or so, then return 200
j

Justin Moy

12/22/2020, 8:32 PM
launching them in the globalscope will ensure they won’t get canceled when the server returns a response?
n

Nikky

12/22/2020, 8:37 PM
yes
its the easiest and most straightforward way to start a task outside of structured concurrency
j

Justin Moy

12/22/2020, 8:40 PM
cool, i’ll give it a shot, thanks
j

Jorge R

12/22/2020, 10:39 PM
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

Justin Moy

12/22/2020, 10:40 PM
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

Jorge R

12/22/2020, 11:48 PM
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
3 Views