Sub topic 13
Protecting work from cancellation with shield
This chapter assumes you know asyncio.create_task, asyncio.timeout, asyncio.wait_for, and how CancelledError works. You need Python 3.11 or newer.
The problem
Cancellation normally passes down to whatever a task is awaiting. Suppose a request handler awaits a database save and its deadline expires. The save is cancelled too, which can leave a write half done. Sometimes you want the caller to stop waiting while the work itself finishes.
asyncio.shield(aw) does this. It wraps an awaitable in a new outer future. If the outer future is cancelled, the cancellation stops there and the inner task keeps running.
A shielded save
import asyncio
async def save():
await asyncio.sleep(0.3)
print("save finished")
return "saved"
async def main():
inner = asyncio.create_task(save())
try:
await asyncio.wait_for(asyncio.shield(inner), timeout=0.1)
except TimeoutError:
print("stopped waiting, but save is still running")
print(await inner)
asyncio.run(main())The timeout fires after 0.1 seconds. wait_for cancels the shield wrapper, not inner. The TimeoutError is raised, and the later await inner collects the result once the save completes.
Gotchas
- Keep a reference to the inner task. If you write
shield(save())and the caller is cancelled, nothing else refers to the inner task. It can be garbage collected or go unobserved. Create the task yourself, as above. - Shield delays cancellation, it does not remove it. The shielded task can still be cancelled directly with
inner.cancel().asyncio.runalso cancels all remaining tasks when it shuts down, so a shielded task that outlivesmainis still cancelled. - Errors can go unseen. If the inner task fails after the caller has stopped waiting, nobody retrieves the exception. Asyncio logs "Task exception was never retrieved". Await the inner task later, or add a done callback that inspects
inner.exception(). - A shield does not protect the outer task. The awaiting task still receives
CancelledErrorat the shield line. Only the inner work is saved. - Shield inside a TaskGroup does not keep the group open. If the group is cancelled, the shielded work is orphaned in the way structured concurrency tries to prevent. A good use is a short, critical step, such as committing a transaction. It is a poor fit for long background jobs.
Choosing shield
| Situation | Approach |
|---|---|
| Caller may give up, but the write must complete | `shield` on a task you hold |
| Work should stop when the deadline passes | `asyncio.timeout`, with no shield |
| Cleanup that must finish during cancellation | `finally` block, optionally with a shielded await |
Exercise
In the shield example, what is cancelled when wait_for times out, and why does await inner still return "saved"?
Show answer
Only the outer future returned by asyncio.shield(inner) is cancelled. The inner task is a separate task that never received the cancellation, so it keeps running and finishes after 0.3 seconds. Awaiting it afterwards returns its result.