How to Implement Structured Concurrency
Use structured concurrency: tie child tasks to their scope, propagate cancellation and errors, and never leave a task running past its parent.
On this page
Introduction
Structured concurrency is the idea that a child async task should not outlive the scope that started it. Without it, a handler starts a background task, returns a response, and the task continues in a context whose request is gone, updating state that no longer exists or writing to a closed connection. The scope that started the work should be the scope that ends it, and a failure or a cancel should reach every child.
This tutorial implements structured concurrency with a task group: children bound to a scope, cancellation propagated to all on a failure, errors aggregated, and a guarantee that the scope does not return until the children are done. The examples mirror task-group behavior across runtimes, and the discipline applies wherever async tasks can be started.
Bind child tasks to their scope
A task group runs its children and does not return until all have finished, failed, or been cancelled. The parent awaits the group, so the lifetime of the children is nested inside the parent’s, and nothing continues after the parent returns. This is the structural property: the call tree of tasks matches the lexical structure of the code, so there is no hidden concurrency that outlives its creator.
Contrast with a fire-and-forget task that is started and forgotten: its lifetime is not nested, and it can run after the parent returned, in a context that may no longer be valid. A task group removes that class of bug by construction, because the parent cannot finish while a child is still running.
import asyncio
async def handle(request):
async with asyncio.TaskGroup() as tg:
a = tg.create_task(fetch_a(request))
b = tg.create_task(fetch_b(request))
# the group waits here until both finish (or one fails and cancels the other)
return combine(a.result(), b.result())
Propagate cancellation to all children
When the owner is cancelled, every child should be cancelled, or a cancelled request leaves its work running. The group ties the children to the owner’s cancellation, so when the owner’s signal fires, the group cancels the children and waits for them to stop. This is what makes a cancel complete rather than a promise that the outer work is still going.
When one child fails, the group cancels the others if the group is fail-fast, so a doomed fan-out stops instead of loading a downstream after the outcome is decided. For a collect-all group, the children continue and their errors are aggregated. Choose the policy per group, and make it explicit, because whether one failure stops the rest is a decision about the work.
package main
import (
"context"
"golang.org/x/sync/errgroup"
)
func handle(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx) // ctx cancels when a child returns an error
g.Go(func() error { return fetchA(ctx) })
g.Go(func() error { return fetchB(ctx) })
return g.Wait() // waits for all, cancels the rest on failure
}
Aggregate the failures
A group with several children can have several failures, and all of them matter. Fail-fast groups surface the first error and cancel the rest, but the cancellation errors are not the cause. Collect-all groups return every child’s error so the caller sees the full picture. Either way, do not lose an error: an error swallowed because another finished first is a debugging dead end.
Where the runtime supports it, return a combined error that includes each child’s failure, so the caller can log all of them. For a fail-fast group, return the triggering error and treat the cancellation of the others as expected. The point is that the caller learns why the group failed, not just that it did.
Guarantee the scope does not leak
The defining guarantee is that when the scope returns, no child is still running. This is what prevents a task from updating state after its context is gone or writing to a closed socket. If the runtime cannot guarantee it, add a final wait for the children before returning, and a timeout after which a stuck child is abandoned deliberately and logged.
For a long-lived background task that should outlive a request, do not use the request’s scope; give it its own owner with its own lifetime, so it is structured under that owner instead. Structured concurrency does not forbid background work; it requires that every task has an owner whose scope covers its lifetime, so the task’s end is defined by a scope, not by chance.
Test the scope boundary
Test that the group waits for all children, by asserting the group does not complete while a child is still running. Test that one child failing cancels the others and the group returns the failure, by a child that records whether it was cancelled. Test that when the owner is cancelled, the children are cancelled too. Test that no child touches shared state after the scope returns, by a child that writes after a delay and asserting the write did not happen.
python -c '
import asyncio
async def child():
try: await asyncio.sleep(10)
except asyncio.CancelledError: print("child cancelled"); raise
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(child())
# on exit the child is cancelled; assert the message printed and the loop is idle
asyncio.run(main())
'
Common pitfalls
Fire-and-forget tasks that outlive their scope, a Promise.all that does not cancel the rest on a failure, a cancelled owner whose children keep running, errors swallowed because another child failed first, and background work with no defined owner are the recurring mistakes. A task group with nested lifetimes, cancellation propagation, aggregated errors, and a defined owner for background work address them.
Conclusion
Structured concurrency keeps every child task inside a scope that ends it. Bind children to their scope, propagate cancellation to all on a cancel or the first failure, aggregate the errors, and guarantee no child runs after the scope returns. Self-check by asserting the scope waits for all children, cancels the rest on a failure, and leaves nothing running. Then a task cannot outlive its owner and update a world that is gone.
Sources: MDN: Aborting a group of async tasks, Python: asyncio TaskGroup, Go: errgroup and context.
FAQ
- What is structured concurrency?
- It is the discipline that child async tasks live within the scope that created them: the scope does not return until the children are done or cancelled, and a failure or cancellation propagates to them. It removes the leak where a child outlives its parent and runs in a context that no longer exists.
- How is this different from Promise.all?
- Promise.all waits for all the promises, but it does not cancel the others when one rejects, and it does not tie them to a scope. A task group waits and, on the first failure, cancels the rest, so no work continues after the group has decided the outcome.
Report a problem with this articleOpens a pre-filled issue on GitHub.