Search code examples
kotlinkotlinx.coroutines

"Fire and forget" with structured concurrency and coroutines


I have a little endpoint that looks like this

val numbers = it.bodyAsString.parseJsonList<Numbers>()
processedNumbers = numberService.process(numbers)
GlobalScope.launch {
    sqsService.sendToSqs(processedNumbers)
}
it.response.setStatusCode(204).end()

The reason why I use GlobalScope is because the producer does only need the acknowledge after the numbers have been processed so I am trying to do a fire and forget in a parallel track to be able to immediately respond to the producer

What would be the “best practice” way of doing this with structured currency? Should I create my own scope (like fireAndForgetScope instead of GlobalScope)?


Solution

  • As you already guessed, creating your own scope would be a good solution in this case.
    You can define it as member of your controller:

    private val bgScope = CoroutineScope(newFixedThreadPoolContext(4, "background-tasks"))
    

    Then usage is very similar to what you're doing:

    val numbers = it.bodyAsString.parseJsonList<Numbers>()
    processedNumbers = numberService.process(numbers)
    bgScope.launch {
        sqsService.sendToSqs(processedNumbers)
    }
    it.response.setStatusCode(204).end()