Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 40 ยท Testing and Debugging

Debugging asyncio - Debug Mode, Slow Callbacks, Task Inspection

Debug asyncio programs: enable debug mode, find blocking calls and slow callbacks, catch never-awaited coroutines, name and inspect tasks, and monitor event loop lag.

Async bugs are different from ordinary bugs. Nothing crashes where the mistake is: a forgotten await makes a function silently do nothing, one blocking call makes a different part of the program stutter, and an exception inside a background task can vanish without a trace. Finding these needs a few tools that are specific to asyncio.

This lesson shows those tools: debug mode, the slow-callback detector, warnings for coroutines that were never awaited, task names and introspection, handling of forgotten exceptions, and a home-made loop-lag monitor that works anywhere.

What runs where. Debug mode and slow-callback logging belong to CPython's own event loop, which you have on your computer. The browser editor runs Python on a different loop implementation without those two features, so they appear below as read-only snippets. Everything else, including warnings, task inspection, exception handling and the lag monitor, is runnable here.

Turning on debug mode

Any of these enable asyncio's debug mode:

Terminal
python -X dev app.py                 # Python's development mode (also enables asyncio debug)
PYTHONASYNCIODEBUG=1 python app.py   # just asyncio debug
Python
asyncio.run(main(), debug=True)      # or loop.set_debug(True)

You should also enable logging at DEBUG level for the asyncio logger so messages appear:

Python
import logging
logging.basicConfig(level=logging.DEBUG)

Debug mode changes the loop in useful ways (it is slower, so use it in development and tests, not in production):

  • Slow callbacks are reported. Any callback or task step that holds the loop for longer than loop.slow_callback_duration (0.1 seconds by default) is logged, with the task that did it. A typical line looks like this:
TEXT
WARNING:asyncio:Executing <Task finished name='Task-2' coro=<fetch_report() done, defined at app.py:12> result=None created at app.py:30> took 0.204 seconds

That line is how you find the accidental requests.get() or the big json.loads. See running blocking code for the fixes.

  • Coroutines never awaited are reported with a traceback showing where the coroutine object was created.
  • Thread-safety checks. Calling loop.call_soon() or similar from another thread raises RuntimeError instead of corrupting state silently; use call_soon_threadsafe.
  • Unclosed transports and sockets log resource warnings, and task repr() includes where each was created.

The forgotten await

The most common asyncio bug is calling a coroutine function and forgetting await. The call returns a coroutine object that never runs:

Python A coroutine that was never awaited

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python itself warns RuntimeWarning: coroutine 'save' was never awaited when the unused coroutine object is garbage collected. In the lesson we captured it with warnings.catch_warnings; in your terminal it goes to stderr. Linters such as Ruff and Pyright, and type checkers, also flag this mistake before you run the code, so keep them switched on.

Tasks that fail in silence

When a task created with create_task() raises and nobody ever awaits it or reads task.exception(), the error is only reported when the task object is garbage collected, as Task exception was never retrieved. By then the context is gone and it might never print at all if the task is still referenced. Three habits fix this:

  1. Keep a reference to every background task (a set, or a TaskGroup), so tasks are not garbage collected mid-run.
  2. Await or gather them eventually, so exceptions reach your code.
  3. For fire-and-forget tasks, attach a done callback that logs failures.
Python Logging failures of background tasks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The add_done_callback pattern is the standard way to supervise fire-and-forget work. A TaskGroup is better when you can wait for the tasks, because it propagates errors for you.

Name and inspect your tasks

Give every task a meaningful name with create_task(coro, name="..."). Names appear in repr(), logs, debug output and tools. You can list what the loop is currently running with asyncio.all_tasks() and find yourself with asyncio.current_task():

Python Listing the tasks that are alive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a server seems stuck, dumping asyncio.all_tasks() and calling task.print_stack() on each shows exactly which await every task is waiting at. Python 3.14 adds python -m asyncio ps PID and python -m asyncio pstree PID to do this for a running process from the outside. The leaked-task check at the end of a test, assert not leaked, uses the same function (see testing async code).

Measuring event-loop lag yourself

You do not need debug mode to notice a blocked loop. A tiny lag monitor task asks the loop to wake it every 10 ms and measures how late each wake-up was. If something blocks the loop for 200 ms, the next wake-up is about 200 ms late. This technique works on any loop and is cheap enough to run in production, reporting to your metrics system.

Python A loop-lag monitor catches a blocking call

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In a real service, export the worst lag per minute as a metric and alert when it climbs. Lag is often the first visible symptom of a blocking call, a CPU spike or an overloaded process.

Other debugging tips

  • Use asyncio.run() as the single entry point, and set debug=True in development.
  • Reproduce with await asyncio.sleep(0) to force a context switch at a suspect location; many race conditions only appear when another task runs there.
  • Add timeouts everywhere (timeouts lesson): a hang turns into a TimeoutError with a traceback that shows where it was stuck.
  • Check ExceptionGroups. TaskGroup and gather can raise several errors at once; read all of eg.exceptions.
  • Log task names with every log line using asyncio.current_task().get_name() or a logging filter, and use context variables (contextvars) for request IDs.
  • Don't swallow CancelledError (cancelling tasks): a task that refuses to stop shows up as a hang at shutdown.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does asyncio debug mode report that is useful for finding accidental blocking calls?

    In debug mode the loop logs any step that runs longer than loop.slow_callback_duration (0.1 seconds by default), naming the task responsible.
  2. 2. You call "save(record)" on an async def function without await. What happens?

    Calling a coroutine function only creates a coroutine object. Nothing runs until it is awaited or wrapped in a task.
  3. 3. How can you make sure the failure of a fire-and-forget task is not lost?

    A strong reference keeps the task alive, and a done callback that retrieves the exception lets you log it.
  4. 4. What does a loop-lag monitor measure?

    If something blocks the loop, a timer fires late; the lateness is the lag, a good indicator of blocking code.

Summary

  • Enable debug mode (-X dev, PYTHONASYNCIODEBUG=1 or asyncio.run(debug=True)) during development to log slow callbacks and report un-awaited coroutines.
  • A missing await creates a coroutine that never runs; linters and warnings catch it.
  • Keep references to background tasks, attach done callbacks and give tasks names so failures are visible.
  • asyncio.all_tasks(), print_stack() and a loop-lag monitor show what is stuck or blocking.

Next: Testing async code