A database receiver is not database observability: PostgreSQL with OpenTelemetry
BuildGuide7 min read

A database receiver is not database observability: PostgreSQL with OpenTelemetry

By Nicolas Narbais

The PostgreSQL receiver reports what the server is doing; your traces report what the request felt. Neither joins the other. A staged guide to server metrics, client spans and pool telemetry, with what each one cannot tell you.

Your PostgreSQL receiver is scraping and your application traces are arriving, yet you still cannot explain why checkout slowed down.

Nothing is broken. The receiver measures what PostgreSQL is doing; application spans measure what the caller felt. Neither connects to the other, and no exporter flag joins them automatically.

This first part covers the two stages every deployment needs: server metrics from the receiver and client spans plus pool telemetry from the application. Stopping here is enough for most services. Stages 3 and 4 (query samples, blocking evidence, and pg_stat_statements) require database privileges and export query text, so they live in part two.

Note

Pinned version: Examples and field captures below use OpenTelemetry Collector Contrib v0.158.0 (released 2026-08-04).

flowchart LR App["Application: client spans, pool metrics"] Recv["PostgreSQL receiver: scrapes, opt-in logs"] Infra["Infrastructure: host, storage, network path"] Diag["PostgreSQL diagnostics: statements, locks, plans"] Backend[("One backend, four unrelated views")] App -->|OTLP| Backend Recv -->|OTLP| Backend Infra -->|OTLP| Backend Diag -->|OTLP| Backend App -.->|"application_name = traceparent (you build this)"| Recv

Four producers land in one backend. The only join between them (the dashed line) does not exist until you build it.

Six reasons a PostgreSQL client span looks slow

When an incident trace shows a slow database span, the span alone cannot tell you which of six things happened, and whether pool wait or retries sit inside that duration depends on your driver instrumentation, not on PostgreSQL:

  • Pool exhaustion: requests queued waiting for a free connection.
  • Query regression: one query shape slowed down for everyone.
  • Lock contention: the statement waited behind another transaction.
  • Replica lag: reads hit a replica that fell behind.
  • Host or storage pressure: PostgreSQL is healthy, but disk IOPS, CPU, or memory is saturated.
  • Network or proxy trouble: the slowdown sits between the application and PostgreSQL.

Observability means connecting a user-visible symptom to the evidence that narrows these six hypotheses down to one.

Four independent producers and what each leaves blind

ProducerSourceWhat it answersWhat it misses alone
ApplicationClient instrumentation and pool metricsWhich request called PostgreSQL, duration, errors, pool queueingServer internals
PostgreSQL receiverServer stats views + opt-in logsServer/database load, deadlocks, opt-in query evidenceCalling application request
InfrastructureHost, container, proxy, or managed-DB telemetryCPU throttling, disk IOPS/latency, network pathQuery semantics and request causality
PostgreSQL diagnosticspg_stat_statements, lock views, EXPLAINExpensive query shapes, blocking PIDs, execution plansWhether continuous collection is safe

Do not skip the infrastructure row. The PostgreSQL receiver reads PostgreSQL’s own statistics views, so a database can look healthy inside those views while sitting on an EBS volume out of burst credits or behind a flaky proxy.

Stage 1: server health and a least-privilege role

Receiver metrics need zero application changes and add low overhead on small schemas. Watch collection cost on large databases: the receiver scrapes table/index views on an interval, and v0.158.0 runs lock collection across every configured database instead of only postgres.

Create a scoped monitoring role

The receiver README requires SELECT on pg_stat_database for baseline metrics. Start there instead of reflexively granting pg_monitor. PostgreSQL’s predefined-roles docs warn to grant predefined roles (pg_monitor, pg_read_all_stats, pg_read_all_settings, pg_stat_scan_tables) only where needed.

-- Baseline metrics only: one dedicated login role, no ownership
CREATE ROLE otel_monitor WITH LOGIN PASSWORD 'set-from-your-secret-store';

-- Per database listed in the receiver config
GRANT CONNECT ON DATABASE orders  TO otel_monitor;
GRANT CONNECT ON DATABASE billing TO otel_monitor;

-- Documented baseline grant
GRANT SELECT ON pg_stat_database TO otel_monitor;

Enabling opt-in metrics can require additional grants, so enable them one at a time and test as otel_monitor.

Track the receiver.postgresql.useOTelSemconv feature gate

The receiver is migrating to OpenTelemetry database semantic conventions behind the alpha receiver.postgresql.useOTelSemconv gate. Enabling it moves database, table, and index identity from resource attributes onto metric datapoints.

Attribute layerGate offGate on (v0.158.0)
Resource attributespostgresql.database.name, postgresql.table.name, postgresql.index.nameserver.address, server.port
Datapoint attributessource, type, operation, state (6 metrics)Above plus db.namespace (12 metrics), db.collection.name (7), postgresql.index.name (2)
Warning

Treat toggling this gate as a schema migration. It adds no new PostgreSQL visibility, changes postgresql.table.name to db.collection.name (while keeping postgresql.index.name on datapoints), and breaks dashboards or alerts querying the old attribute names.

Configure the receiver and wire the right pipeline

receivers:
  postgresql:
    endpoint: postgres.internal:5432
    transport: tcp
    username: otel_monitor          # scoped role
    password: ${env:PG_MONITOR_PASSWORD}
    databases: [orders, billing]    # restrict collection explicitly
    collection_interval: 60s        # start conservative; scrapes add DB load
    tls:
      insecure: false
      insecure_skip_verify: false   # receiver default is true; verify certs explicitly
      ca_file: /etc/otel/pg-ca.pem
    # metrics: enable opt-in metrics one at a time

Receiver health data is metrics; stage 3/4 query samples and top queries are logs. Wire the pipelines accordingly:

service:
  pipelines:
    metrics:
      receivers: [postgresql]
      # processors / exporters
    logs:
      receivers: [postgresql]      # required only when stage 3/4 events are enabled
      # processors / exporters
Warning

Silent drop warning: Stage 1 needs only the metrics pipeline. When you enable query events in stage 3, attach postgresql to logs too, otherwise the Collector gathers the events and quietly drops them.

Monitor the Collector’s own scrape health

An empty PostgreSQL dashboard can mean six different failures: missing SQL grant, failed scrape query, wrong database name, unsupported PostgreSQL version, exporter failure, or a genuinely idle database. Export Collector self-metrics and errors (see debugging a Collector pipeline locally) and watch otel_monitor activity inside PostgreSQL so you know both health and scrape load.

Five receiver metrics for your first dashboard

Alert on user-facing SLOs first, then use these five v0.158.0 signals (Development stability) to confirm or rule out PostgreSQL. Thresholds depend on your workload, so none are hardcoded here.

MetricRevealsAlert postureCaveat
postgresql.backends + postgresql.connection.maxConnection pressureWarn with latency/errors; page on SLO riskCounts autovacuum/parallel workers too; not exact client %
postgresql.deadlocks (opt-in)Concurrency failuresInvestigate any jump; page if requests failCounts deadlocks; does not name the lock cycle
postgresql.rollbacks vs postgresql.commitsFailed/aborted transaction shiftsAlert on sustained ratio drift from baselineMany apps roll back by design
postgresql.replication.data_delay or postgresql.wal.lag (opt-in)Replica staleness and RPO riskPage against freshness/RPO targetOnly on replicated topologies
postgresql.db_size + host disk free spaceStorage capacity runwayForecast and warn before disk fillsDB size is not volume free space

Deadlocks and replication lag are opt-in. Explicitly enable them before assuming silence means zero issues:

metrics:
  postgresql.deadlocks:
    enabled: true
  postgresql.replication.data_delay:
    enabled: true
  postgresql.wal.lag:
    enabled: true

Keep block reads, cache hits, temporary-file I/O, lock counts, and postgresql.query.execution.time as on-demand diagnostic signals rather than noisy alerts, since there is no universal healthy threshold for them.

Stage 2: client spans and connection-pool telemetry

Alerts fire on user impact, so investigations start from a client span, not a server metric.

Verify db.system.name, db.namespace, and stability versions

According to the database client semantic conventions, two attributes carry most grouping and correlation work:

  • db.system.name: database technology (postgresql), never your database name.
  • db.namespace: target database/schema. Conventions recommend {database}|{schema} (e.g., orders|public), though many drivers still emit only the database name.
  • Other high-value span fields: duration and status, server.address and server.port, error.type, db.operation.name (present even when summary is missing), and db.query.summary (low-cardinality query shape).

Which names you receive depends on your instrumentation version and OTEL_SEMCONV_STABILITY_OPT_IN=database. Same app, same env var, different package version:

@opentelemetry/instrumentation-pgEmitted pg.query attributes
0.47.1db.system, db.name, db.statement, db.user, db.connection_string, net.peer.name, net.peer.port
0.73.0db.system.name, db.namespace, db.query.text, server.address, server.port
Warning

Security and correlation checks: Older packages emit db.connection_string, which can leak passwords if unredacted. Never assume db.namespace formats match across drivers and receivers; inspect one real client span alongside one receiver record first (in testing, both Node instrumentation-pg 0.73.0 and the receiver emitted db.namespace = app).

Treat db.query.text as sensitive even when parameterized

OpenTelemetry distinguishes three cases:

  • Parameterized SQL (WHERE id = $1): safe to collect by default in spec, though table/column names remain visible and apps can still inline literals accidentally.
  • Non-parameterized SQL (WHERE email = 'alice@example.com'): contains PII; sanitize before exporting.
  • Query parameters (db.query.parameter.<key>): opt-in only because values carry PII or secrets.

Inspect actual emitted SQL in staging before shipping db.query.text to production backends.

Verify your language driver and ESM patching

Coverage depends on the language library. Python ships separate packages for psycopg and psycopg2, while Node uses instrumentation-pg.

Warning

Node ESM silent failure: Using a plain ESM import pg from 'pg' emitted pg-pool.connect spans and zero query spans, because instrumentation-pg patches CommonJS modules. Load pg via createRequire or register the OpenTelemetry ESM loader hook, then confirm query spans actually appear.

Add connection-pool metrics to separate queue time from query time

A 400 ms database span could mean a 400 ms query or 390 ms waiting for a free pool slot. OpenTelemetry defines db.client.connection.* metrics (Development stability) keyed by db.client.connection.pool.name, though driver support is still partial:

MetricQuestion it answersNode instrumentation-pg 0.73.0
db.client.connection.pending_requestsRequests queued for a connection right nowYes
db.client.connection.countActive occupancy (idle vs used)Yes
db.client.connection.wait_timeQueue wait histogram to compare with span latencyNo
db.client.connection.timeoutsPool wait timeoutsNo
.max, .idle.min, .idle.maxConfigured pool ceiling and idle boundsNo
.create_time, .use_timeSlow handshakes or connections held too longNo

Because wait_time is missing in instrumentation-pg 0.73.0, infer pool queueing from pending_requests > 0 coinciding with saturated count (used) and rising span latency.

Verify db.client.connection.pool.name when using multiple pools

With Node instrumentation-pg 0.73.0, relying on PGHOST, PGPORT, and PGDATABASE environment variables produced:

db.client.connection.pool.name = unknown_host:unknown_port/unknown_database

Passing those values explicitly to new Pool({ host, port, database, ... }) fixed it to postgres:5432/app. Without explicit values, multiple pools collide under one placeholder label.

Rollout order and your next check

  1. Deploy Stage 1 (receiver metrics): scoped otel_monitor role, explicit databases: list, verified TLS, 60s interval, documented useOTelSemconv state, and infrastructure telemetry alongside it.
  2. Deploy Stage 2 (client spans + pool metrics): pinned driver instrumentation, verified semantic-convention fields, verified ESM/patch loading, and explicit pool.name.

Server metrics, client spans, pool telemetry, and infrastructure context settle four of the six opening hypotheses. Open one recent trace with a slow PostgreSQL span this week and check whether you can separate pool wait, host/storage pressure, and network latency. If the remaining gap is which query shape or which transaction blocked it, continue to part two: query-level PostgreSQL evidence.

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.

Scroll to zoom · Drag to pan · Double-click to reset