Lesson 3 of 9 · 24m
Cancellation and Timeouts Without Resource Leaks
How CancelledError travels through coroutines, how timeout semantics changed with asyncio.timeout, and how to write cleanup that survives real shutdowns.
Cancellation is not an exception you occasionally catch and ignore. It is asyncio's structured way of saying: this work is no longer needed, unwind it now. If you treat cancellation as noise, your service leaks sockets, database transactions, locks, and half-written files during deploys and client disconnects.
Cancellation is injected at await points
async def long_job():
try:
await step_one()
await step_two()
except asyncio.CancelledError:
print('cancelled while suspended')
raiseCalling task.cancel() does not instantly stop arbitrary bytecode. It arranges for CancelledError to be raised inside the task at its next suspension point. CPU-bound code that never awaits cannot be cancelled until it yields.
Always re-raise CancelledError unless you are intentionally converting cancellation into a controlled result. Swallowing it breaks timeouts and shutdown because the caller believes cancellation failed.
Modern timeouts are context managers
Python 3.11 introduced the spelling you should prefer:
async def load_profile(user_id):
async with asyncio.timeout(2.5):
return await build_profile(user_id)When the deadline expires, the body is cancelled. The context manager converts that cancellation into TimeoutError outside the block. This avoids older wait_for() edge cases around nested cancellation and makes the scope visually explicit.
asyncio.wait_for() still exists and is common in older code:
row = await asyncio.wait_for(db.fetchrow(query, key), timeout=2)Cleanup belongs in finally, sometimes with shielding
lock = asyncio.Lock()
async def critical_update():
await lock.acquire()
try:
await write_checkpoint()
await commit()
finally:
lock.release()finally runs during cancellation. That is how you release locks, close files, and end transactions. But cleanup itself may need to await — and a second cancellation can interrupt that too. Use asyncio.shield() sparingly for operations that must finish once started:
finally:
await asyncio.shield(close_resource())Shielding is not a cancellation blocker for the outer task; it protects the inner awaitable while cancellation still reaches the waiter. Read it as 'let this resource finish closing', not as 'ignore shutdown'.
Cancellation scopes must match ownership
A caller may cancel a child operation it started. It should not reach across the service and cancel tasks owned by another subsystem. During application shutdown, cancel in reverse order: stop accepting new work, drain or deadline in-flight work, cancel background supervisors, then close shared clients and pools.
Field notes
CancelledErrorinherits fromBaseException, soexcept Exceptiondoes not catch it in modern Python — but broadexcept BaseExceptionabsolutely will.- Never
except asyncio.CancelledError: passunless you can explain exactly who is responsible for finishing the operation. - Timeouts should be near the operation they protect: connect, query, downstream call, or whole request. One giant timeout hides where time went.
- Cancellation during a lock acquisition can leave code outside the
try; acquire first, then entertryimmediately.
Was this lesson helpful?