
Query-level PostgreSQL evidence with OpenTelemetry: a privilege decision, not a config flag
By Nicolas Narbais
Query samples, blocking evidence and pg_stat_statements are not config flags. Each one buys diagnostic power for a privilege, for query text leaving the database, or for work the receiver makes PostgreSQL do. What each costs, measured.
Stages 1 and 2 of part one put server health next to client spans, but neither can name the query shape consuming the server or prove that a statement stalled behind a lock.
The PostgreSQL receiver can collect both, at the cost of higher database privileges, query text leaving PostgreSQL, and extra query work on the server. Treat each capability below as a governance decision, not a toggle.
| Capability | Question it answers | Required privilege / change | Main cost |
|---|---|---|---|
| Stage 3: Query samples + locks | What was this backend waiting on, and who blocked it? | pg_monitor + logs pipeline | Log volume + query structure exported |
| Stage 3 (optional): Trace bridge | Which exact app trace held this PostgreSQL session? | Custom app code setting application_name | Loses human application_name; leak risk if reset fails |
Stage 4: Top queries (pg_stat_statements) | Which query shape costs the most total DB time? | Server restart (shared_preload_libraries) + pg_read_all_stats | Cross-user SQL text exported + EXPLAIN DB load |
Pinned versions: Verified on OpenTelemetry Collector Contrib v0.158.0 (released 2026-08-04) against PostgreSQL 16.4.
Stage 3: query samples and blocking evidence
The receiver emits query samples from pg_stat_activity as logs: point-in-time snapshots of whatever backend was active or idle at scrape time. Here is a real unedited sample from the sandbox:
db.system.name = postgresql
db.namespace = app
db.query.text = SELECT id, customer, status, amount FROM orders WHERE id = ?
user.name = app
postgresql.state = idle
postgresql.pid = 417
postgresql.application_name =
network.peer.address = 172.20.0.3/32
network.peer.port = 45422
postgresql.client_hostname =
postgresql.query_start = 2026-08-11 06:28:00.739932+00
postgresql.wait_event = ClientRead
postgresql.wait_event_type = Client
postgresql.query_id =
postgresql.total_exec_time = 0.022
Four facts jump out immediately:
- Literals are masked, schema is not:
WHERE id = 1arrives asWHERE id = ?, while table and column names remain visible. - Samples are snapshots, not a complete log: a 5 ms query running between scrapes is never seen, and even slow queries are sampled probabilistically rather than guaranteed.
- Most samples are noise: fast,
idlebackends waiting inClientReaddominate raw output. postgresql.query_idis empty unlesspg_stat_statementsorcompute_query_idpopulates it, leaving no sideways join to Stage 4.
Enable query samples with explicit row caps
The v0.158.0 receiver docs specify pg_monitor for query sampling (test any narrower grant against your PostgreSQL version before relying on it). Enable the event and wire postgresql into the logs pipeline:
receivers:
postgresql:
# ... stage 1 settings unchanged
events:
db.server.query_sample:
enabled: true # off by default
query_sample_collection:
max_rows_per_query: 100 # default 1000 per collection
Cap max_rows_per_query before enabling. The default 1000 rows every 10s can emit up to 6,000 log records per minute per database. Also remember PostgreSQL truncates pg_stat_activity.query at track_activity_query_size (default 1024 bytes; raising it requires a restart and exports more query text).
Read blocking and lock fields together
Since v0.156.0, query samples include lock-wait fields (wait start requires PostgreSQL 14+). Here is a captured row-lock wait on orders:
| Attribute | Meaning | Captured row-lock value |
|---|---|---|
postgresql.blocking.pids | Blocking backend PIDs (PostgreSQL array syntax, not JSON) | {713} |
postgresql.blocking.wait_duration | Seconds waiting on the lock | 5 (up to 25 in later scrape) |
postgresql.blocking.start_time | Lock wait start timestamp | 2026-08-11T06:30:24Z |
postgresql.blocking.lock.mode / .type | Requested lock mode and object type | ShareLock, transactionid |
postgresql.blocking.lock.relation | Locked relation (empty on transactionid row waits) | (empty) |
postgresql.blocking.transaction.start_time | Blocked transaction start | 2026-08-11T06:30:24Z |
db.system.name = postgresql
db.namespace = app
db.query.text = UPDATE orders SET status = ? WHERE id = ?
user.name = app
postgresql.state = active
postgresql.pid = 727
postgresql.wait_event = transactionid
postgresql.wait_event_type = Lock
postgresql.total_exec_time = 4788.563
postgresql.blocking.pids = {713}
postgresql.blocking.wait_duration = 5
postgresql.blocking.start_time = 2026-08-11T06:30:24Z
postgresql.blocking.lock.mode = ShareLock
postgresql.blocking.lock.type = transactionid
postgresql.blocking.lock.relation =
postgresql.blocking.transaction.start_time = 2026-08-11T06:30:24Z
PID 727 reports state = active with 4.8s execution time, yet wait_event_type = Lock (transactionid) and blocking.pids = {713} prove it spent that time waiting on PID 713 rather than doing query work. Because row-lock waits target a transaction ID, lock.relation is empty, so db.query.text supplies the table name (orders).
Two mandatory filters for query-sample dashboards:
- Filter by non-empty value, not key existence: blocking attributes appear on every sample (empty when unblocked). Filter with
postgresql.blocking.pids != '{}'(orpostgresql.blocking.pids:*in Tsuga), and parse PostgreSQL{713,721}array syntax rather than JSON. - Exclude the monitoring role: on the sandbox (two receivers scraping every 10s + one app), 85 of 95 samples came from the monitoring role watching itself. Filter out
user.name = otel_monitorbefore building views.
Optional: correlate a query sample with an application trace
Query samples already answer “slow vs blocked” without trace correlation. Add the application_name bridge only if real incidents require naming the exact HTTP request that held a PostgreSQL session.
If a connection’s application_name contains a valid 55-character W3C traceparent (which fits inside PostgreSQL’s 63-byte limit), the receiver extracts traceId and spanId onto the query-sample log record:
Captured sandbox output with the bridge active:
traceId = 7a54b0006244f5fa047ef6384e28ac50
spanId = 9f115c95e55c806b
db.system.name = postgresql
db.namespace = app
db.query.text = SELECT pg_sleep ( ? )
postgresql.pid = 809
postgresql.application_name = 00-7a54b0006244f5fa047ef6384e28ac50-9f115c95e55c806b-01
postgresql.wait_event = PgSleep
postgresql.wait_event_type = Timeout
postgresql.total_exec_time = 40.5
Node: set application_name on the borrowed client
Set and reset the value on the borrowed client, never on the shared Pool:
import { context, trace } from '@opentelemetry/api';
import pg from 'pg';
const { Pool } = pg;
const pool = new Pool();
function currentTraceparent() {
const span = trace.getSpan(context.active());
if (!span) return null;
const ctx = span.spanContext();
if (!ctx.traceId || !ctx.spanId) return null;
const flags = (ctx.traceFlags & 0xff).toString(16).padStart(2, '0');
return `00-${ctx.traceId}-${ctx.spanId}-${flags}`;
}
async function queryWithTrace(sql, params = []) {
const client = await pool.connect();
const traceparent = currentTraceparent();
try {
if (traceparent) {
await client.query(`SELECT set_config('application_name', $1, false)`, [traceparent]);
}
return await client.query(sql, params);
} finally {
try {
await client.query('RESET application_name');
} finally {
client.release();
}
}
}
Python: the same ownership boundary with Psycopg 3
Keep try/finally around the entire period the request owns the physical connection, and never move the reset into unrelated middleware:
from opentelemetry import trace
def current_traceparent():
span = trace.get_current_span()
ctx = span.get_span_context()
if not ctx.is_valid:
return None
return f"00-{ctx.trace_id:032x}-{ctx.span_id:016x}-{int(ctx.trace_flags):02x}"
def query_with_trace(pool, sql, params=None):
with pool.connection() as conn:
traceparent = current_traceparent()
try:
if traceparent:
conn.execute(
"SELECT set_config('application_name', %s, false)",
(traceparent,),
)
return conn.execute(sql, params or ()).fetchall()
finally:
conn.execute("RESET application_name")
Why pool cleanup and aborted transactions make this risky
If an explicit transaction fails, PostgreSQL enters an aborted transaction state and rejects RESET application_name until ROLLBACK runs. Always run ROLLBACK in catch before running RESET application_name in finally.
When I skipped the reset in the sandbox and sent six unrelated requests through the pool, PID 869 kept an earlier request’s traceparent while executing someone else’s query:
pid | state | application_name | last_query
-----+-------+---------------------------------------------------------+---------------------
869 | idle | 00-509e98b0953fcb9a2e5c55d78f13f268-004a495208fe1def-01 | SELECT id, customer…
877 | idle | (empty) | SELECT id, customer…
Wrong correlation is worse than none: Missing trace links are an obvious gap; leaked application_name links look authoritative while pointing at the wrong trace. You also give up human-readable application_name values (orders-api, billing-worker) while the traceparent is installed. Start without this bridge.
Stage 4: workload-level top queries and execution plans
Stage 4 shifts from one request to the whole database workload using pg_stat_statements, answering four questions spans cannot: which normalized query shape consumes the most total time, whether it got slower or just ran more often, whether your slow span was the cause or a bystander, and whether a fix actually lowered DB load.
Query analysis works at three depths:
- Top queries (
pg_stat_statements): total time, call count, and rows per normalized shape, with no plans run. - Receiver-generated plans: automated
EXPLAINcapped bytop_n_queryandmax_explain_each_interval(never runsEXPLAIN ANALYZE). - Manual plans: operator-run
EXPLAINorEXPLAIN ANALYZEduring an investigation.
Production EXPLAIN ANALYZE warning: EXPLAIN estimates a plan, while EXPLAIN ANALYZE executes the statement for real, running slow queries and modifying data on writes unless wrapped in BEGIN; ... ROLLBACK;.
Load pg_stat_statements and create the extension in postgres
Loading pg_stat_statements via shared_preload_libraries requires a PostgreSQL restart:
# postgresql.conf (defaults in comments)
shared_preload_libraries = 'pg_stat_statements'
pg_stat_statements.max = 10000 # default 5000 shapes kept
pg_stat_statements.track = top # default top ('all' includes nested functions)
pg_stat_statements.track_utility = off # default on; off drops VACUUM/SET/DDL
track_io_timing = on # default off; measure block-timing overhead
compute_query_id = auto # default auto; enabled automatically by module
Create the extension in the database the receiver connects to (postgres by default), not only in the application databases listed under databases:. Verified on Collector v0.158.0 + PostgreSQL 16.4: creating it only in the application database caused top-query collection to fail, while creating it in postgres worked.
-- Run in `postgres` (the receiver's connection database)
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
Grant pg_read_all_stats and verify identity is not stripped
Without pg_read_all_stats, PostgreSQL still returns rows from pg_stat_statements, with every other user’s SQL text and queryid silently stripped out.
GRANT pg_read_all_stats TO otel_monitor;
Verify both the extension and the grant in one query as otel_monitor:
psql "host=postgres.internal user=otel_monitor dbname=postgres" -Atc \
"SELECT count(*), count(queryid) FROM pg_stat_statements" \
|| echo "extension missing, fix before rollout"
On the sandbox, this returned 156 and 0 without the grant, and 157 and 157 with it.
Set explicit receiver caps
receivers:
postgresql:
# ... stage 1 settings unchanged
databases: [orders, billing]
events:
db.server.query_sample:
enabled: true
db.server.top_query:
enabled: true # off by default
top_query_collection:
collection_interval: 60s # independent of metric scraping
top_n_query: 100 # default 200
max_rows_per_query: 100 # default 1000
max_explain_each_interval: 50 # default 1000, DB plan-generation budget
query_plan_cache_size: 1000
query_plan_cache_ttl: 1h
Normalized does not mean sanitized: pg_read_all_stats lets other teams’ SQL text leave PostgreSQL and reach your telemetry backend. Decide access and retention upfront, and pair it with downstream redaction (such as Tsuga’s Sensitive Data Scanner) as defense in depth. Also note postgresql.queryid is not guaranteed stable across major PostgreSQL upgrades.
Treat custom SQL receivers as a separate layer
The native receiver deliberately omits table bloat, maintenance age, active vacuums, idle-in-transaction counts, and WAL/replication-slot inventories. Tsuga’s Helm example adds them via otel.* SQL functions and sqlquery receivers (locks/connections at 30s, vacuum/WAL at 60s, maintenance at 5m, bloat at 1h, capped at 50 table rows / 20 bloat / 20 shapes).
That is custom SQL running permanently against your database. Measure its load and scope its pg_monitor / EXECUTE grants explicitly. The sqlquery receiver never bypasses privilege or load governance.
Three operator psql queries during an incident
1. Which query shape costs the most total time? (Rank by total time, not mean; on PostgreSQL 12 and earlier use total_time.)
SELECT queryid,
calls,
round(total_exec_time::numeric, 1) AS total_ms,
round(mean_exec_time::numeric, 2) AS mean_ms,
rows,
left(query, 100) AS shape
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT 10;
Sandbox output mid-load proves why total time wins:
queryid | calls | total_ms | mean_ms | rows | shape
----------------------+-------+----------+---------+------+------------------------------
-6257661822689736760 | 501 | 65896.4 | 131.53 | 5010 | SELECT o1.customer, count(*)…
-4221548598437380883 | 1352 | 42.5 | 0.03 | 1352 | SELECT id, customer, status,…
2. Did it get slower or just run more often? Diff two snapshots a few minutes apart per queryid. Never call SELECT pg_stat_statements_reset(); during an incident because it wipes baselines for every collector and operator (if you ever must clear one shape, use pg_stat_statements_reset(userid, dbid, queryid)).
3. Why is this shape slow? On PostgreSQL 16+, plan normalized $1 placeholders directly with GENERIC_PLAN (estimated plan only; cannot combine with ANALYZE):
EXPLAIN (GENERIC_PLAN, FORMAT JSON)
SELECT * FROM orders WHERE customer_id = $1 AND status = $2;
On writes with EXPLAIN ANALYZE, always wrap in a rollback:
BEGIN;
EXPLAIN ANALYZE UPDATE orders SET status = 'shipped' WHERE id = 12345;
ROLLBACK;
If operators or tooling need EXPLAIN without broad table SELECT, isolate a SECURITY DEFINER helper in its own schema so unauthorized callers fail at the schema boundary first:
CREATE SCHEMA IF NOT EXISTS otel_diag;
CREATE OR REPLACE FUNCTION otel_diag.explain_statement(l_query text, OUT explain json)
RETURNS SETOF json AS $$
DECLARE
curs REFCURSOR;
plan json;
BEGIN
SET TRANSACTION READ ONLY;
OPEN curs FOR EXECUTE pg_catalog.concat('EXPLAIN (FORMAT JSON) ', l_query);
FETCH curs INTO plan;
CLOSE curs;
RETURN QUERY SELECT plan;
END;
$$ LANGUAGE plpgsql RETURNS NULL ON NULL INPUT SECURITY DEFINER;
-- Revoke default PUBLIC execute and scope to otel_monitor
REVOKE EXECUTE ON FUNCTION otel_diag.explain_statement(text) FROM PUBLIC;
GRANT USAGE ON SCHEMA otel_diag TO otel_monitor;
GRANT EXECUTE ON FUNCTION otel_diag.explain_statement(text) TO otel_monitor;
Information-exposure tradeoff: SECURITY DEFINER plans queries with the function owner’s permissions. Skip this function and keep EXPLAIN manual if the monitoring role must not inspect plans across those tables.
Six agreements to settle with the database owner before Stage 4
- Grants: exact roles added, target clusters, and approver.
- Query text: whether normalized SQL and schema names may leave PostgreSQL and who can read them.
- Destination and retention: where logs land and how long they stay.
- Limits: explicit
top_n_query,max_rows_per_query,max_explain_each_interval, and cache TTL values. - Load: measured on a representative workload, not an idle box.
- Off switch: named owner and tested rollback.
Safe rollout order (Stages 3–4)
After completing Stages 1 and 2 from part one, stop at whichever step answers your active incident gaps:
- Query samples for lock and wait evidence, usually the highest-value first trade.
- Trace correlation bridge only when incidents demand request-to-session attribution and pool cleanup is tested.
- Top queries one database at a time after the six DBA agreements, restart, extension, grant check, and explicit limits are complete.
- Manual
EXPLAINinside incident runbooks.
Take the six agreements above to your database owner before flipping a single event flag. Query samples tell you what a backend waited on, and top queries tell you which shape costs the most.
Written by
Nicolas Narbais
Nicolas Narbais builds, breaks, debugs, and scales observability systems using OpenTelemetry and modern telemetry pipelines. He shares practical, opinionated lessons to help engineers get better signal with less noise.
Olatuak Editorial Philosophy
Better signal, not more telemetry.
Olatuak helps platform engineers, SREs, and observability teams turn noisy telemetry into clear operational decisions without blindly collecting more data.
