What this thread does
Do first: use asyncio.timeout(10) around the operation, then cancel and join owned tasks before closing their resources.
Short answer
As of November 2026, target Python 3.15.2, October 25 release.
Choose / don't choose
- TaskGroup: choose related tasks whose lifetime belongs to one scope; don't detach resource users from that scope.
- shield: choose only independently owned cleanup that must survive caller cancellation; the caller still receives
CancelledError. Retain and eventually join the cleanup task (API).
Not for: selecting sync versus async request handlers; see python-coroutine-never-awaited-and-fastapi-async-def-blocking.
Settings that matter
| Setting or flag | Value / default | Applies to | Source |
|---|---|---|---|
asyncio.timeout(delay) | Seconds, e.g. 10; None disables the limit | Python current docs | API |
asyncio.gather(return_exceptions=True) | Join every already-cancelled task; default is False | Python current docs | API, Lynn Root |
asyncio.shield(task) | Protect child, not caller; retain task reference | Python current docs | API |
Task.cancel() | Request cancellation, then await completion | Python current docs | API |
Order of operations
1. Stop intake; keep dependent clients open. Use try/finally for release; if explicitly catching asyncio.CancelledError, clean up and re-raise. 2. A child failure other than cancellation cancels remaining tasks in the group; scope exit waits for every child, including cleanup, before raising grouped failures (API). 3. For independently owned tasks, cancel all, then await gather(*tasks, return_exceptions=True) and inspect outcomes. Root's July 2018 report, updated July 2019 shows a second termination signal; aggregation lets shutdown continue after cancellation results. 4. Catch TimeoutError outside the timeout context. Cleanup can extend elapsed time; no delay value both forcibly terminates arbitrary cleanup and guarantees its completion. Give cleanup its own bounded I/O and an external termination policy.
Known failures and fixes
| Error (short quote) | Cause | Fix | Source |
|---|---|---|---|
CancelledError | Default gather does not return exceptions | Cancel first, aggregate exceptions while joining | Root's shutdown report |
TaskGroup shutting down | Historical bug: nested TaskGroup could silently swallow cancellation request from parent TaskGroup | Avoid swallowing cancellation; use maintained runtime and explicit ownership | arthur-tacca report, March 2024 |
The nested cancellation report was closed on 2024-04-09 by merged PR #117407; it does not establish that this behavior persists on the target release.
Missing
Task.cancel()does not guarantee cancellation; ten seconds is the documentation example (API).- Deployment kill deadline and cleanup I/O budget are application inputs; the timeout argument alone supplies neither.
Started from a post by @Python Software Foundation, packaged by the editor. Original post