Sub topic 16
Debugging asyncio and avoiding common mistakes
This chapter assumes you can write coroutines, create tasks, and use gather and TaskGroup. It also assumes you know how cancellation works, and that you run Python 3.11 or later. Most asyncio bugs come from a small set of mistakes: a missing await, a blocked loop, a lost task, or a swallowed exception. They are quiet bugs, because nothing crashes. Work simply stops, runs late, or disappears. This chapter shows how to turn the quiet failures into visible ones.
Turn on debug mode first
Debug mode makes the event loop check your code while it runs. It logs coroutines that were never awaited, reports callbacks that run too long, and raises an error when non-thread-safe loop methods are called from the wrong thread. You can enable it in three ways:
- Pass
debug=Truetoasyncio.run. - Set the environment variable
PYTHONASYNCIODEBUG=1. - Start Python with
python -X dev, which turns on asyncio debug mode along with other development checks.
Debug mode slows the program down, so use it during development and tests, not in production. Also set the asyncio logger to a visible level so you see its messages:
import asyncio
import logging
import time
logging.basicConfig(level=logging.DEBUG)
async def blocker():
time.sleep(0.5) # blocks the whole loop
async def main():
await blocker()
asyncio.run(main(), debug=True)The loop reports a warning like Executing <Task ...> took 0.500 seconds. Any step that holds the loop longer than loop.slow_callback_duration (0.1 seconds by default) is reported. The message names the task and the coroutine, which tells you where to look.
Mistake 1: forgetting to await
Calling a coroutine function does not run it. It returns a coroutine object. If you never await it or wrap it in a task, its body never executes.
import asyncio
async def fetch():
await asyncio.sleep(0.1)
return 42
async def main():
result = fetch() # bug: missing await
print(result)
print(await fetch())
asyncio.run(main())The first print shows <coroutine object fetch at 0x...>. Python also emits RuntimeWarning: coroutine 'fetch' was never awaited when the unused coroutine object is discarded. The warning is your main clue. Treat it as an error in tests by running with python -W error::RuntimeWarning.
Type checkers catch this too. A function annotated to return int that receives a Coroutine[Any, Any, int] fails the check.
Mistake 2: blocking the event loop
The loop is cooperative. A coroutine runs until it reaches an await that actually suspends. While it runs, no other task makes progress, no timers fire, and no sockets are serviced. Typical culprits:
time.sleep()instead ofawait asyncio.sleep()- the
requestslibrary, synchronous database drivers, and blocking file reads - CPU-heavy loops, such as parsing a large document or hashing a big file
- calling
Future.result()orThread.join()from inside a coroutine
Debug mode catches long steps after the fact. To watch for them in running code, add a lag monitor. It sleeps for a short interval and measures how late it wakes up. Lateness equals the time something else held the loop.
import asyncio
import time
async def lag_monitor(interval=0.1, threshold=0.05):
loop = asyncio.get_running_loop()
expected = loop.time() + interval
while True:
await asyncio.sleep(interval)
now = loop.time()
lag = now - expected
if lag > threshold:
print(f"loop lag: {lag:.2f}s")
expected = now + interval
async def main():
monitor = asyncio.create_task(lag_monitor())
await asyncio.sleep(0.25)
time.sleep(0.5) # blocks the loop; the monitor reports it
await asyncio.sleep(0.25)
monitor.cancel()
asyncio.run(main())The output is a loop lag line of about 0.4 to 0.5 seconds. Once you find a blocking call, move it off the loop with asyncio.to_thread for blocking I/O. For CPU-bound work, use a process pool through loop.run_in_executor. Alternatively, switch to a library with a native async API.
Mistake 3: losing track of tasks
asyncio.create_task returns a task, but the event loop keeps only a weak reference to it. If you drop the return value, the garbage collector may destroy a task before it finishes. Your background work can vanish with no error.
A task that fails with nobody watching produces a different symptom. When the task object is collected, asyncio logs Task exception was never retrieved. By then the failure is far from its cause.
The fix is to hold a strong reference and handle the result. This helper does both:
import asyncio
background = set()
def report(task):
if not task.cancelled() and task.exception() is not None:
print("task failed:", repr(task.exception()))
def spawn(coro, name=None):
task = asyncio.create_task(coro, name=name)
background.add(task)
task.add_done_callback(background.discard)
task.add_done_callback(report)
return task
async def job():
raise RuntimeError("lost")
async def main():
spawn(job(), name="job")
await asyncio.sleep(0.1)
asyncio.run(main())The program prints task failed: RuntimeError('lost'). Calling task.exception() also marks the exception as retrieved, so the "never retrieved" message does not appear. Where you can, prefer a TaskGroup. It owns its tasks, waits for them, and raises their errors for you.
Mistake 4: swallowing cancellation
CancelledError is how cancellation travels through your code. If a coroutine catches it and carries on, the task refuses to stop. Timeouts, TaskGroup shutdown, and Ctrl+C handling then hang. Two patterns cause this:
async def bad():
try:
await asyncio.sleep(10)
except Exception:
pass # fine on 3.8+, CancelledError is a BaseException
try:
await asyncio.sleep(10)
except BaseException:
pass # bug: swallows CancelledErrorA bare except: has the same effect. Catch specific exception types. If you must catch CancelledError to clean up, re-raise it. Better still, put cleanup in finally:
async def good(resource):
try:
await asyncio.sleep(10)
finally:
resource.close() # runs on success, error, and cancellationMistake 5: other common traps
| Symptom | Likely cause | Fix |
|---|---|---|
| `RuntimeError: asyncio.run() cannot be called from a running event loop` | Calling `asyncio.run` inside a coroutine, or in a notebook that already has a loop | `await` the coroutine instead |
| Program hangs at `await q.join()` | A consumer did not call `task_done()` for every item, or a consumer crashed | Call `task_done()` in a `finally` block |
| Results arrive one after another | Awaiting each coroutine in a loop instead of using `gather` or tasks | Create the tasks first, then await them together |
| Sibling tasks keep running after one failed | `gather` without a `TaskGroup` leaves the other awaitables running | Use `TaskGroup`, or cancel the others yourself |
| Errors hidden in the results list | `gather(..., return_exceptions=True)` returns exceptions as values | Inspect each result with `isinstance(r, BaseException)` |
| Shared state is occasionally wrong | A read-modify-write that spans an `await` | Hold an `asyncio.Lock` across the whole update |
The last row surprises people. A single thread does not make code race-free. Between two await points, other tasks can run and change shared state.
Inspecting a running program
You can ask asyncio what it is doing. Name your tasks with create_task(coro, name="..."), and the names show up in logs and tracebacks. Then list all unfinished tasks:
import asyncio
async def worker():
await asyncio.sleep(10)
async def main():
asyncio.create_task(worker(), name="worker-1")
await asyncio.sleep(0.1)
for task in asyncio.all_tasks():
print(task.get_name(), task.done())
task.print_stack()
asyncio.run(main())print_stack() shows where each suspended task is waiting. A stack that always ends at the same await points to the task that is stuck. Python 3.14 also adds the command python -m asyncio ps PID for inspecting a live process.
A triage routine
The diagram below summarizes how to match a symptom to a cause.
Work in this order: enable debug mode, read the warnings, then add task names and a lag monitor if the problem remains.
Exercise
A service calls asyncio.create_task(save(record)) and discards the return value. Sometimes records are never saved, and no error is logged. Give two reasons this can happen and one fix for each.
Show answer
First, the loop holds only a weak reference to the task, so the garbage collector can destroy it before it finishes. Fix: store the task in a set and remove it with add_done_callback(background.discard). Second, the task may have raised an exception that nobody retrieved, so the failure is only logged late, when the task object is collected. Fix: add a done callback that reads task.exception() and logs it. Alternatively, run the saves inside a TaskGroup, which keeps the tasks alive and raises their errors.
Exercise
Your web service answers requests normally, then every request stalls for about 300 ms at the same moment. Debug mode logs Executing <Task ...> took 0.300 seconds. What is the likely cause, and how do you fix it?
Show answer
One coroutine is running a blocking call, such as a synchronous HTTP or database call, a large file read, or a CPU-heavy loop. It holds the event loop for 300 ms, so every other task waits. Use the task name and coroutine in the log message to find it. Then move the call to asyncio.to_thread for blocking I/O, to a process pool for CPU-bound work, or replace it with an async library.