- Book: Hexagonal Architecture in Python
- Companion code: hexagonal-python-examples — every listing from the book, free on GitHub
- My project: Hermes IDE | GitHub — an IDE for developers who ship with Claude Code and other AI coding tools
- Me: xgabriel.com | GitHub
You write asyncio.create_task(send_webhook(order)) in a request handler, return the response, and move on. Most days the webhook goes out. Some days it doesn't, and the only trace is one log line: Task was destroyed but it is pending!
That is documented behavior. The asyncio docs for create_task carry an "Important" box: "Save a reference to the result of this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn't referenced elsewhere may get garbage collected at any time, even before it's done."
The box came out of bpo-44665, filed in 2021. The proposal to change the design, cpython#91887 "Use strong references for free-flying tasks", was opened in April 2022 and is still open. In that thread Guido van Rossum wrote that the weak reference "has always been part of the design, it just wasn't made explicit in the docs." So this is old, intended behavior. The Python 3.15 docs still describe it.
Most unreferenced tasks survive by accident. The ones that don't share one shape, and you can build it on purpose.
Where the weak reference lives
Open the pure-Python implementation in Lib/asyncio/tasks.py. Every scheduled task is registered in one module-level set:
_scheduled_tasks = weakref.WeakSet()
_eager_tasks = set()
def _register_task(task):
"""Register an asyncio Task scheduled to run on an event loop."""
_scheduled_tasks.add(task)
That WeakSet is what asyncio.all_tasks() iterates. It lets asyncio list your tasks without keeping any of them alive. The comment above it says eagerly executed tasks sit in a plain set while they run eagerly, and "may graduate to a WeakSet if the task blocks on IO." So an eager task that blocks on IO can end up in the same WeakSet as everything else.
The C accelerator changed its bookkeeping in Python 3.14. CPython's internal asyncio notes say it used a WeakSet "so that the event loop doesn't hold strong references to the tasks," and that 3.14 replaced it with a per-thread linked list embedded in each task. The public contract did not change: the 3.15 docs still say the loop keeps only weak references.
When a task gets collected while pending, Task.__del__ reports it through the loop's exception handler with the message 'Task was destroyed but it is pending!' (it's right there in tasks.py). By then the code after your await will never run.
Why most fire-and-forget tasks survive anyway
If the loop doesn't hold your task, why does create_task(asyncio.sleep(5)) without a saved reference usually finish fine? Because something else does.
A task that is suspended on a future registers a wakeup callback on it. In __step_run_and_handle_result, the task calls result.add_done_callback(self.__wakeup, context=self._context). A bound method holds its object, so the future now holds the task.
Now follow asyncio.sleep. Its body does future = loop.create_future() and then loop.call_later(delay, futures._set_result_unless_cancelled, future, result). The loop's timer heap holds that handle, the handle holds the future, the future's callbacks hold the task. That chain starts at the running loop, so the task is reachable and safe. Socket reads anchor the same way through the selector's registered handles, which is the point a DEV post on this bug makes too.
The danger is a task waiting on something only it can see. Look at asyncio.Event.wait:
fut = self._get_loop().create_future()
self._waiters.append(fut)
try:
await fut
return True
finally:
self._waiters.remove(fut)
If the Event is a local inside the task's coroutine, you get a closed loop: task → coroutine frame → event → _waiters → future → wakeup callback → task. Nothing outside that ring points in. Once you drop the value create_task returned, the ring is garbage, and the cyclic collector can reclaim all of it whenever it next runs. That timing is why Will McGugan called it a Heisenbug: whether the task survives depends on when the garbage collector happens to run, which makes it close to impossible to reproduce.

A task, its coroutine, a private Event and its future can form a closed ring with no path from the loop.
Reproducing it on purpose
You can force the timing with an explicit gc.collect():
import asyncio
import gc
async def wait_for_signal() -> None:
signal = asyncio.Event() # only this coroutine holds it
await signal.wait()
print("after the wait")
async def main() -> None:
asyncio.create_task(wait_for_signal()) # result dropped
await asyncio.sleep(0) # let the task start and block
gc.collect() # a collection that lands right now
await asyncio.sleep(0.1)
asyncio.run(main())
After sleep(0) the task has started and is parked on the event's future. The only references to it are inside the ring described above, so gc.collect() finds an unreachable cycle and reclaims it. What you should see is the Task was destroyed but it is pending! report from the loop's exception handler, logged on the asyncio logger, and never after the wait. I haven't pasted a captured run here; the mechanism is the one in the CPython source linked above. Swap the Event for asyncio.sleep(10) and the task survives, because the timer heap anchors it.
In production the "event" is rarely an Event. It's a client library's internal future, a queue nobody else holds, or a lock created inside the task. You don't control those chains, which is why the docs' advice is blunt: keep the reference yourself.
Two fixes from the docs
The first is a held set with a done callback. The docs show background_tasks.add(task) followed by task.add_done_callback(background_tasks.discard), so the set holds each task until it finishes and then lets go. The same page warns that this never awaits the tasks, so a failure ends up as "Task exception was never retrieved" when the task is collected. Retrieve the exception in the callback and log it yourself:
import asyncio
import logging
from collections.abc import Coroutine
from typing import Any
log = logging.getLogger(__name__)
_background: set[asyncio.Task[None]] = set()
def _on_done(task: asyncio.Task[None]) -> None:
_background.discard(task)
if task.cancelled():
return
exc = task.exception()
if exc is not None:
log.error("background task failed", exc_info=exc)
def spawn(coro: Coroutine[Any, Any, None]) -> asyncio.Task[None]:
task = asyncio.create_task(coro)
_background.add(task)
task.add_done_callback(_on_done)
return task
The second is asyncio.TaskGroup, added in 3.11, which the create_task note says "keeps a strong reference to each task, awaits them and propagates their exceptions." It's the right tool when the caller can wait: all tasks are awaited when the async with block exits. Two properties make it a poor fit for "send it after the response." The block doesn't exit until every task is done, and the first task that fails with anything other than CancelledError cancels the rest and raises an ExceptionGroup. One flaky webhook should not cancel its neighbors.
If you are inside FastAPI, there is a third option: BackgroundTasks runs work "after returning a response," and you don't call create_task yourself. Its docs point you to bigger tools like Celery when the work is heavy or should run in other processes or on other servers.
Put "in the background" behind a port
All three fixes are scheduling policy. Held set, task group, framework hook or a real queue, that choice belongs to the edge of the app. If your use case calls asyncio.create_task directly, the policy is baked into the core. Every test of that use case has to yield to the loop or sleep before it can see the side effect, and still leaves a task pending when it returns. Switching to an outbox later means editing business code.
So give the core a port that says what happened and nothing about how it gets delivered:
from dataclasses import dataclass, field
from typing import Protocol
class OrderNotifier(Protocol):
def order_placed(self, order_id: str) -> None: ...
@dataclass
class Order:
id: str
@dataclass
class InMemoryOrders:
rows: dict[str, Order] = field(default_factory=dict)
async def add(self, order: Order) -> None:
self.rows[order.id] = order
@dataclass
class PlaceOrder:
orders: InMemoryOrders
notifier: OrderNotifier
async def __call__(self, order: Order) -> None:
await self.orders.add(order)
self.notifier.order_placed(order.id)
order_placed is a plain def, on purpose. The core hands off and returns; it can't await the delivery even by accident. (In a real app orders would be a repository port too; the in-memory class keeps the example short.)

The use case sees one port. The test plugs in a recorder; production plugs in the adapter that owns the tasks.
The production adapter owns the tasks and the shutdown drain:
import asyncio
import logging
from collections.abc import Awaitable, Callable
log = logging.getLogger(__name__)
class AsyncioOrderNotifier:
def __init__(
self, send: Callable[[str], Awaitable[None]]
) -> None:
self._send = send
self._tasks: set[asyncio.Task[None]] = set()
def order_placed(self, order_id: str) -> None:
task = asyncio.create_task(self._run(order_id))
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
async def _run(self, order_id: str) -> None:
try:
await self._send(order_id)
except Exception:
log.exception("notify failed for %s", order_id)
async def drain(self, timeout: float) -> None:
if self._tasks:
await asyncio.wait(self._tasks, timeout=timeout)
Call drain from your app's shutdown hook (FastAPI's lifespan is the natural place) so a deploy doesn't kill in-flight sends. Catching inside _run means no task ever ends with an unretrieved exception.
The test never yields to the loop or sleeps. asyncio.run is the only asyncio call in it:
import asyncio
# PlaceOrder, Order, InMemoryOrders from the listing above
class RecordingNotifier:
def __init__(self) -> None:
self.sent: list[str] = []
def order_placed(self, order_id: str) -> None:
self.sent.append(order_id)
def test_place_order_notifies() -> None:
notifier = RecordingNotifier()
place = PlaceOrder(InMemoryOrders(), notifier)
asyncio.run(place(Order(id="o-1")))
assert notifier.sent == ["o-1"]
The fake is synchronous, so the assertion runs after the use case returns with nothing left pending. The weak-reference problem now exists in exactly one class, and that class has one job, which makes it the one place to test GC survival, drain timeouts and failure logging.
What the port doesn't buy you
An in-process task, held or not, dies with the process. A crash between the database commit and the send loses the notification, and the held set can't help with that. If losing one matters, swap AsyncioOrderNotifier for an adapter that writes an outbox row in the same transaction and lets a worker deliver it. The use case and its test stay exactly as they are.
A good first step: search your code for create_task( calls whose result isn't assigned. Each one is a candidate for that adapter.
If this was useful
The move in the last two sections, keeping the core apart from the event loop behind a port and pushing scheduling into one adapter, is what Hexagonal Architecture in Python is about. The book builds one async FastAPI + SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered, vertical slice) and measures the trade-offs, and every listing runs from the free companion repo on GitHub.

Top comments (0)