Skip to content

Lesson 9 of 9 · 24m

Testing, Observability, and Debugging Async in Production

How to test time-dependent async code, instrument the loop, reproduce races, and read the signals that reveal blocking, starvation, and cancellation bugs.

You cannot operate async systems with print statements and hope. The important questions are invisible by default: Is the loop responsive? Which task has been waiting for eight seconds? Are we accumulating tasks? Did cancellation happen before or after the database commit? Production async needs tests that control time and telemetry that exposes scheduling health.

Test behavior, not wall-clock luck

pytest-asyncio lets tests drive coroutines directly:

import pytest
@pytest.mark.asyncio
async def test_fetch_timeout():
    with pytest.raises(TimeoutError):
        async with asyncio.timeout(0.01):
            await asyncio.sleep(1)

Avoid real sleeps longer than a few milliseconds. They make suites slow and flaky. Design code so clocks, delays, and retry policies are injectable:

async def retrying_fetch(fetch, *, sleep=asyncio.sleep):
    await sleep(backoff)

In tests pass a fake sleep that records delays without waiting. Testing random backoff with real randomness is self-inflicted pain; seed it or inject it.

Race reproduction requires controlled scheduling

A race hidden behind two network calls can often be reproduced with events:

started = asyncio.Event()
release = asyncio.Event()
async def fake_open():
    started.set()
    await release.wait()
    return FakeConnection()

Start two tasks, wait until both reach the dangerous point, then release them in the order that triggers the bug. This converts an intermittent production failure into a deterministic regression test.

Enable asyncio debug mode in development

PYTHONASYNCIODEBUG=1 python -m app

Debug mode detects never-awaited coroutines, tasks destroyed while pending, and slow callbacks. It is too expensive for many production deployments, but invaluable in development and CI. You can also set a slow callback duration explicitly:

loop.set_debug(True)
loop.slow_callback_duration = 0.1

A callback taking longer than the threshold gets logged. In production, approximate this with a heartbeat task measuring scheduling delay:

async def loop_heartbeat(metrics):
    while True:
        expected = loop.time() + 1
        await asyncio.sleep(1)
        metrics.gauge('event_loop_delay', max(0, loop.time() - expected))

If the delay jumps, something blocked the loop or the process was starved of CPU.

Instrument the lifecycle boundaries

Useful production metrics include active tasks, queue depth, oldest queued item age, connection pool in-use count, outbound request latency by dependency, cancellation count, and background-task restart count. Log structured cancellation events at boundaries:

except asyncio.CancelledError:
    logger.info('job cancelled', extra={'job_id': job_id, 'phase': phase})
    raise

Do not log every routine cancellation as an error. Client disconnects cancel perfectly healthy work. The important signal is cancellation in places where work was expected to complete.

Postmortem inspection

When a process is stuck, py-spy dump --pid <pid> is often the fastest safe first look at Python stacks. For in-process inspection, asyncio.all_tasks() plus task names and stack dumps can reveal thousands of tasks parked at the same queue or lock. Make sure that diagnostic endpoint is protected and bounded; dumping ten thousand full stack traces into a response is its own incident.

Field notes

  • In tests, assert cancellation cleanup: locks released, sessions closed, transactions rolled back; cancellation is behavior worth testing. Never use production PYTHONASYNCIODEBUG blindly — measure overhead first.
  • Task names should include stable categories, not unbounded user input — high-cardinality labels will hurt metrics systems.
  • If latency improves when traffic drops but error rates do not, you may be timing out clients while server-side work continues. Correlate cancellation with downstream load.

Was this lesson helpful?

Sign in to rate