Skip to content

Find slow asyncio callbacks and measure scheduled work

Find code that keeps the asyncio event loop from running other tasks. The event loop is the scheduler that lets tasks take turns while they wait for things like network responses. You can also measure how long scheduled operations take and how often they get cancelled.

What you’ll capture

  • Warnings identify code that keeps other tasks waiting.
  • Metrics are numbers tracked over time. The integration counts operations and measures their durations at supported asyncio API calls, including in libraries that use those APIs. Metrics are recorded even when span capture is off.
  • Spans record individual operations with a name, start time, and duration. Enable them for selected coroutines, futures, or functions run with asyncio.to_thread().

The OpenTelemetry Python Contrib asyncio instrumentor produces these metrics and spans. It uses OpenTelemetry, the open standard for collecting traces, metrics, and logs.

Before you start

You’ll need a Logfire project. Open Add data in your project (top navigation) and follow the setup for your language: it signs your machine in with logfire auth (a browser sign-in, no token to copy) and, for production or other languages, creates a write token (the credential your app uses to send data). New to Logfire? Start with Getting Started.

Installation

Terminal
pip install 'logfire[asyncio]'

Usage

Find what blocks the event loop

Call logfire.instrument_asyncio() after configuring Logfire. This example produces one warning when the event loop is blocked and one duration measurement for a task.

main.py
import asyncio
import time

import logfire

logfire.configure()
logfire.instrument_asyncio()


async def do_work():
    # Deliberately block the event loop to trigger a warning.
    time.sleep(0.2)


async def main():
    await asyncio.create_task(do_work(), name='demo')


asyncio.run(main())

The default warning threshold is 0.1 seconds. Set slow_duration to change it.

What does a slow callback warning measure?

For a coroutine, Logfire times how long it runs before it pauses at an await that lets another task run, or before it finishes. When the coroutine resumes, a new timer starts. An await that completes immediately stays in the same timed stretch. Logfire calls each such stretch a callback. A function scheduled with loop.call_soon() is also a callback.

For example, time.sleep(0.2) keeps other tasks waiting for 200 milliseconds, so its time counts toward the warning. With await asyncio.sleep(0.2), the task pauses and other tasks can run during the wait.

The duration metric in this example comes from passing do_work() to create_task(). A direct await do_work() bypasses that hook and produces no separate asyncio metric or span.

If you already manage the OpenTelemetry asyncio instrumentor or only want these warnings, logfire.log_slow_async_callbacks() is available in the base Logfire package. Use one setup call per process to avoid duplicate warnings.

Verify

Find the warning

In the Live view, look for a warning like Async task demo (do_work) blocked for 0.200 seconds. Open the warning to see its duration and any available source location. For a task, the warning can include the task name and the chain of coroutines it was awaiting. Use the location to find the blocking call. If it is synchronous I/O, look for an async API or move the call to a worker thread with asyncio.to_thread().

Find the duration metric

Open the SQL Workbench in your Logfire project, select a time range that includes the run, and query the metrics table:

SELECT metric_name, attributes, ROUND(metric_avg(value), 2) AS reading
FROM metrics
WHERE otel_scope_name = 'opentelemetry.instrumentation.asyncio'
ORDER BY recorded_timestamp DESC
LIMIT 10

After one run in a fresh project, the result looks like this:

metric_nameattributesreading
asyncio.process.duration{"type": "coroutine", "name": "do_work", "state": "finished"}0.2

reading is the average duration in seconds within that data point, rounded to two decimal places.

What gets measured

The asyncio instrumentor wraps specific API calls. It measures the coroutine, future, or thread function passed into the call. When you pass an existing task to gather(), its telemetry comes from the call that created it, if that call was instrumented. A nested direct await contributes to the outer operation’s duration.

Code you callWork the integration can see
asyncio.create_task(coro), group.create_task(coro) on a TaskGroup, or asyncio.run_coroutine_threadsafe(coro, loop)A coroutine scheduled to run as a task
asyncio.gather(coro, ...), asyncio.wait_for(coro, timeout), or asyncio.as_completed([coro, ...])Coroutines passed to a helper that waits for asynchronous work
asyncio.ensure_future(future) or asyncio.wait([future, ...])A future that represents a result that will arrive later
asyncio.to_thread(func)A synchronous function run on a worker thread

Pass the operation as a positional argument as shown. Calls to the event loop’s loop.create_task() and loop.run_in_executor() directly bypass these hooks.

Query asyncio metrics

asyncio.process.duration is a histogram, or distribution, of elapsed time in seconds. Coroutine timing starts when the wrapper begins running and includes time spent awaiting. Future timing runs from when the instrumentor starts observing the future until its completion callback runs. For to_thread(), timing starts when the worker runs the function.

The metric has a type (coroutine, future, or to_thread) and a state (finished, cancelled, timeout, or exception). A named coroutine or thread function also has a name label. Coroutine names are bare function names, so functions with the same name can appear in the same group.

Generate sample metrics

Run this script in a test project to generate data for the query below. It completes three quick checks and two cache refreshes, then cancels one more refresh by giving it a shorter timeout than it needs to finish.

asyncio_metrics.py
import asyncio

import logfire

logfire.configure()
logfire.instrument_asyncio()


async def quick_check():
    await asyncio.sleep(0.01)


async def refresh_cache():
    await asyncio.sleep(0.04)


async def main():
    for _ in range(3):
        await asyncio.create_task(quick_check())
    for _ in range(2):
        await asyncio.create_task(refresh_cache())
    try:
        await asyncio.wait_for(refresh_cache(), timeout=0.01)
    except TimeoutError:
        pass


asyncio.run(main())

Compare coroutine durations and outcomes

Run this query in the SQL Workbench to see how many coroutines finished, were cancelled, or failed in each five-minute window, and how long they took on average.

SELECT
    time_bucket('5 minutes', recorded_timestamp) AS bucket,
    attributes->>'name' AS coroutine,
    attributes->>'state' AS state,
    SUM(metric_count(value)) AS observations,
    ROUND(SUM(metric_sum(value)) / NULLIF(SUM(metric_count(value)), 0), 2) AS mean_seconds
FROM metrics
WHERE metric_name = 'asyncio.process.duration'
  AND otel_scope_name = 'opentelemetry.instrumentation.asyncio'
  AND attributes->>'type' = 'coroutine'
GROUP BY bucket, attributes->>'name', attributes->>'state'
ORDER BY bucket, mean_seconds DESC, coroutine, state

If the sample falls within one five-minute bucket, expect rows like these. Mean durations are rounded to two decimal places.

bucket (example)coroutinestateobservationsmean_seconds
14:00refresh_cachefinished20.04
14:00quick_checkfinished30.01
14:00refresh_cachecancelled10.01

Here, wait_for() raises TimeoutError in the caller after cancelling the coroutine, so the coroutine’s metric records cancelled.

See Working with metrics for more ways to aggregate metric data.

Trace selected operations

To see how long a selected operation took, configure the asyncio integration to record a span when the operation goes through one of the APIs above. Each span shows the operation’s name and timing and can include exception details on failure. You can trace operations in library code without editing the functions that run them.

The integration places the asyncio span under the current span when one exists, and the coroutine keeps running in its original trace context. To trace a specific function you own, use @logfire.instrument. The decorator also works with direct await, can capture selected arguments, and makes spans created inside the function children of the decorator’s span.

Set the environment variables before calling logfire.instrument_asyncio(). The settings control spans. The metrics described above are available with the default settings.

Environment variableWhat it enables
OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACEA comma-separated list of bare coroutine function names, such as do_work,refresh_cache. A shared name selects every matching coroutine passed through a supported API.
OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLEDSet to true to trace futures observed by supported calls such as asyncio.ensure_future(future). Spans use the name asyncio future.
OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACEA comma-separated list of bare function names to trace when passed to asyncio.to_thread(), such as blocking_work.

This example uses all three settings. It passes a coroutine to wait_for(), makes a future that completes on the event loop, and runs a synchronous function in a worker thread.

trace_asyncio.py
import asyncio
import os
import time

import logfire

logfire.configure()
os.environ['OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE'] = 'do_work'
os.environ['OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED'] = 'true'
os.environ['OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE'] = 'blocking_work'
logfire.instrument_asyncio()


async def do_work():
    await asyncio.sleep(0.01)


async def call_future():
    loop = asyncio.get_running_loop()
    future = loop.create_future()
    loop.call_later(0.02, future.set_result, 'ready')
    assert await asyncio.ensure_future(future) == 'ready'


def blocking_work():
    time.sleep(0.03)


async def main():
    # This is traced by OTEL_PYTHON_ASYNCIO_COROUTINE_NAMES_TO_TRACE=do_work
    await asyncio.wait_for(do_work(), timeout=1)

    # This is traced by OTEL_PYTHON_ASYNCIO_FUTURE_TRACE_ENABLED=true
    await call_future()

    # This is traced by OTEL_PYTHON_ASYNCIO_TO_THREAD_FUNCTION_NAMES_TO_TRACE=blocking_work
    await asyncio.to_thread(blocking_work)


asyncio.run(main())

In the Live view, look for asyncio coro-do_work, asyncio future, and asyncio to_thread-blocking_work in that order.

Troubleshooting

  • The metrics query is empty. Check the project and time range in the SQL Workbench. If you adapted the example, check that your coroutine goes through asyncio.create_task() or another supported call. Metrics can arrive separately from spans and warnings.
  • There are metrics but the expected span is missing. Check the environment variable and the exact bare function name. Pass the coroutine through a supported API such as asyncio.create_task(). For a directly awaited function you control, use @logfire.instrument.
  • A second call has no effect. Asyncio instrumentation applies to the whole Python process. While it is active, another logfire.instrument_asyncio() call has no effect, even on a different instance from logfire.configure(local=True). The first installation determines the destination and reads the trace settings from the environment. To change either, restart the process with the desired configuration and a single instrumentation call.

Advanced

Enable the optional counter

The asyncio.process.duration histogram already counts each recorded operation, including cancelled and failed operations. Use SUM(metric_count(value)), as in the query above, to get those counts by operation type, name, or outcome.

If an existing dashboard or alert expects OpenTelemetry’s asyncio.process.created metric, use this startup code to export the separate counter and keep Logfire’s other default metric settings.

Configure Logfire to export the asyncio counter
from opentelemetry.sdk.metrics.view import SumAggregation, View

import logfire

logfire.configure(
    metrics=logfire.MetricsOptions(
        views=[
            *logfire.MetricsOptions.DEFAULT_VIEWS,
            View(
                meter_name='opentelemetry.instrumentation.asyncio',
                instrument_name='asyncio.process.created',
                aggregation=SumAggregation(),
            ),
        ],
    ),
)
logfire.instrument_asyncio()