{"id":2153,"library":"opentelemetry-instrumentation-asyncpg","title":"OpenTelemetry AsyncPG Instrumentation","description":"This library provides OpenTelemetry tracing instrumentation for the `asyncpg` PostgreSQL driver. It allows for automatic capturing of database queries as spans, providing visibility into asynchronous PostgreSQL operations within an OpenTelemetry-instrumented Python application. As part of the `opentelemetry-python-contrib` repository, it often receives frequent beta releases.","status":"active","version":"0.62b0","language":"en","source_language":"en","source_url":"https://github.com/open-telemetry/opentelemetry-python-contrib","tags":["opentelemetry","tracing","async","asyncpg","postgresql","database","instrumentation"],"install":[{"cmd":"pip install opentelemetry-instrumentation-asyncpg","lang":"bash","label":"Install library"},{"cmd":"pip install asyncpg opentelemetry-sdk opentelemetry-exporter-console","lang":"bash","label":"Install core dependencies for quickstart"}],"dependencies":[{"reason":"The PostgreSQL driver that this library instruments. Required for the instrumentation to function.","package":"asyncpg","optional":false},{"reason":"Core OpenTelemetry API for defining tracing and metrics interfaces.","package":"opentelemetry-api","optional":false},{"reason":"Core OpenTelemetry SDK for implementing the API, including `TracerProvider` and `SpanProcessor`.","package":"opentelemetry-sdk","optional":false},{"reason":"Provides base classes and utilities for OpenTelemetry instrumentations.","package":"opentelemetry-instrumentation","optional":false},{"reason":"Defines standard attribute names for OpenTelemetry telemetry.","package":"opentelemetry-semantic-conventions","optional":false}],"imports":[{"symbol":"AsyncPGInstrumentor","correct":"from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor"}],"quickstart":{"code":"import asyncio\nimport os\n\nimport asyncpg\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.resources import Resource\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import ConsoleSpanExporter, BatchSpanProcessor\nfrom opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor\n\n# 1. Setup OpenTelemetry TracerProvider\nresource = Resource.create({\"service.name\": \"asyncpg-app\"})\ntracer_provider = TracerProvider(resource=resource)\nspan_processor = BatchSpanProcessor(ConsoleSpanExporter())\ntracer_provider.add_span_processor(span_processor)\ntrace.set_tracer_provider(tracer_provider)\n\n# 2. Instrument asyncpg\nAsyncPGInstrumentor().instrument()\n\nasync def main():\n    # Database connection details from environment variables or defaults\n    user = os.environ.get('POSTGRES_USER', 'user')\n    password = os.environ.get('POSTGRES_PASSWORD', 'password')\n    database = os.environ.get('POSTGRES_DB', 'database')\n    host = os.environ.get('POSTGRES_HOST', 'localhost')\n    port = os.environ.get('POSTGRES_PORT', '5432')\n\n    # Ensure asyncpg is available before attempting connection\n    try:\n        conn = await asyncpg.connect(\n            user=user, password=password, database=database, host=host, port=port\n        )\n        print(f\"Connected to PostgreSQL at {host}:{port}/{database}\")\n\n        # Perform a database operation that will be traced\n        result = await conn.fetchval(\"SELECT 42 as my_value;\")\n        print(f\"Query result: {result}\")\n\n        await conn.close()\n        print(\"Connection closed.\")\n\n    except Exception as e:\n        print(f\"Failed to connect or query PostgreSQL: {e}\")\n        print(\"Ensure a PostgreSQL instance is running and accessible (e.g., via Docker):\")\n        print(\"docker run -e POSTGRES_USER=user -e POSTGRES_PASSWORD=password -e POSTGRES_DB=database -p 5432:5432 postgres\")\n\nif __name__ == \"__main__\":\n    # Run the asynchronous main function\n    asyncio.run(main())\n\n# Optional: Flush spans before exiting for console exporter\n# For real applications, use a proper exporter like OTLPSpanExporter\n# and ensure processes have time to send data.","lang":"python","description":"This quickstart demonstrates how to set up OpenTelemetry to trace `asyncpg` database operations. It initializes a `TracerProvider` with a `ConsoleSpanExporter` to print traces to the console, then instruments the `asyncpg` library. An asynchronous function connects to a PostgreSQL database (using environment variables for credentials) and executes a simple query, generating a trace automatically. A running PostgreSQL instance is required, which can be easily started with Docker."},"warnings":[{"fix":"Review release notes and official documentation for any breaking changes when upgrading to newer beta versions.","message":"This instrumentation is currently in beta. While generally stable, its API and behavior might undergo minor changes in future pre-releases before reaching a stable (1.0) version.","severity":"gotcha","affected_versions":"All versions up to 0.62b0"},{"fix":"Avoid instrumenting `CursorIterator.__anext__` if possible, or consider alternative fetching methods (`fetch`, `fetchrow`, `fetchmany`) if fine-grained row-by-row tracing is not strictly required. Monitor trace sizes and adjust if performance issues arise.","message":"Iterating over `asyncpg.Cursor` can generate an excessive number of spans, with one span per row fetched via `CursorIterator.__anext__`. This can lead to very large traces and potential performance overhead.","severity":"breaking","affected_versions":"All versions up to 0.62b0 (addressed in issue #3109 as of late 2024; future versions might offer an opt-out)."},{"fix":"Ensure `AsyncPGInstrumentor().instrument()` is called as part of your application's OpenTelemetry initialization routine, typically before your application's main loop or database connection setup begins.","message":"The `AsyncPGInstrumentor().instrument()` call must occur early in your application's lifecycle, specifically before any `asyncpg` connections are established or its modules are significantly used. If `asyncpg` functions are called before instrumentation, those calls will not be traced.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Ensure your project's Python interpreter is version 3.9 or newer. Upgrade your Python environment if necessary.","message":"The `opentelemetry-instrumentation-asyncpg` library requires Python 3.9 or higher. Attempting to use it with older Python versions will result in compatibility errors.","severity":"gotcha","affected_versions":"<=0.62b0"}],"env_vars":null,"last_verified":"2026-04-09T00:00:00.000Z","next_check":"2026-07-08T00:00:00.000Z"}