Sub topic 7
Structured concurrency: tasks that cannot outlive their scope
What this chapter assumes
You should be comfortable with async/await, asyncio.run, and asyncio.create_task. You should also know that Task.cancel() raises CancelledError inside a task at its next await. The earlier chapters on gather and cancellation cover these.
This chapter explains the design idea behind asyncio.TaskGroup and asyncio.timeout. The next chapter covers TaskGroup itself in detail.
The problem: tasks that outlive their caller
create_task starts work and returns immediately. Nothing ties the new task to the function that created it. The function can return, raise, or be cancelled while the task keeps running. The task is then an orphan: no code is responsible for waiting for it, handling its exception, or cleaning up after it.
import asyncio
async def log_event(name):
await asyncio.sleep(0.2)
print(f"logged {name}")
async def handle_request(name):
asyncio.create_task(log_event(name))
return f"handled {name}"
async def main():
print(await handle_request("a"))
print("main finished")
asyncio.run(main())The output is handled a and main finished. The line logged a never appears, because asyncio.run cancels leftover tasks when main returns. Even if the program kept running, handle_request has already reported success while its logging work was still pending. If log_event raised an error, nobody would see it until the task object was garbage collected, and then only as a warning on stderr.
Three things go wrong with orphans:
- Lost errors. An exception in a task nobody awaits is not raised anywhere useful.
- Leaked resources. Connections or files held by the task stay open for an unpredictable time.
- Unclear completion. A function's return no longer means its work is done, so callers cannot reason about what is still running.
The same problem with gather
asyncio.gather waits for several awaitables, so it looks structured. It is only partly so. When one awaitable raises, gather propagates that exception to the caller but does not cancel the others.
import asyncio
async def worker(name, delay, fail=False):
await asyncio.sleep(delay)
if fail:
raise RuntimeError(f"{name} failed")
print(f"{name} finished")
async def main():
try:
await asyncio.gather(
worker("a", 0.1, fail=True),
worker("b", 0.3),
)
except RuntimeError as exc:
print("gather raised:", exc)
print("main continues")
await asyncio.sleep(0.5)
print("done")
asyncio.run(main())The output order is gather raised: a failed, main continues, b finished, done. The await gather(...) call has already failed, yet b is still running in the background. It finishes while main is doing something unrelated. If b held a database transaction, that transaction would stay open after the error handler ran.
The structured rule
Structured concurrency borrows an idea from structured programming. In a normal function, control enters at the top and leaves at the bottom, and every block finishes before its parent does. Concurrent code can follow the same rule:
- Tasks are started inside a scope, such as an
async withblock. - The scope does not exit until every task started in it has finished.
- If one task fails, the scope cancels the other tasks and waits for their cleanup to complete.
- When the scope exits, its errors are raised to the code that opened it.
The lifetime of a task is then bounded by the lexical block that created it. You can read the code and know that nothing started in the block is still running after it.
| Property | Unstructured (`create_task`, `gather`) | Structured (`TaskGroup`) |
|---|---|---|
| Who waits for the task | Whoever remembers to | The scope, automatically |
| Sibling tasks when one fails | Keep running | Cancelled |
| Errors from tasks | Easy to lose | Collected and raised at scope exit |
| Function returns while work is pending | Possible | Not possible |
| Cost | None | Must fit work into a block |
Seeing it work
Here is the same pair of workers inside a TaskGroup. This is a preview. The next chapter explains the API and the except* syntax.
import asyncio
async def worker(name, delay, fail=False):
try:
await asyncio.sleep(delay)
if fail:
raise RuntimeError(f"{name} failed")
print(f"{name} finished")
except asyncio.CancelledError:
print(f"{name}: cancelled, cleaning up")
raise
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(worker("a", 0.1, fail=True))
tg.create_task(worker("b", 0.3))
except* RuntimeError as eg:
print("group failed:", [str(e) for e in eg.exceptions])
print("main continues")
asyncio.run(main())The output is:
b: cancelled, cleaning up
group failed: ['a failed']
main continuesWhen a fails, the group cancels b and waits for b to finish its cleanup. Only then does the async with block raise. By the time main continues prints, no task from the group is alive.
How the scope guarantees this
The key step is the wait that follows cancellation. Cancelling a task only requests that it stop. The scope keeps waiting until each task has actually ended, so finally blocks and async with exits inside those tasks run before the scope's caller continues.
The same pattern is why asyncio.timeout is a scope too. When its deadline passes, it cancels the code inside its block, waits for that code to unwind, and only then raises TimeoutError outside the block. A later chapter shows how the two scopes nest.
What you gain
- Local reasoning. A function that uses a scope either finishes all its work or raises. Callers need no knowledge of hidden background tasks.
- Reliable cleanup. Cancellation of siblings and cleanup in
finallycomplete before the error reaches your handler. - No silently lost errors. Failures are collected and raised, not dropped.
- Cancellation that propagates. If the code containing the scope is cancelled, the scope cancels its children too, so cancelling the top of a call tree reaches every task below it.
Edge cases and limits
Asyncio does not enforce the rule. asyncio.create_task still works anywhere. Structured concurrency in asyncio is a discipline you choose by using TaskGroup and timeout. One stray create_task brings back orphans. If you do need a task that outlives its caller, make that choice deliberately: keep a reference, give it an owner, and cancel it at shutdown. That is the fire-and-forget case from the earlier chapter.
Cleanup code can still block the scope. The scope waits for cancelled tasks. A task that catches CancelledError and does not re-raise it, or one that awaits something slow inside finally, delays the scope's exit. A task that ignores cancellation can hang it indefinitely. Structure makes this problem visible, but it does not remove it.
Cancellation is not instant. A task is cancelled at its next await. A task running a long synchronous loop with no await cannot be stopped, and every sibling and the scope itself wait for it.
Results belong to the scope. Task results are safe to read after the block exits, because every task is done. Reading them inside the block, before the tasks finish, raises InvalidStateError.
Scopes nest. A task inside a scope may open its own scope. A failure in the inner scope raises out of that task, which the outer scope treats as a failure of that task and handles the same way. Cancellation passes down through each level.
Choosing between the styles
Use a structured scope when the tasks together produce one result, such as fetching three pages to build one response. In that case a failure in any task means the whole job has failed.
Use independent tasks with owned references when the work has its own lifetime, such as a background cache refresher. Give it a clear start and stop, and cancel it during shutdown.
Use gather with return_exceptions=True only when you really want every result and every failure back as a list, and you accept that nothing cancels the survivors.
Exercise
In the gather example, a fails after 0.1 seconds and b takes 0.3 seconds. After gather raises, is b still running? Name the rule of structured concurrency that this violates, and say what a TaskGroup does differently.
Show answer
Yes. gather raises to the caller but does not cancel b, so b runs on and prints "b finished" later. This violates the rule that a scope must not exit while tasks started in it are still running. A TaskGroup cancels b when a fails, waits for b to finish its cleanup, and only then raises the error, so no task from the group is alive after the block.
Exercise
A function opens async with asyncio.TaskGroup() as tg:, starts two tasks, and in one task catches CancelledError to log it but does not re-raise. What effect does this have on the scope?
Show answer
The scope cannot treat that task as cancelled. If the task then keeps running or returns normally, the scope may wait longer than expected or the cancellation may be effectively swallowed. The task must re-raise CancelledError after cleanup so the scope can finish and the cancellation can propagate.