Sub topic 16
Debugging asyncio and avoiding common mistakes
This chapter assumes you can write coroutines, create tasks, and use gather or TaskGroup. It covers the mistakes that cause most asyncio bugs and the tools that expose them.
Turn on debug mode
Debug mode makes asyncio report problems it normally ignores. Enable it with asyncio.run(main(), debug=True), the environment variable PYTHONASYNCIODEBUG=1, or python -X dev.
The program below has two bugs.
import asyncio
import time
async def fetch():
await asyncio.sleep(0.1)
return "data"
async def main():
fetch() # bug 1: coroutine created but never awaited
time.sleep(0.5) # bug 2: blocks the event loop
result = await fetch()
print(result)
asyncio.run(main(), debug=True)Debug mode prints a warning that coroutine 'fetch' was never awaited. It also logs that the task took about 0.5 seconds to run a step. Any step longer than loop.slow_callback_duration (0.1 seconds by default) is reported this way.
The common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Forgetting `await` | `RuntimeWarning: coroutine ... was never awaited`, or a coroutine object where a result was expected | Add `await`, or wrap the coroutine in a task |
| Blocking the loop (`time.sleep`, `requests.get`, heavy computation) | Every task stalls, timeouts fire late, slow-callback warnings appear | Use async libraries, or `asyncio.to_thread` |
| Dropping the task reference | A background task disappears before it finishes | Store the task in a set |
| Swallowing `CancelledError` | Tasks refuse to stop, and shutdown or timeouts hang | Clean up, then re-raise |
| Unretrieved exceptions | `Task exception was never retrieved` appears at exit | Await the task, or add a done callback |
Keep a reference to background tasks
The event loop holds only a weak reference to a task. If you call create_task and discard the result, garbage collection can destroy the task while it runs. Keep your own reference and remove it when the task finishes.
import asyncio
background = set()
async def work():
await asyncio.sleep(0.2)
print("background work finished")
async def main():
task = asyncio.create_task(work())
background.add(task)
task.add_done_callback(background.discard)
await asyncio.sleep(0.5)
asyncio.run(main())A diagnostic routine
When a program hangs or runs slowly, work through these steps.
- Run with debug mode on and read the warnings first. They usually point at the file and line.
- Look for blocking calls inside
async deffunctions. Search fortime.sleep, synchronous HTTP clients, file reads of large files, and long loops. - Check that every coroutine call is awaited or wrapped in a task.
- Confirm every task is awaited, held in a
TaskGroup, or stored with a done callback, so its exceptions surface. - For a hang, print the running tasks with
asyncio.all_tasks(). Each task'sprintoutput includes the coroutine it is suspended in. - Add timeouts around network calls so a stuck peer cannot block you forever.
Also remember that a mixed program needs care at the boundary. Calling asyncio.run from inside a running loop raises RuntimeError. In that case, await the coroutine instead.
Exercise
Your service prints "Task exception was never retrieved" and some background jobs seem to vanish. Name two likely causes and one fix for each.
Show answer
One cause is that tasks were created with createtask and never awaited, so their exceptions were never read. Fix this by awaiting them, putting them in a TaskGroup, or adding a done callback that checks task.exception(). The second cause is that the task references were discarded, so garbage collection could remove the tasks while they ran. Fix this by storing each task in a set and removing it with adddone_callback(background.discard).
Exercise
A coroutine calls time.sleep(2) while ten other tasks are running. What happens to them, and what should replace the call?
Show answer
All ten tasks freeze for two seconds, because the single event loop thread is blocked and cannot switch tasks. Replace it with await asyncio.sleep(2). If the blocking work is not a sleep, run it with await asyncio.to_thread(...).