Structured Concurrency and Cancellation

Topics Covered

The Case for Structure

The go statement problem

Nurseries and scopes

What structure guarantees

Structure across languages

Errors from many tasks at once

Escape hatches, made explicit

Structure and testing

Structure and readability

Most concurrency bugs in production are not exotic races but lifecycle mistakes: work that keeps running after nobody needs it, errors that vanish in background tasks, and shutdowns that hang. Structured concurrency is a discipline, now built into Python, Kotlin, Swift, Java and Trio, that eliminates this class of bug by tying the lifetime of every concurrent task to a lexical scope. This section explains the problem it solves and the core idea.

The go statement problem

In 2018, Nathaniel Smith, author of the Trio library, published an essay arguing that unrestricted task spawning, the go statement in Go or create_task in asyncio or new Thread start in Java, is to concurrency what goto was to sequential control flow. A function that calls another normally gets control back when the callee finishes, so the call is a black box: whatever happens inside is over by the time it returns. A function that spawns a task breaks this property. The task can outlive the function, keep using resources the function thought it had released, and raise errors that nobody is positioned to catch. Reading the function no longer tells you what it does, since its effects continue after it returns. Just as structured programming replaced goto with blocks, loops and calls that have a single entry and exit, structured concurrency replaces free spawning with constructs that guarantee every task finishes before its parent scope exits.

A free spawn lets work outlive the function that started it, so the caller cannot know when it is really done.

Nurseries and scopes

The structured alternative is a scope object, called a nursery in Trio, a task group in Python and Swift, a coroutine scope in Kotlin and a StructuredTaskScope in Java. Tasks can be started only inside such a scope, and the scope does not exit until all of its tasks have finished. If the function that opened the scope returns, every task it started is already done. If any task fails, the scope cancels its siblings, waits for them, and propagates the failure to the code that opened the scope, where it can be handled like any other exception. Scopes nest, forming a tree that mirrors the call stack: a request handler opens a scope for its subtasks, each of which may open scopes of their own. Cancelling a scope cancels its entire subtree. Background work that must outlive one request is still possible, but only by explicitly passing a longer lived scope, such as one owned by the application, which makes the extended lifetime visible in the code.

Every task belongs to a scope, and scopes nest. Cancelling a scope cancels the whole subtree below it.

What structure guarantees

Structured concurrency provides three guarantees that are hard to obtain otherwise. First, no leaks: when a scope exits, all its tasks are finished, so resources opened in the scope can be safely closed afterwards, and a test that returns has no lingering background work. Second, no lost errors: an exception in any task propagates to the scope owner, and if several tasks fail, the runtime combines their errors, as Python does with ExceptionGroup, rather than dropping all but one. Third, reliable cancellation: cancelling a scope reaches every task in it, transitively, so stopping a request or shutting down a server stops all of its work rather than only the top level task. These guarantees compose: a library function that uses a scope internally looks, from outside, exactly like a sequential function call that either returns a result or raises.

Structure across languages

The idea spread quickly after the Trio essay. Kotlin coroutines adopted structured concurrency before their 1.0 release, making every coroutine a child of a scope. Swift async let and task groups, introduced in 2021, are structured by design, with detached tasks as the explicit escape hatch. Python added asyncio.TaskGroup in 3.11, directly inspired by Trio nurseries, with AnyIO providing the same model on both asyncio and Trio. Java added StructuredTaskScope as a preview alongside virtual threads. Go has no built in construct, but errgroup with a shared context provides most of the benefits, and the community convention is that a function that starts goroutines should wait for them before returning. C++ is exploring structured concurrency through the senders and receivers model accepted for C++26. The convergence suggests that structure is becoming the expected default for concurrent code.

Errors from many tasks at once

Concurrency raises a question sequential code never faces: what should happen when several things fail at the same time. If three subtasks of a request all raise, reporting only the first hides the others, which may be the real cause; reporting none, as unscoped spawning often does, is worse. Structured scopes collect every failure. Python wraps them in an ExceptionGroup, which except star clauses can split by type, so a handler can deal with network errors and let programming errors propagate. Trio did the same with MultiError before ExceptionGroup was standardized. Kotlin keeps the first exception and attaches the others as suppressed exceptions, and Java StructuredTaskScope policies decide whether the first failure or all of them matter. Whatever the representation, the principle is that the scope owner sees every failure from its children, so debugging a concurrent failure starts from complete information rather than one lucky stack trace.

Escape hatches, made explicit

Structured concurrency does not forbid long lived background work; it requires that its owner be visible. A web application that warms a cache every minute, flushes metrics or consumes a queue needs tasks that outlive any single request. The structured way is to open a scope at application startup, for example in the lifespan handler of FastAPI or the main function of a Go service, and pass that scope, or a handle to it, to the components that need to start background tasks. The tasks then belong to the application, are cancelled when it shuts down and report their errors to it. Swift calls its escape hatch Task.detached, Kotlin has GlobalScope, which its documentation discourages, and Python allows create_task outside any group. Code review can treat each use of such an escape hatch as something to justify, much as unsafe blocks are treated in Rust.

Structure and testing

Structured concurrency pays off immediately in tests. When every task belongs to a scope that the code under test opens and closes, a test that calls the function and gets a result knows that all the work is finished, so assertions about database rows, files or messages are not racing against background tasks still running. Flaky tests caused by stray tasks, in which a test passes alone but fails when run after another test whose leftover task interferes, largely disappear. Leak checks become simple: count tasks or goroutines before and after each test and fail if the number grew, which tools such as goleak for Go and pytest plugins for asyncio automate.

Structure and readability

Structure also makes concurrent code easier to read. When tasks can only be started inside a visible block, a reader can see where concurrency begins and ends, which tasks run together and where their results are collected, all within one function. Reviewing such code resembles reviewing ordinary sequential code with a few clearly marked parallel regions, rather than chasing references to tasks across modules to discover who waits for what and who handles their errors.

It also lets tools help: linters can flag unscoped spawns, and debuggers can show the task tree as a tree, mirroring the scopes in the source code.

Make every task belong to a scope

Unscoped spawning lets work outlive its caller, leak resources and lose errors. Start tasks only inside a nursery, task group or scope that waits for them, cancels siblings on failure and propagates errors to its owner. Background work that must outlive a request belongs to an explicitly passed, longer lived scope owned by the application.