Skip to content

Lesson 19 of 20 · 19m

asyncio Cancellation and Timeouts: What the Loop Won't Save You From

task.cancel() injects CancelledError at the next await — asyncio.timeout, TaskGroup, shield, and the blocking-call stall are the mechanics behind every async incident.

task.cancel() does not kill a task. It schedules a CancelledError to be raised inside the coroutine at its next await — cancellation is just another exception your code must survive, and every await is a place it can land.

Since Python 3.8 CancelledError is a BaseException, not Exception — the old except Exception: continue pattern that swallowed cancellations is exactly why the change was made. If you catch it, re-raise it: a task that returns normally after cancellation breaks the caller's contract, and asyncio.timeout relies on the error propagating so it can convert it to TimeoutError on exit.

Timeouts and shields

async with asyncio.timeout(5):          # 3.11+
    await client.get(url)               # TimeoutError if the block outlives 5s

asyncio.timeout is a context manager: the cancellation lands at an await inside the block and the block converts it. asyncio.wait_for is the older spelling and still works. asyncio.shield(aw) is the half everyone gets wrong — it protects the inner awaitable so the download keeps running, but your outer await still raises CancelledError. Shield protects the work, not your timeline.

Cleanup belongs in finally and async with, never in code after the await. If cancellation lands between "acquire" and "release", release code that lives below the await never runs — the lock stays held, the connection stays open, and the next incident begins.

Catching CancelledError is legal when the catch itself awaits cleanup — flush, close, commit — as long as it re-raises. Task.uncancel() (3.11) is the edge case worth knowing: asyncio.timeout calls it internally to untangle its own timeout-cancellation from an external cancel() landing at the same moment. You almost never call it directly, but if a finally block swallows the very cancellation timeout raised, the deadline bookkeeping corrupts — which is why the docs tell you to use the context manager rather than racing cancel() by hand.

TaskGroup beats gather

asyncio.TaskGroup (3.11) is structured concurrency: the async with block waits for every task, the first failure cancels the siblings, and failures surface as an ExceptionGroup you catch with except* ValueError:. asyncio.gather(return_exceptions=True) returns exceptions as values in the results list — fine for "try all of these", but it will not cancel the rest, and matching exception to call means indexing back into your inputs.

Two traps ship constantly. asyncio.create_task(coro) without storing the reference: the event loop holds only a weak reference to the task, and if the GC collects it mid-flight the coroutine silently stops — the docs have warned about this since 3.11. Keep a set: tasks.add(t); t.add_done_callback(tasks.discard). And except* — catching an ExceptionGroup with plain except catches nothing, because the group is not an instance of the wrapped types.

The loop is one thread

time.sleep(1), requests.get, a 400 MB json.loads, a regex across a megabyte of user input — each blocks the entire loop. Not your task: every task. asyncio.to_thread(fn) (3.9+) and loop.run_in_executor move blocking calls off the loop; CPU-heavy work goes to ProcessPoolExecutor, because threads don't escape the GIL for compute. await asyncio.sleep(0) yields to the scheduler explicitly. asyncio.Semaphore(n) bounds concurrency — ten thousand simultaneous upstream requests is a self-inflicted outage wearing the word concurrency. For producer/consumer shapes asyncio.Queue(maxsize=N) is the backpressure: put blocks when full, which is a feature — unbounded queues are how crawlers OOM their own process. An asyncio.Lock held across an await is held across every cancellation point inside it too — release happens in async with's exit or in a finally, or the next waiter hangs forever. An unawaited coroutine is a RuntimeWarning and a silent no-op.

The practice

asyncio.timeout for deadlines, TaskGroup for fan-out, finally/async with for cleanup, to_thread for blocking calls, stored references for create_task, except* for ExceptionGroup, and re-raised CancelledError always. Cancellation is control flow — write as if it can happen at every await, because it can.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.