Skip to content

Lesson 3 of 9 · 27m

Structured Concurrency and Cancellation in Real Services

Use scopes, supervisors, timeouts, and cooperative cancellation so background work finishes, fails, or stops predictably.

The worst production coroutine bug I reviewed did not crash. It quietly kept thousands of inventory-sync jobs alive after their HTTP requests timed out, because every job captured a scope that never ended. Memory grew, downstream calls multiplied, and the service looked healthy until it wasn't. Structured concurrency exists to stop work from outliving the reason it was started.

Scope is lifetime

A coroutine scope defines who owns the work. Inside request handling, use coroutineScope when child work is part of the response:

suspend fun buildOrderView(id: OrderId): OrderView = coroutineScope {
    val order = async { orders.load(id) }
    val shipments = async { shipmentClient.forOrder(id) }
    OrderView(order.await(), shipments.await())
}

If shipments throws, the scope cancels the other children and propagates failure. You get a bounded lifetime instead of orphaned tasks.

Do not use request scope for fire-and-forget work

If the user should receive a response while work continues, launch into an application-owned scope with explicit limits:

class ImportService(
    private val scope: CoroutineScope,
) {
    fun enqueue(importId: ImportId) {
        scope.launch(CoroutineName("import-$importId")) {
            process(importId)
        }
    }
}

That scope needs supervision, metrics, shutdown handling, and usually a durable queue. "Launch it in the background" is not an architecture. If the process restarts, whatever was only in memory is gone.

Cancellation is cooperative

Coroutine cancellation does not violently kill running code. It throws CancellationException at suspension points. Code that never suspends, or catches every exception, may never stop:

suspend fun sync(records: List<Record>) {
    for (record in records) {
        ensureActive()
        blockingClient.send(record)
    }
}

Do not swallow CancellationException. Catch it only to clean up, then rethrow.

Field notes

  • GlobalScope is almost always the wrong scope on a server; it has no application lifecycle or ownership.
  • Always shut down application scopes during graceful stop; in-flight work should finish or cancel within a deadline.
  • Coroutine names are cheap and invaluable in thread dumps and logs.

Was this lesson helpful?

Sign in to rate