Sub topic 3
Fire-and-forget tasks and why you must keep a reference
This chapter assumes you are on Python 3.11 or newer. It also assumes you can write async def functions, call asyncio.run, and use try/finally. You have already seen asyncio.create_task. Here you will learn the one habit that makes it safe for background work.
The problem
A fire-and-forget task is one you start and never await. Examples are sending an audit log entry or refreshing a cache. The obvious code looks like this:
import asyncio
async def audit(event):
await asyncio.sleep(0.1)
print(f"audited {event}")
async def handler():
asyncio.create_task(audit("login")) # reference dropped
return "ok"
async def main():
print(await handler())
await asyncio.sleep(0.3)
asyncio.run(main())This often works, which makes the bug hard to spot. The event loop keeps only a weak reference to each task. A weak reference does not stop the garbage collector from freeing an object. If nothing else points to the task, it can be collected while it is still pending. The work then stops partway, with no error and no log line.
Keep a strong reference
Store each task in a collection that lives as long as the work does. Remove it when it finishes, so the collection does not grow forever.
import asyncio
background_tasks = set()
def _finished(task):
background_tasks.discard(task)
if not task.cancelled() and task.exception() is not None:
print(f"background task failed: {task.exception()!r}")
def spawn(coro):
task = asyncio.create_task(coro)
background_tasks.add(task)
task.add_done_callback(_finished)
return task
async def audit(event):
await asyncio.sleep(0.1)
print(f"audited {event}")
async def main():
spawn(audit("login"))
spawn(audit("logout"))
await asyncio.sleep(0.3)
asyncio.run(main())The _finished callback runs when the task ends, whether it succeeded, failed, or was cancelled. Check task.cancelled() first, because calling task.exception() on a cancelled task raises CancelledError.
Errors in background tasks
If a task fails and nobody ever reads its result or exception, Python prints "Task exception was never retrieved" when the task is garbage collected. That message may appear long after the failure. The done callback above reads the exception right away, so each failure is reported when it happens. In real code, use logging instead of print.
When not to fire and forget
Fire-and-forget fits work whose outcome you truly do not need. If a failure should affect the caller, or the work must finish before a function returns, use a different tool. asyncio.TaskGroup ties task lifetimes to a block and reports every failure. You will meet it shortly.
| Situation | Tool |
|---|---|
| Optional side work, such as metrics | `create_task` plus a stored reference |
| Work that must finish before you continue | `TaskGroup` |
| Failures must reach the caller | `TaskGroup` |
Exercise
A teammate writes asyncio.create_task(send_email(user)) inside a request handler and never stores the result. Emails occasionally go missing, with no error in the logs. Give the likely cause and a fix.
Show answer
The event loop holds only a weak reference to the task, so the garbage collector can destroy it while it is still pending. Store the task in a module-level set, add it before returning, and register task.add_done_callback(background_tasks.discard). A callback that also logs task.exception() will make failures visible.