Sub topic 13
Protecting work from cancellation with shield
This chapter assumes you know asyncio.create_task, Task.cancel(), how CancelledError propagates, and how asyncio.timeout and asyncio.wait_for behave. It uses Python 3.11 or newer.
What shield does
Cancellation normally travels down. If you cancel a task, it is cancelled at its current await. If that await is waiting on another task, the cancellation is passed on to it.
asyncio.shield(aw) breaks that chain. It wraps aw in a task, if it is not one already, and returns a separate outer future. Awaiting the outer future waits for the inner work. Cancelling the outer future does not cancel the inner work.
Use it when you want to stop waiting for something without stopping the thing itself. Typical cases are a database commit, a message acknowledgement, or a cache write that must not be left half-done.
The basic pattern
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())Without shield, wait_for would cancel save() when the timeout expires. With it, wait_for cancels only the outer wrapper. The inner task keeps running, and the program can await it later.
The code keeps its own reference to inner. That reference is not optional, as the next sections explain.
Gotchas
You must keep the inner task
When you pass a coroutine instead of a task, shield creates the inner task for you and you have no handle to it. If the outer wait is cancelled, nobody can await that task afterwards. The event loop also keeps only weak references to tasks, so an unreferenced task can be garbage-collected before it finishes. Create the task yourself, store it, and pass it to shield.
Errors from the inner task can disappear
If the outer future was cancelled and the inner task later fails, shield marks the exception as retrieved. This avoids a "Task exception was never retrieved" warning, but it also means the error is not reported anywhere. If you care about the outcome, await inner yourself afterwards, as the example does, or attach a done callback that logs inner.exception().
Shield does not survive loop shutdown
asyncio.run cancels every task still pending when the main coroutine returns. That includes your shielded inner task. In the example above, main awaits inner before returning. If it returned without doing so, save would be cancelled mid-way.
Shield does not protect tasks in a TaskGroup
When a TaskGroup aborts, it calls cancel() directly on each of its child tasks. If inner was created with tg.create_task, that cancellation reaches it without going through any shield wrapper. The group will also wait for inner before the async with block exits, so you cannot use a shield to let a child escape its group. To make work outlive the group, create it outside the group's scope and make something else responsible for awaiting it.
The caller still sees the cancellation
shield does not hide the cancellation from the code that was waiting. That code still receives CancelledError or TimeoutError. Only the inner work is protected, which is the point.
The table below summarizes what is and is not protected.
| Situation | Inner work survives? |
|---|---|
| Outer task cancelled while awaiting `shield(inner)` | Yes |
| `wait_for(shield(inner), t)` times out | Yes |
| `asyncio.timeout` expires around `await shield(inner)` | Yes |
| `inner` is a child of a `TaskGroup` that aborts | No |
| `asyncio.run` finishes while `inner` is pending | No |
| Someone calls `inner.cancel()` directly | No |
Shielding cleanup code
A common use is protecting cleanup that runs in a finally block. A single task.cancel() does not interrupt await calls in finally, because the cancellation has already been delivered. A second cancellation does. That happens when a timeout fires during cleanup, or when a framework cancels twice.
import asyncio
async def flush_to_disk():
await asyncio.sleep(0.2)
print("flush: finished")
async def worker():
try:
await asyncio.sleep(10)
finally:
await asyncio.shield(flush_to_disk())
print("worker: cleanup done")
async def main():
task = asyncio.create_task(worker())
await asyncio.sleep(0.1)
task.cancel()
await asyncio.sleep(0.05)
task.cancel() # second cancel arrives during cleanup
try:
await task
except asyncio.CancelledError:
print("worker cancelled")
await asyncio.sleep(0.3) # give the flush time to finish
asyncio.run(main())The output is:
worker cancelled
flush: finishedThe flush completes, which is what the shield is for. The second cancel still interrupts worker, so worker: cleanup done is never printed. Any cleanup steps after the shielded await are skipped.
If the whole cleanup sequence must run, put all of it inside one shielded coroutine, and make sure something awaits that task before the loop closes. Here main does this with the final sleep. Real code should await the task itself, because a fixed sleep is a guess.
Do not swallow the CancelledError. After cleanup, let it propagate so the caller and any enclosing TaskGroup or timeout can see that the task was cancelled.
When to avoid shield
Shield is a workaround for work that cannot be interrupted safely. Consider these first:
- Make the operation idempotent, so a cancelled attempt can be retried without harm.
- Use the database's transaction rollback, so cancellation leaves no partial state.
- Put the critical section in a separate, supervised task with its own lifecycle, and communicate with it through a queue.
Overusing shield makes shutdown slow, because protected work must finish before the process can exit. Shielded work with no timeout of its own can hang a shutdown forever, so bound it with asyncio.timeout inside the shielded coroutine.
Shield compared with wait_for alone
| Approach | On timeout | Use when |
|---|---|---|
| `wait_for(coro, t)` | Cancels `coro` | The work is useless after the deadline |
| `wait_for(shield(task), t)` | Stops waiting, task continues | The work should finish, but the caller cannot wait |
| `timeout(t)` around `await shield(task)` | Same as above, with block scope | You need one deadline over several awaits |
Exercise
A handler runs await asyncio.wait_for(asyncio.shield(save_record(record)), timeout=2), where save_record is a coroutine function. The save sometimes takes 5 seconds and fails with an exception. After a timeout, the failure is never logged. Name two problems with this code and give a fix.
Show answer
First, shield was given a bare coroutine, so the inner task has no reference. The handler cannot await it after the timeout, and the task may be garbage-collected before it finishes. Second, once the outer wait is cancelled, shield marks the inner task's exception as retrieved, so a later failure is silently dropped. The fix is to create the task yourself with inner = asyncio.create_task(save_record(record)) and keep it, for example in a set with a done callback that removes it. Then wrap it with shield(inner) and, after a TimeoutError, await inner (or log inner.exception() in a callback) so success or failure is observed. Also make sure the process awaits inner before asyncio.run returns.
Exercise
You create inner with tg.create_task(...) inside a TaskGroup, and a sibling task raises. Does await asyncio.shield(inner) elsewhere in the group keep inner running?
Show answer
No. The group cancels each of its child tasks directly with cancel(), which does not pass through the shield wrapper. The group also waits for inner before the async with block ends. To let work outlive a group, create it outside the group and have a longer-lived owner await it.