Database Tracing
Trace PostgreSQL queries from Python with psycopg, psycopg2, SQLAlchemy, and the Django ORM, and carry the trace into the database with SQLCommenter so pg_tracing adds server-side spans to the same trace.
Database tracing has two halves. The driver instrumentation records a client span for every query, which shows how long the application waited. SQLCommenter appends the W3C traceparent to each statement, which lets PostgreSQL's pg_tracing extension record what the database did during that wait, as spans in the same trace. The first half needs only an installed extra. The second is off by default and has to be turned on.
Choose the extras
| Stack | Install | Instrumentation that traces queries |
|---|---|---|
| psycopg 3 | sophonz-opentelemetry[psycopg] | psycopg |
| psycopg2 | sophonz-opentelemetry[psycopg2] | psycopg2 |
| SQLAlchemy on psycopg 3 | sophonz-opentelemetry[sqlalchemy,psycopg] | sqlalchemy or psycopg (pick one, see below) |
| Django ORM | sophonz-opentelemetry[django,psycopg] | psycopg |
Call init() before the driver is imported and before any connection, pool, or engine is created. Connections opened earlier are not instrumented.
Client spans
With the extra installed, every statement produces a CLIENT span under the span that was current when the query ran. The span is named after the SQL operation (SELECT) and carries the statement text as db.statement, with parameters as placeholders.
No configuration is needed. What the client span cannot show is where the time went inside PostgreSQL: planning, lock waits, the scan that read a million rows. That is what the comment and pg_tracing add.
Enable SQLCommenter
Pass enable_commenter to the instrumentation closest to the wire:
import os
from sophonz.opentelemetry import init
init(
service="checkout-api",
api_key=os.getenv("SOPHONZ_API_KEY"),
instrumentations={
"psycopg": {
"enable_commenter": True,
# keep only the trace context in the comment
"commenter_options": {
"db_driver": False,
"dbapi_threadsafety": False,
"dbapi_level": False,
"libpq_version": False,
"driver_paramstyle": False,
},
},
},
)PostgreSQL then receives:
SELECT id FROM users WHERE id = $1 /*traceparent='00-af36bce59ed899006154f6fdbe8f1155-a0fc80d07613b887-03'*/Without commenter_options, the driver tags are included as well:
SELECT id FROM users WHERE id = $1 /*db_driver='psycopg%3A3.3.5',dbapi_level='2.0',dbapi_threadsafety=2,driver_paramstyle='pyformat',libpq_version=180006,traceparent='00-fdcd384a08bf56936f73209d94c9bc47-a88d94702e452911-03'*/pg_tracing reads only traceparent. The Sophonz sample servers turn the other tags off, which keeps the comment short and the same for every driver version.
Options by layer
| Instrumentation | Enable | Tags you can turn off in commenter_options |
|---|---|---|
psycopg | enable_commenter | db_driver, dbapi_threadsafety, dbapi_level, libpq_version, driver_paramstyle, opentelemetry_values |
psycopg2 | enable_commenter | Same as psycopg |
sqlalchemy | enable_commenter | db_driver, db_framework, opentelemetry_values |
django | is_sql_commentor_enabled | Configured through Django settings |
flask | enable_commenter (on by default) | framework, controller, route |
opentelemetry_values is the traceparent itself. Leave it on.
The Flask row is different. The Flask instrumentation does not comment by itself; it adds framework, controller, and route tags to the comment written by the driver. Pass "flask": {"enable_commenter": False} to keep those out.
The environment variable shortcut
SOPHONZ_PYTHON_SQLCOMMENTER=true sets enable_commenter on psycopg and psycopg2, which is the way to turn it on under opentelemetry-instrument. It does not set commenter_options, so the driver tags are included. An instrumentations entry, or SOPHONZ_PYTHON_INSTRUMENTATIONS, overrides it:
export SOPHONZ_PYTHON_INSTRUMENTATIONS='{"psycopg": {"enable_commenter": true, "commenter_options": {"db_driver": false, "dbapi_threadsafety": false, "dbapi_level": false, "libpq_version": false, "driver_paramstyle": false}}}'Comment on one layer only
Each layer that has commenting enabled appends its own comment. Enable it on the driver for plain psycopg, psycopg2, and Django applications. For SQLAlchemy, enable it on either SQLAlchemy or the driver underneath, not both.
psycopg 3
A connection pool per process works with the instrumentation as is. Under gunicorn without --preload, the pool is created in each worker after init():
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
pool = ConnectionPool(
os.environ["DATABASE_URL"],
min_size=1,
max_size=5,
kwargs={"autocommit": True, "row_factory": dict_row},
open=False,
)
def list_users():
if pool.closed:
pool.open(wait=False)
with pool.connection() as conn:
return conn.execute("SELECT id, email, name FROM users ORDER BY id").fetchall()Statements in a transaction appear in order under the request span:
with pool.connection() as conn, conn.transaction():
for post in posts:
conn.execute(
"INSERT INTO posts (author_id, title, body) VALUES (%s, %s, %s)",
(author_id, post["title"], post["body"]),
)With AsyncConnectionPool, open the pool in the application lifespan and use async with pool.connection(). The trace context survives await and asyncio.gather, so concurrent queries are children of the request that started them. See the FastAPI guide.
psycopg2
init(
service="reports",
instrumentations={"psycopg2": {"enable_commenter": True}},
)
import psycopg2 # noqa: E402
conn = psycopg2.connect(os.environ["DATABASE_URL"])
with conn.cursor() as cur:
cur.execute("SELECT id FROM users WHERE id = %s", (1,))The instrumentation wraps psycopg2.connect. Import psycopg2 after init(), and do not import connect into your module namespace before it (from psycopg2 import connect), or the unwrapped function is kept.
SQLAlchemy
The sqlalchemy instrumentation wraps create_engine() and traces the engines it creates. Import create_engine after init(): a from sqlalchemy import create_engine that runs earlier keeps the unwrapped function, and its engines produce no query spans. The spans are named after the operation and database (SELECT app), with a connect span when a connection is opened.
init(
service="checkout-api",
instrumentations={
"sqlalchemy": {
"enable_commenter": True,
"commenter_options": {"db_driver": False, "db_framework": False},
},
"psycopg": {"enabled": False},
},
)
from sqlalchemy import create_engine, text # noqa: E402
engine = create_engine(os.environ["SQLALCHEMY_URL"]) # postgresql+psycopg://...
with engine.connect() as conn:
conn.execute(text("SELECT id FROM users WHERE id = :id"), {"id": 1})When both the sqlalchemy and psycopg instrumentations are loaded, each query produces two client spans, SELECT app from SQLAlchemy and SELECT from psycopg. Pick one layer: disable psycopg as above to keep SQLAlchemy's spans, or disable sqlalchemy and comment on the driver.
Django ORM
Django's django.db.backends.postgresql engine uses psycopg 3 when it is installed, so the psycopg instrumentation traces ORM queries and adds the comment.
# mysite/telemetry.py
init(
service="mysite",
instrumentations={
"psycopg": {
"enable_commenter": True,
"commenter_options": {
"db_driver": False,
"dbapi_threadsafety": False,
"dbapi_level": False,
"libpq_version": False,
"driver_paramstyle": False,
},
},
},
)# mysite/settings.py
import os
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "app",
"USER": "app",
"PASSWORD": os.environ["DB_PASSWORD"],
"HOST": "db",
"PORT": "5432",
"CONN_MAX_AGE": 60,
}
}Leave the Django instrumentation's is_sql_commentor_enabled off; with the driver already commenting, it would add a second comment. select_related, prefetch_related, and transaction.atomic() blocks show up as the individual statements Django sends.
In the database
The comment is only useful if PostgreSQL does something with it.
- Self-hosted PostgreSQL with
pg_tracingrecords server-side spans for each commented statement, as children of the query's client span. See Self-hosted PostgreSQL. - Managed PostgreSQL cannot load
pg_tracing. The comment still lands in the database log, which is what joins those logs to the trace. See Cloud-managed PostgreSQL.
pg_tracing traces only statements that arrive with a sampled traceparent. The SDK's default sampler, parentbased_always_on, samples every trace the browser or an upstream service sampled, and every trace that starts on the server. If you sample with OTEL_TRACES_SAMPLER, the database follows the same decision.
CAUTION — Prepared statements
The trace ID in the comment is different for every query, so the statement text never repeats. psycopg 3 prepares a statement on the server after it has run five times on a connection, and a text that never repeats is never prepared. For most web workloads this makes no difference. Where server-side preparation matters, set prepare_threshold=None on the connection to make the behavior explicit, or leave commenting off for that workload.
Verifying
- Run with
SOPHONZ_DEBUG_PAYLOAD=trueand send a request. The console shows aCLIENTspan per query withdb.statement, under the request's server span. - Turn on statement logging on a development database (
log_statement=all) and check that statements end with/*traceparent='00-...'*/. - On a
pg_tracingdatabase,SELECT * FROM pg_tracing_info();shows the span count increasing as requests arrive.
db.statement on the client span does not include the comment; only the statement sent to the server does.
Next steps
- Browser to Backend Tracing — start the trace in the browser.
- PostgreSQL instrumentation — what the database can report, by deployment.
TIP — This is just the beginning
Now ship your app. Sophonz surfaces the problems real users hit — so your app evolves on its own.