← Lessons

quiz vs the machine

Gold1420

Concurrency

Structured Concurrency

Tie task lifetimes to a lexical scope so nothing leaks.

5 min read · core · beat Gold to climb

Structured Concurrency

Structured concurrency says that the lifetime of a concurrent task should be bound to a lexical scope, just as a local variable is. When you open a scope and start child tasks inside it, the scope does not return until every child has finished, failed, or been cancelled. No task outlives the block that launched it.

This mirrors how structured programming replaced raw goto with blocks and loops. The benefit is that concurrency gains the same clean nesting. Errors propagate up like exceptions, and cancellation flows down to all children automatically.

Key guarantees:

  • No leaks A task cannot escape its scope and run forever in the background.
  • Error propagation If one child fails, siblings can be cancelled and the failure surfaces at the scope boundary.
  • Cancellation cascade Cancelling the scope cancels all descendants.

Contrast this with launching detached background tasks, where a thrown error vanishes and orphaned work keeps consuming resources. Structured concurrency makes the happens before relationship explicit: the parent waits, so its results are visible after the scope closes. Languages and libraries such as Kotlin coroutines, Java structured task scope, and Trio for Python all build on this principle.

Key idea

Structured concurrency binds task lifetimes to a scope so children cannot leak, and errors and cancellation propagate cleanly across them.

Check yourself

Answer to earn rating on the learn ladder.

1. What is the central guarantee of structured concurrency?

2. How does cancellation behave in structured concurrency?