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 coroutines with async/await, run them with asyncio.run, and read a try/finally block. You should already know that asyncio.create_task schedules a coroutine to run concurrently. Here we look at what happens when you schedule a task and never wait for it.
What "fire-and-forget" means
A fire-and-forget task is one you start and never await. Typical uses are sending an audit event, warming a cache, or pushing a metric. The caller does not need the result and does not want to wait.
asyncio.create_task(send_audit("login")) # looks harmlessThis line looks safe, but it hides two problems.
- The task can be garbage collected before it finishes.
- If the task fails, nobody sees the error until the task object is destroyed.
The event loop holds only weak references
create_task returns a Task object and registers it with the event loop. The loop does not keep a strong reference to it. Python's documentation says so directly: the event loop only keeps weak references to tasks, and you should save a reference to the result to avoid a task disappearing mid-execution.
A weak reference does not keep an object alive. If nothing else points to the task, the garbage collector may destroy it, even while it is suspended at an await.
Which tasks survive depends on what they are waiting for. A task sleeping on asyncio.sleep is usually kept alive by the timer the loop has scheduled. A task waiting on a future that only the task itself references can be collected. You cannot rely on either case, because the details are internal to the implementation.
import asyncio
import gc
async def orphan():
try:
await asyncio.get_running_loop().create_future() # never completes
finally:
print("orphan: leaving")
async def main():
asyncio.create_task(orphan()) # reference discarded immediately
await asyncio.sleep(0) # let the task start and suspend
gc.collect() # the task is now unreachable
await asyncio.sleep(0.1)
print("main done")
asyncio.run(main())On CPython this typically logs a "Task was destroyed but it is pending!" message. The work was abandoned without any exception reaching your code. The exact output can vary between versions and runs, which is the point: code that works only when the garbage collector is idle is a latent bug.
The diagram shows who keeps a task alive.
The standard fix: a set plus a done callback
Keep each background task in a collection, and remove it when it finishes. Removal matters because a collection that only grows is a memory leak.
The done callback is also the right place to look at the outcome. Calling task.exception() marks the exception as retrieved, so you decide how it is reported.
import asyncio
import logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("background")
background_tasks: set[asyncio.Task] = set()
def _on_done(task: asyncio.Task) -> None:
background_tasks.discard(task)
if task.cancelled():
log.info("task %s was cancelled", task.get_name())
return
exc = task.exception()
if exc is not None:
log.error("task %s failed", task.get_name(), exc_info=exc)
def spawn(coro, *, name: str | None = None) -> asyncio.Task:
task = asyncio.create_task(coro, name=name)
background_tasks.add(task)
task.add_done_callback(_on_done)
return task
async def send_audit(event: str, delay: float) -> None:
await asyncio.sleep(delay)
if event == "bad":
raise RuntimeError("audit service unreachable")
log.info("audit sent: %s", event)
async def main() -> None:
spawn(send_audit("login", 0.1), name="audit-login")
spawn(send_audit("bad", 0.2), name="audit-bad")
spawn(send_audit("slow", 30), name="audit-slow")
await asyncio.sleep(0.5)
log.info("%d tasks still running", len(background_tasks))
# Shutdown: cancel what is left and wait for it to unwind.
for task in list(background_tasks):
task.cancel()
await asyncio.gather(*background_tasks, return_exceptions=True)
asyncio.run(main())Points to notice:
spawnis the only place that callscreate_taskfor background work, so the rule is enforced in one spot.discarddoes not raise if the task is already gone, so the callback is safe to run in any order.- The callback checks
task.cancelled()before callingtask.exception(). Callingexception()on a cancelled task raisesCancelledError. - At shutdown, the code iterates over
list(background_tasks), a copy, because done callbacks modify the set while you loop. - The
gathercall withreturn_exceptions=Truewaits for the cancelled tasks to finish their cleanup. Without it,asyncio.runwould cancel and drain remaining tasks anyway, but doing it yourself lets you control the order and any timeout.
Unretrieved exceptions
A task that fails and is never awaited keeps its exception inside the task object. Nothing is printed at the moment of failure. When the task is finally garbage collected, asyncio logs "Task exception was never retrieved" through the asyncio logger.
That log line has three weaknesses. It appears at an unpredictable time. It does not tell you which request or user caused the failure. And if you keep a reference forever, for example in a set that never discards, the message may never appear at all.
The done callback above fixes all three: it reports at once, can include the task name, and discards the reference.
Naming tasks
Pass name= to create_task. Names appear in repr(task), in asyncio.all_tasks() output, and in your own log messages. For per-event tasks, include an identifier, such as name=f"audit-{event_id}". When you debug a hang, a list of tasks named Task-4817 is much harder to read than one with meaningful names.
Prefer a TaskGroup when you can
A background set is a manual version of what a TaskGroup does for you. A task group keeps strong references to its tasks and waits for all of them. It also cancels the siblings when one fails, and it reports failures as an ExceptionGroup. You will see these details in later chapters.
Fire-and-forget code is acceptable when the work really should outlive the caller, such as a request handler that returns while a metric upload continues. Even then, the work should belong to something that lives long enough, like the application. A group opened at startup can serve as that owner.
import asyncio
async def push_metric(name: str) -> None:
await asyncio.sleep(0.1)
print("pushed", name)
async def handle_request(tg: asyncio.TaskGroup, request_id: int) -> str:
tg.create_task(push_metric(f"request-{request_id}")) # outlives the handler
return f"response {request_id}"
async def main() -> None:
async with asyncio.TaskGroup() as app_scope:
for i in range(3):
print(await handle_request(app_scope, i))
# Leaving the block waits for every metric push.
print("all background work finished")
asyncio.run(main())The handlers return immediately, and the group's lifetime defines when background work must be finished. The trade-off is that a failure in one background task cancels all the others in the group. For independent best-effort work such as metrics, you may prefer the set-and-callback pattern, or you can catch exceptions inside each background coroutine so that nothing escapes to the group.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| `asyncio.create_task(coro())` with the result discarded | Task may be collected mid-run | Store the task in a set or a task group |
| Adding to a set but never removing | Memory grows with every task | Use `add_done_callback(background_tasks.discard)` or a fuller callback |
| Calling `task.exception()` on a cancelled task | Raises `CancelledError` inside the callback | Check `task.cancelled()` first |
| Iterating over the set while tasks finish | `RuntimeError: Set changed size during iteration` | Iterate over `list(background_tasks)` |
| Swallowing errors with a bare `except Exception: pass` in the coroutine | Failures vanish silently | Log in the task, or in the done callback |
Summary
The event loop does not own your tasks, so your code must. Keep a strong reference until the task finishes, remove it in a done callback, and read the outcome there so failures are logged promptly. Where the work has a natural scope, use a TaskGroup and let it do this bookkeeping.
Exercise
A teammate writes asyncio.create_task(upload(report)) inside a request handler and never stores the result. In production, some uploads occasionally never finish and no error is logged. Explain the likely cause, then describe the change you would make so that (1) the task cannot be lost, (2) the set of running tasks does not grow forever, and (3) a failed upload is logged with the task's name.
Show answer
The event loop holds only a weak reference to the task, and the handler discards the only strong one. If the task is suspended on something that does not keep it reachable, the garbage collector can destroy it before it completes, so the upload is silently abandoned. To fix it, add the task to a module-level set right after creating it with a name such as name=f"upload-{report.id}". Register a done callback that removes the task from the set with discard. In the callback, return early if task.cancelled(), and otherwise call task.exception() and, if it is not None, log it with task.get_name() and the exception. Wrapping these steps in a spawn helper keeps every call site consistent.