Sub topic 12
Putting a timeout around a task group
This chapter assumes you know asyncio.TaskGroup, asyncio.timeout, and CancelledError from the earlier chapters. It covers what happens when you combine them, where to place the timeout, and which edge cases can surprise you.
Two places to put a timeout
A timeout and a task group can be nested in two ways:
- Outside the group. One deadline covers the whole group. When it expires, every unfinished child is cancelled.
- Inside a child. Each task has its own deadline. When one expires, only that task is affected, though the group may react to the error.
Pick the placement by the question you are answering. "How long may this whole batch take?" calls for an outer timeout. "How long may each request take?" calls for inner timeouts.
| Placement | Scope of the deadline | Exception you catch | Siblings of the expired task |
|---|---|---|---|
| Outside the group | The whole `async with TaskGroup` block | `TimeoutError` | Cancelled by the group |
| Inside a child, error escapes | One task | `ExceptionGroup` (use `except* TimeoutError`) | Cancelled by the group |
| Inside a child, error handled | One task | None, the child returns a fallback | Keep running |
A timeout outside the group
This example is the main pattern of the chapter:
import asyncio
async def work(i):
await asyncio.sleep(i)
print(f"work {i} finished")
async def main():
try:
async with asyncio.timeout(1.5):
async with asyncio.TaskGroup() as tg:
for i in range(1, 4):
tg.create_task(work(i))
except TimeoutError:
print("deadline hit, remaining tasks were cancelled")
asyncio.run(main())It prints work 1 finished after one second. At 1.5 seconds it prints deadline hit, remaining tasks were cancelled. Tasks 2 and 3 never finish.
What happens at the deadline
The parent task is the task running main. It is suspended inside the group's __aexit__, waiting for the children. The steps are:
- The timeout's timer fires and calls
cancel()on the parent task. The context manager records that it caused this cancellation. CancelledErroris raised in the parent at its currentawait, which is inside the task group's exit.- The task group sees that its parent was cancelled. It cancels every child that is still running and waits for them to finish.
- The group re-raises
CancelledErrorso that it leaves theasync with TaskGroupblock. - The timeout's
__aexit__receives thatCancelledError. It callsuncancel()on the parent to withdraw its own cancellation request. It then raisesTimeoutErrorin its place.
Your except TimeoutError therefore sits outside the async with asyncio.timeout(...) block. Catching it inside the block would not work, because the conversion happens only when the block exits.
Checking whether the deadline fired
If you need to tell a timeout from other outcomes, keep a reference to the context manager. expired() returns True once the deadline has fired:
import asyncio
async def work(i):
await asyncio.sleep(i)
async def main():
try:
async with asyncio.timeout(0.5) as cm:
async with asyncio.TaskGroup() as tg:
tg.create_task(work(1))
except TimeoutError:
print("expired:", cm.expired())
asyncio.run(main())You can also move the deadline while the block is running with cm.reschedule(new_deadline). The deadline is an absolute time on the event loop's clock, so compute it from asyncio.get_running_loop().time().
The group does not enforce the deadline
The timeout only requests cancellation. The TimeoutError appears after every child has actually stopped. A child with slow cleanup delays it:
import asyncio
import time
async def slow_cleanup():
try:
await asyncio.sleep(10)
finally:
await asyncio.sleep(0.5) # slow cleanup
print("cleanup done")
async def main():
start = time.perf_counter()
try:
async with asyncio.timeout(0.2):
async with asyncio.TaskGroup() as tg:
tg.create_task(slow_cleanup())
except TimeoutError:
print(f"TimeoutError after {time.perf_counter() - start:.1f}s")
asyncio.run(main())The deadline is 0.2 seconds, but the output is cleanup done followed by TimeoutError after 0.7s. The timeout waits for the cleanup to finish.
If cleanup itself might hang, give it its own limit. You can wrap the cleanup await in a separate asyncio.timeout. Cancellation is delivered once per request, so this inner timeout still works while the task is being cancelled.
Timeouts inside children
A timeout inside a child behaves differently. The child's TimeoutError is an ordinary exception raised in a child task. The group treats it like any failure: it cancels the siblings and raises an ExceptionGroup when the block exits.
import asyncio
async def fetch(name, delay):
async with asyncio.timeout(0.5):
await asyncio.sleep(delay)
return name
async def main():
try:
async with asyncio.TaskGroup() as tg:
tg.create_task(fetch("a", 0.1))
tg.create_task(fetch("b", 2))
except* TimeoutError as eg:
print("timeouts:", len(eg.exceptions))
asyncio.run(main())This prints timeouts: 1. A plain except TimeoutError would not match here, because the exception that leaves the group is an ExceptionGroup, not a TimeoutError.
If you want one slow request to degrade gracefully instead of aborting the batch, handle the timeout inside the child and return a fallback:
import asyncio
async def fetch(name, delay):
try:
async with asyncio.timeout(0.5):
await asyncio.sleep(delay)
return f"{name}: ok"
except TimeoutError:
return f"{name}: timed out"
async def main():
async with asyncio.TaskGroup() as tg:
a = tg.create_task(fetch("a", 0.1))
b = tg.create_task(fetch("b", 2))
print(a.result())
print(b.result())
asyncio.run(main())Both tasks complete normally. The output is a: ok and b: timed out. The group never sees an error, so nothing is cancelled.
You can use both placements together. Put a short timeout inside each child and a longer one around the group as a safety net for the whole batch.
Edge cases
- A child fails while the deadline is pending. If a child raises first, the group cancels its siblings and raises an
ExceptionGroup. The timeout's timer is stopped when the block exits, so noTimeoutErroris produced. - A child fails during cancellation. Suppose the deadline has fired and a child raises a real error from its
finallyblock. TheExceptionGrouppropagates, and the timeout does not convert it. You see the child's error, notTimeoutError. - Results of finished tasks. Tasks that completed before the deadline keep their results, but the exception stops you from reaching the code after the block. Store results in a shared list or dict as each task finishes if you need partial output.
wait_foraround a group.asyncio.wait_for(coro, timeout)also works with a coroutine that contains a task group. In 3.12 and later it is implemented withasyncio.timeout, so the behavior matches. Preferasyncio.timeoutwhen the guarded code is a block rather than a single awaitable.
Summary of the rules
- Put the timeout outside the group to bound the whole batch. Expect
TimeoutError. - Put the timeout inside a child to bound one operation. Either handle
TimeoutErrorthere, or catch it withexcept*outside the group. - The
TimeoutErrorarrives only after all children have finished their cleanup. - Re-raise
CancelledErroreverywhere, or the deadline will not be honored.
Exercise
In the code below, what is printed, and in what order? Assume asyncio.run(main()) is called.
async def quick():
await asyncio.sleep(0.1)
print("quick done")
async def lingering():
try:
await asyncio.sleep(5)
finally:
print("lingering cleanup")
async def main():
try:
async with asyncio.timeout(0.5):
async with asyncio.TaskGroup() as tg:
tg.createtask(quick())
tg.createtask(lingering())
except TimeoutError:
print("timeout")
Show answer
It prints "quick done" after 0.1 seconds. At 0.5 seconds the timeout cancels the parent task, and the group cancels lingering. Its finally block prints "lingering cleanup". Only then does the group let the cancellation leave the block, and the timeout converts it into TimeoutError, so "timeout" prints last. The order is: quick done, lingering cleanup, timeout.
Exercise
A task group has three children, and each child wraps its work in its own asyncio.timeout(1) without catching the error. One child takes 3 seconds. What do you need to write to catch the failure, and why does a plain except TimeoutError around the group not work?
Show answer
Use except* TimeoutError. The child's TimeoutError is raised inside a child task, so the group cancels the other children and raises an ExceptionGroup that contains it. A plain except TimeoutError does not match an ExceptionGroup, so the exception would propagate uncaught.