Database Monitoring Implementation Guide
By Nicolas Narbais
Connect request-level database spans with PostgreSQL health, pool behaviour, query evidence, and operational response.
Connect user-facing slowness to PostgreSQL internals in five progressive levels. Start with application client spans and PostgreSQL server metrics; add pool telemetry, query samples, and pg_stat_statements only when their diagnostic value justifies the database permissions and data-exposure policy.
| Level | Signal added | What it answers |
|---|---|---|
| 1 | Database client spans | Which service and request called PostgreSQL, duration, errors |
| 2 | PostgreSQL receiver server metrics | Connections, transactions, deadlocks, size, replication lag, locks |
| 3 | Connection-pool + infra metrics | Pool queueing vs DB work vs host/disk/network saturation |
| 4 | Query samples + blocking evidence (opt-in) | Active waits and blocking PIDs |
| 5 | pg_stat_statements top queries (opt-in) | Most expensive normalized query shapes across the workload |
Level 1 requires calling applications to already export traces. Collect compute and storage telemetry for the database’s host, cluster, or managed cloud provider before starting Level 3.
Before starting
- Scope: agree on the database, environment, calling services, database owner, and critical user workflow.
- Data policy: decide whether query text, role names, table names, and plans may leave PostgreSQL (literal masking still exposes schema structure).
- Least-privilege role: create a dedicated monitoring account; require DBA sign-off for every grant added in Levels 4 and 5.
- Collector health: run the receiver close to PostgreSQL and export Collector self-metrics/logs so an empty view is never ambiguous.
- Schema contract: standardize database name, technology, environment, and instance identity, and record whether the PostgreSQL receiver semantic-convention feature gate is enabled (changing it breaks existing dashboards).
Level 1 - Send database client spans
Instrument calling applications with OpenTelemetry SDKs or auto-instrumentation. Client spans populate Tsuga’s Services → Databases inventory with calling services, request rate, error rate, latency, and query breakdown where allowed.
Verify spans emit db.system.name (postgresql) and db.namespace (plus legacy db.name if older instrumentation requires it). Treat db.statement / db.query.text as an explicit data-classification decision, and never assume parameterization makes SQL harmless.
Validate one known request end to end: the trace shows a PostgreSQL client span, the database appears under Services → Databases for the target environment, and the database page lists the calling service.
Exit criteria: A known request emits a client span with verified db.system.name and db.namespace, the database appears in Tsuga’s Databases inventory, and the query-text policy is documented.
Level 2 - Collect PostgreSQL server health
Deploy the OpenTelemetry Collector Contrib postgresql receiver with a scoped monitoring role on a metrics pipeline. Start with connections, commits/rollbacks, deadlocks, database size, applicable replication lag, and locks; enable extra optional metrics one at a time while measuring scrape load.
receivers:
postgresql:
endpoint: "<POSTGRES_HOST>:5432"
username: ${env:POSTGRES_MONITORING_USER}
password: ${env:POSTGRES_MONITORING_PASSWORD}
databases: ["<DATABASE>"]
collection_interval: 30s
service:
pipelines:
metrics/postgresql:
receivers: [postgresql]
processors: [memory_limiter, batch]
exporters: [otlp_http/tsuga]
Pin the Collector version, test feature gates in staging, and confirm the database identity attribute expected by your Tsuga PostgreSQL panels (such as context.postgresql.database.name) before standardizing monitors.
Exit criteria: Connection, transaction, deadlock, size, and lock metrics arrive with the expected database identity, Collector version and feature-gate state are recorded, and scrape load is measured.
Level 3 - Add connection-pool and infrastructure context
Add pool metrics where supported so on-call can separate connection wait from query execution, and give every pool an explicit db.client.connection.pool.name.
Node.js pg example
Register PgInstrumentation and a metric reader before importing pg (PgInstrumentation emits db.client.connection.pending_requests and db.client.connection.count; set OTEL_SEMCONV_STABILITY_OPT_IN=database where supported and inspect live fields):
// instrumentation.cjs: load before app.cjs imports `pg`
const { NodeSDK } = require('@opentelemetry/sdk-node');
const { PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics');
const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-proto');
const { PgInstrumentation } = require('@opentelemetry/instrumentation-pg');
const sdk = new NodeSDK({
// Keep existing trace exporter and resource config here.
metricReader: new PeriodicExportingMetricReader({
exporter: new OTLPMetricExporter(),
}),
instrumentations: [new PgInstrumentation()],
});
sdk.start();
Pass connection fields explicitly to new Pool(...) so db.client.connection.pool.name does not collapse to unknown_host:unknown_port/unknown_database:
// app.cjs
require('./instrumentation.cjs');
const { Pool } = require('pg');
const pool = new Pool({
host: process.env.PGHOST,
port: Number(process.env.PGPORT || 5432),
database: process.env.PGDATABASE,
user: process.env.PGUSER,
password: process.env.PGPASSWORD,
max: 20,
});
Node ESM trap: Confirm query spans (not just pg-pool.connect spans) arrive. ESM apps require createRequire or the OpenTelemetry ESM loader hook so pg is patched before loading.
Match infrastructure telemetry to where PostgreSQL runs
Server metrics cannot detect a throttled EBS volume or saturated host NIC. Pair them with the matching infrastructure path:
- Kubernetes / self-hosted: node/cluster telemetry scoped to the database workload and node.
- Managed DB (RDS, Cloud SQL, Azure): provider CPU, storage, IOPS, connection-limit, network, and failover metrics.
- VM / bare metal: host CPU, memory, filesystem, disk I/O, and network metrics alongside the PostgreSQL receiver.
Exit criteria: Each pool reports a distinct db.client.connection.pool.name, pool wait is distinguishable from query time, and compute/storage telemetry is flowing for the database tier.
Level 4 - Opt in to query samples and blocking evidence
Enable pg_stat_activity query samples only after DBA approval of privileges, log volume, and data policy. Samples are point-in-time snapshots, so short queries and brief lock waits can slip between scrapes.
Development stability (v0.157.0+): PostgreSQL receiver logs remain in Development stability, so pin Collector versions and review upgrades. Confirm pg_monitor (or a tested narrower grant) with the DBA, enable the event, and attach postgresql to a logs pipeline:
receivers:
postgresql:
# Level 2 settings unchanged
events:
db.server.query_sample:
enabled: true
query_sample_collection:
max_rows_per_query: 20
service:
pipelines:
logs/postgresql-query-evidence:
receivers: [postgresql]
processors: [memory_limiter, batch]
exporters: [otlp_http/tsuga]
Three operational guardrails:
- Truncation: PostgreSQL truncates sampled text at
track_activity_query_size(default1024bytes); increase only if truncation blocks real investigations. - Exclude the observer: filter out the monitoring role’s own sessions so they do not dominate dashboards.
- Optional trace bridge: if writing W3C
traceparentintoapplication_name, clear it infinallybefore returning every pooled connection, because stale values misattribute later requests to the wrong trace.
Exit criteria: DBA signed off on grants and query-text policy, samples arrive as logs with agreed masking/retention, monitoring-role sessions are filtered out, and any trace bridge proves connection cleanup under pooling.
Level 5 - Add workload-level top-query evidence
Enable pg_stat_statements (requiring shared_preload_libraries + restart), create the extension in the receiver’s default connection database (postgres) (one installation covers the monitored cluster), and grant pg_read_all_stats so SQL text and queryid are visible to the monitoring role.
Set explicit caps so plan generation never overloads PostgreSQL (max_explain_each_interval is real database work):
receivers:
postgresql:
events:
db.server.top_query:
enabled: true
top_query_collection:
collection_interval: 60s
top_n_query: 100
max_rows_per_query: 100
max_explain_each_interval: 50
Validate output against a direct psql read as the monitoring role, and never run pg_stat_statements_reset() during incidents (compare two snapshots instead). Keep automated EXPLAIN plans gated behind an explicit operational need and scoped helper permissions.
Exit criteria: Top-query logs match direct pg_stat_statements reads as the monitoring role, collection/explain caps are explicit and measured under load, and runbooks forbid resetting shared stats.
Make it operational
Alert on customer-facing symptoms first (service error rate, latency, SLO burn), then use DBM to confirm or rule out PostgreSQL. For every production database, document:
- Dependent services and critical journeys.
- Named owners for app instrumentation, DB permissions, and infrastructure metrics.
- Query-data policy (retention, masking, read access).
- One triage view joining app symptoms, pool state, PostgreSQL health, and host/cloud storage.
- One validation drill: trace a known slow request → database span → server metrics → query evidence.
Troubleshooting path
Validate in order: client span → receiver metrics → optional query logs.
| Symptom | Check first | Action |
|---|---|---|
| Database missing from Tsuga | Client span db.system.name / db.namespace and env filter | Fix client instrumentation and trace export |
| No query breakdown on DB page | db.statement/db.query.text emission and data policy | Enable driver query text or keep intentionally hidden |
| Receiver metrics missing | Collector logs, DB reachability, grants, metrics pipeline | Fix the first failing boundary using Collector self-metrics |
| Query samples missing | Event flag, pg_monitor grant, logs pipeline | Enable event and wire postgresql into logs |
| Wrong trace on sampled query | Pool cleanup around application_name | Reset session context before pool release or disable bridge |
Top queries missing text/queryid | Extension in postgres DB and pg_read_all_stats grant | Install extension in postgres and verify as monitoring role |
Completion criterion and CLI validation
From a known slow request, an investigator opens its database client span in Tsuga, locates the same database in Services → Databases, and reads PostgreSQL health metrics for that exact window.
# Confirm calling services emit PostgreSQL client spans
tsuga traces search \
--query "context.service.name:<service> db.system.name:postgresql" \
--from -15m \
--to now \
--max-results 10
Verify spans carry the right database name and db.system.name:postgresql before troubleshooting the receiver. Validate Level 2 server metrics in Tsuga Metrics (prefix postgresql.) and Level 4/5 query events in Logs, since exact emitted names depend on Collector version and feature gates.
References
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.
