Articles / Python

  • python
  • asyncio
  • concurrency
  • garbage-collection
  • taskgroup
  • debugging

Why Does asyncio Lose Your Background Task Halfway Through?

You call asyncio.create_task(), the job logs "started", and "finished" never arrives. Surprisingly, the event loop doesn't really own your task. It only keeps a weak reference to it, so the garbage collector can be entitled to throw away work that is still in progress.

That is one of three common ways to lose a background task. They leave different clues and need slightly different fixes.

The garbage collector can eat a running task

The code below starts two fire-and-forget tasks and keeps neither return value. One waits on a future that nothing else knows about, and the other just sleeps.

import asyncio
import gc


async def worker(name, wait):
    try:
        print(name, "started")
        await wait()
        print(name, "finished")
    finally:
        print(name, "finally")


async def orphan():
    await asyncio.get_running_loop().create_future()


async def main():
    asyncio.create_task(worker("orphan", orphan))
    asyncio.create_task(worker("sleeper", lambda: asyncio.sleep(0.2)))
    await asyncio.sleep(0.1)
    gc.collect()
    print("collected")
    await asyncio.sleep(0.3)


asyncio.run(main())

On CPython 3.14.4 I get this, with the file paths trimmed out:

orphan started
sleeper started
orphan finally
Task was destroyed but it is pending!
task: <Task pending name='Task-2' coro=<worker() ...> wait_for=<Future pending ...>>
collected
sleeper finished
sleeper finally

The orphan's finally ran, but "finished" never did. Nobody called cancel(). When Python destroyed the suspended coroutine, it closed it, which raises GeneratorExit at the await. An except Exception block won't see that.

The gc.collect() is there to make the failure happen on cue. In a real service, collection runs when the interpreter decides, so the same bug looks random and tends to hide from small tests.

Quick detour: why did the sleeper survive?

The sleeper was saved by accident. asyncio.sleep() registers a timer with the loop, and that creates a chain of ordinary strong references:

  • the loop holds the timer
  • the timer holds the future it will complete
  • the future holds a callback that wakes the task

The orphan's chain is a closed circle: task to coroutine to future and back to task. Nothing outside points in. This is why a test full of sleep() calls can pass happily while code waiting on some privately held future or queue does not.

Keeping a reference stops the vanishing

The asyncio documentation says to save a reference to the result of create_task(), and suggests a set with a done callback:

background_tasks = set()

task = asyncio.create_task(some_coro())
background_tasks.add(task)
task.add_done_callback(background_tasks.discard)

The set must live at least as long as the task should. A local set inside a function that returns immediately buys you very little. Put it on the application or service object that owns the work.

This only fixes collection, so two other holes are still open.

Returning from main cancels whatever is left

asyncio.run() doesn't wait for your background tasks. When the main coroutine returns, CPython's runner cancels every remaining task, waits for them to handle that, and closes the loop.

import asyncio


async def send():
    try:
        print("step 1")
        await asyncio.sleep(1)
        print("step 2")
    finally:
        print("cleanup")


async def main():
    task = asyncio.create_task(send())
    await asyncio.sleep(0.1)
    print("main returns")


asyncio.run(main())

The output is step 1, main returns, cleanup. There is no step 2 and no warning, even though we held a reference. A silent stop at exit usually means cancellation, which you can confirm by catching asyncio.CancelledError, logging it and re-raising.

An exception can stop it while you aren't looking

Sometimes a task that seems lost has actually raised. The exception is stored on the task, waiting for someone to await it. If nobody does, asyncio logs "Task exception was never retrieved" only when the task object is destroyed.

Hang on, that has a daft consequence. If you keep every task in a list and never remove or inspect them, your strong reference also postpones the error report, possibly until shutdown. The documented set-and-discard recipe lets the report out, but you still get a generic message instead of handling the failure.

One small owner handles all three

For fire-and-forget work, I would write one object that holds the tasks, reports failures as they happen and gives them a bounded chance to finish at shutdown.

import asyncio
import logging

log = logging.getLogger(__name__)


class Background:
    def __init__(self):
        self._tasks: set[asyncio.Task] = set()

    def spawn(self, coro):
        task = asyncio.create_task(coro)
        self._tasks.add(task)
        task.add_done_callback(self._done)
        return task

    def _done(self, task):
        self._tasks.discard(task)
        if not task.cancelled() and task.exception() is not None:
            log.error("background task %s failed", task.get_name(),
                      exc_info=task.exception())

    async def drain(self, timeout):
        if not self._tasks:
            return
        _, pending = await asyncio.wait(self._tasks, timeout=timeout)
        for task in pending:
            task.cancel()
        await asyncio.gather(*pending, return_exceptions=True)

Create one, and drain it in a finally so it also runs when the main body fails:

async def main():
    bg = Background()
    try:
        await serve(bg)  # your application, calling bg.spawn(...)
    finally:
        await bg.drain(timeout=5)

Know the limits before you copy it:

  • Stop accepting new work before draining, because tasks spawned during the drain aren't included in the wait.
  • A task that swallows CancelledError and carries on can still hang shutdown.
  • By default SIGTERM kills Python without running your finally. Add a signal handler if your service manager stops processes that way.
  • Nothing in memory survives SIGKILL or a power cut. Work that must happen belongs in a durable queue.

TaskGroup is better when the work has a clear scope

asyncio.TaskGroup, added in Python 3.11, keeps hold of its tasks and doesn't leave the async with block until they finish. If you can arrange your program so background work sits inside such a block, use it.

Watch its failure policy, though. One task raising an ordinary exception cancels its siblings, and the errors come out as an ExceptionGroup. That is right for five requests which only make sense together, and wrong for five unrelated emails.

For independent jobs, handle each failure inside the task so the group never sees it:

async def guarded(coro):
    try:
        await coro
    except Exception:
        logging.exception("background job failed")


async def main():
    async with asyncio.TaskGroup() as tg:
        for n in range(3):
            tg.create_task(guarded(job(n)))  # job is your coroutine

CancelledError isn't a subclass of Exception, so this wrapper still lets cancellation through.

Match the symptom to the cause

  • "Task was destroyed but it is pending!" while the program is running: look for a discarded create_task() result, or an owner that was itself thrown away.
  • Work stops as the program exits: the loop probably cancelled it, so await or drain it first.
  • "Task exception was never retrieved": the task raised, and the traceback underneath is the real bug.
  • No message at all: check that logging reaches the asyncio logger, then log entry, success, exception and cancellation inside the task.

A useful search in any codebase is for lines that begin with asyncio.create_task(. Each one is starting some work and immediately declining to say who is responsible for it.