Lesson 7 of 9 · 21m
Structured Concurrency with TaskGroup
Why task lifetimes should be scoped, how asyncio.TaskGroup changes error semantics, and how to structure supervisors and request fan-out so nothing escapes.
Unstructured concurrency is the async version of goto: tasks appear anywhere, finish whenever, fail silently, and outlive the operation that created them. Structured concurrency imposes one rule: concurrent child work has a scope, and the scope does not exit until all children are done.
Python 3.11 made that rule native with asyncio.TaskGroup.
TaskGroup joins child tasks automatically
async def build_dashboard(account_id):
async with asyncio.TaskGroup() as tg:
user_task = tg.create_task(load_user(account_id))
orders_task = tg.create_task(load_orders(account_id))
alerts_task = tg.create_task(load_alerts(account_id))
return {
'user': user_task.result(),
'orders': orders_task.result(),
'alerts': alerts_task.result(),
}The async with block waits for every child before exiting. There is no forgotten task, no hidden background work, and no need to call gather() manually.
One failure cancels the group
If load_orders raises, the task group cancels the sibling tasks and raises an exception group containing the failure. That behavior is usually correct for a request-scoped fan-out: if one required piece failed, the other results no longer matter.
try:
async with asyncio.TaskGroup() as tg:
a = tg.create_task(step_a())
b = tg.create_task(step_b())
except* ValueError as eg:
handle_value_errors(eg)except* looks strange the first time you see it, but it is the language-level answer to 'several tasks may fail at once'. Read the exception group rather than assuming a single exception object.
Sometimes you want partial failure
Required dependencies and optional dependencies are not the same. If recommendations can fail while checkout must continue, isolate them:
async def optional_recommendations(user_id):
try:
async with asyncio.timeout(1):
return await load_recommendations(user_id)
except Exception:
logger.exception('recommendations unavailable')
return []Notice the boundary is explicit. You are not suppressing failure globally; you are degrading one optional feature. For independent batch jobs where every item can fail independently, inspect per-task results or write outcomes to a result queue instead of treating one item failure as total failure.
Supervisors need restart policy, not blind loops
Long-running services often need background supervisors: websocket listeners, queue consumers, cache warmers. A TaskGroup is still useful, but 'restart forever' needs backoff and shutdown awareness:
async def supervise(worker):
delay = 0.2
while not stopping:
try:
await worker()
delay = 0.2
except asyncio.CancelledError:
raise
except Exception:
logger.exception('worker crashed; restarting in %.1fs', delay)
await asyncio.sleep(delay)
delay = min(delay * 2, 10)The important pieces are re-raising cancellation, logging the real exception, backing off, and having a shutdown flag. Blind while True restart loops turn configuration mistakes into CPU spinners and dependency storms.
Field notes
- TaskGroup requires Python 3.11+. In older versions,
gatherplus careful cancellation is the approximation; create child tasks inside the group so the group owns them. - Use
TaskGroupfor bounded fan-out, not unbounded input streams; name tasks withname=so tracebacks andasyncio.all_tasks()dumps are useful.
Was this lesson helpful?