Lesson · Async Python
Structured Concurrency with TaskGroup
99 min readStructured Concurrency with TaskGroup
`TaskGroup` gives child tasks a structured lifetime tied to a lexical scope. If a child fails, the group coordinates sibling cancellation and reports failures with exception-group semantics.
Learning goals
- Explain how the
async with asyncio.TaskGroup()block owns every child task created inside it. - Describe what the group does when one child raises: sibling cancellation, waiting, then a single raise.
- Read child results from their handles after the block exits and say why that is safe.
- Contrast a failing
TaskGroupblock with loosecreate_taskcalls that nobody gathers. - Catch the group's failure with
except*and inspect the exception group it carries.
Mental model
The block is the owner of every task it creates: it awaits all of them at exit, and one child's failure moves the group into cancelling the rest before the final raise. Nothing created inside the block can outlive it, which is what keeps shutdown and error reporting predictable.
The block owns every task it created
one failure settles the whole scope
Mental model
the same mechanism as a compact list
TaskGroup scope ├── child A ├── child B └── child C failure → coordinated completion/cancellation → group exit
Core idea
TaskGroup ties child tasks to the block that created them: the block cannot finish until every child has finished, and a child failure cancels the siblings and comes back out as one exception group. That folds the two jobs loose tasks leave to you, keeping handles and cancelling on failure, into the scope that started the work.
asyncio.TaskGroup
TaskGroup creates child tasks within a structured scope and waits for them when the block exits. A child failure triggers coordinated handling of the remaining children.
Task lifetime tied to a lexical scope
A task's lifetime should be owned by a scope or component that can await completion and observe failure. Unowned background tasks make shutdown and error reporting unreliable.
Waiting for child tasks
When the async with block ends, the group suspends the enclosing coroutine until every child task has finished; no gather call is needed because awaiting the group is implicit. The block exits only after the last child returns, which is why results read after the block are already available.
Failure propagation
Failure propagation defines which parent or sibling work learns about an error and what happens next. Structured concurrency makes these relationships explicit.
Cancellation propagation
Cancellation propagation is a control-flow event used to stop unfinished concurrent or asynchronous work. Code must release resources and decide whether to propagate, translate, or deliberately suppress the cancellation.
ExceptionGroup interaction
If children fail, the group collects their exceptions into one ExceptionGroup raised when the block exits; except* clauses select the failure types they can handle from that group. Several children can fail before cancellation lands, and the group reports all of them together.
Comparing TaskGroup with loose create_task() usage
Loose create_task calls hand back handles that you must gather, check, and cancel yourself, and a failure is easy to miss. TaskGroup keeps the same children inside a block that awaits them, cancels siblings on failure, and raises their errors as a single group, so lifetime and error handling follow the scope.
Timeouts
Timeouts places an upper bound on waiting. A timeout does not automatically undo external side effects, so design cancellation and cleanup around the resource being used.
Bounded concurrency with semaphores
Bounded concurrency caps the number of simultaneous operations, often with a semaphore or worker pool. This protects downstream services, memory, file descriptors, and latency.
Async producer-consumer pipelines
A producer-consumer pipeline connects coroutines that put items onto a queue with coroutines that take them off. The queue decouples the two sides and, when bounded, applies backpressure, while a TaskGroup is a natural owner for both sides' lifetimes.
Walkthrough
async with asyncio.TaskGroup() as groupopens the scope;group.create_task(work("A", 0.2))andgroup.create_task(work("B", 0.1))schedule both children immediately and the group owns them from then on.- Leaving the block is itself a wait: the code after it runs only when both
workcalls have returned, which is whya.result()andb.result()are ready and printA B. - The
return nameinsideworksupplies each child's result, but the group does not collect results; you read them from the handlesaandbafter the block exits. - Predict before running: the printed pair, and what the program does instead when
work("B", 0.1)raisesValueErrorbefore its sleep.
Experiments to try
- Reorder the delays so A is faster than B and confirm the block still waits for the slower child before printing.
- Make
workraiseValueErrorwhenname == "B"; catch the block withexcept* ValueError, printeg.exceptions, and checka.cancelled()afterwards. - Replace the group with two bare
create_taskcalls that nobody awaits, letmainreturn while both sleep, and compare the shutdown messages with the structured version. - Start ten children that each
await asyncio.sleep(0.05)and confirm from the total time that they overlapped inside the one scope.
Playable lesson
Lab: TaskGroup structured concurrency
Draw a parent scope with child tasks. Fail one child and visualize sibling cancellation, group exit, and the resulting exception group.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
TaskGroup scope
async with asyncio.TaskGroup()
owns three children, waiting for all of them
child A
running
await work(name, delay)
work("A", 0.3)
child B
running
await work(name, delay)
work("B", 0.1)
child C
running
await work(name, delay)
work("C", 0.2)
Predict first
The block body finishes right after scheduling the children. When does execution continue past the block?
The block is entered and both `create_task` calls are made. The block owns every task it created, so none of them can outlive it, and it will await them all at exit.
Common mistakes
- Assuming the block can exit while children still run: it awaits every child, so any code after
async withobserves finished tasks, and leaking a child into the next scope is impossible by construction. - Swallowing
CancelledErrorinside a child with a bareexceptorexcept BaseException: the coordinated shutdown can stall or lose the propagation the group relies on. - Handling the group's failure with plain
except SomeError: the block raises anExceptionGroup, so the individual failures needexcept*or another way to unpack the group. - Expecting exactly one exception when a child fails: several children can fail before cancellation lands, and all of their errors are reported together.
Practice: Easy
- Run the worked example with a
print("block exited")line after theasync withand verify it appears only after bothworkcalls finish. - Add start and end prints inside
work; confirm both starts precede both ends and label each line with its delay. - Change
workto returnname * 2and confirma.result()andb.result()print the doubled names read from the handles.
Practice: Medium
- Make
work("B", ...)raiseValueErrorimmediately; wrap the block inexcept* ValueError, print the number of exceptions in the group, and verifya.cancelled()is True. - Schedule five children with delays from 0.05 to 0.25 and record the total runtime; explain why it approaches 0.25 rather than the sum of the delays.
- Rewrite the same two children with bare
asyncio.create_taskcalls and no awaiting; run both versions with a 0.5 second sleep and describe the difference at shutdown.
Practice: Hard
- Build
fetch_all(items)with aTaskGroupplus a semaphore of three and a shared results list; verify with timestamps that no more than three children run at once. - Create a failure setup where two children raise different exception types; catch both with
except*and state how the group treated the third, sleeping child. - Put
asyncio.timeout(0.1)around a slow child inside the group; explain from the raised exception whether the timeout surfaced as the child's failure or as the group's.
Lesson checklist
- I can describe what happens at the end of an
async with asyncio.TaskGroup()block. - I can explain sibling cancellation and name the object a failing group raises.
- I can read child results from their handles after the block exits.
- I can choose
TaskGroupover loosecreate_taskcalls when failure coordination matters.
Remember
A `TaskGroup` gives its children one owner: the block that started them. The block exit awaits every child, a child failure cancels the rest, and the failures come out together as an `ExceptionGroup`, so lifetime and error handling stop depending on remembering to gather by hand.
Interview angles
What is the main purpose of **asyncio.TaskGroup**?+
TaskGroup creates child tasks within a structured scope and waits for them when the block exits. A child failure triggers coordinated handling of the remaining children.
What should you pay attention to when using **Task lifetime tied to a lexical scope**?+
A task's lifetime should be owned by a scope or component that can await completion and observe failure. Unowned background tasks make shutdown and error reporting unreliable.
How does **Waiting for child tasks** fit into this lesson?+
When the async with block ends, the group suspends the enclosing coroutine until every child task has finished; no gather call is needed because awaiting the group is implicit. The block exits only after the last child returns, which is why results read after the block are already available.
Why is a plain `except Exception` the wrong tool for a failing `TaskGroup` block when you need the individual failures?+
The block raises an ExceptionGroup that wraps the children's exceptions, so a plain handler catches the wrapper but gives you no direct handle on each failure. except* ValueError splits the group and hands over the matching member exceptions with their tracebacks.