Skip to content

Database Observability ​

"The pg_stat_statements module provides a means for tracking planning and execution statistics of all SQL statements executed by a server." — PostgreSQL 19 Documentation, F.34. pg_stat_statements

Summary: Database observability is three signals (metrics, logs, traces) read from two sides (the server's own statistics and the application's view), joined by a few labels so one slow request leads to one query and one wait. Focus: PostgreSQL statistics views, log settings, auto_explain, exporters and alerts; MySQL performance_schema, sys and the slow log; OpenTelemetry database spans; Go DBStats and Laravel DB::listen. Learning goal: Find the costliest query, the blocker of a stuck session and the cause of a saturated server in minutes, and decide which numbers deserve an alert.

This page is the complete reference for watching a relational database in production: the four golden signals applied to a database, every PostgreSQL statistics view a practitioner reads (pg_stat_statements, pg_stat_activity, pg_stat_user_tables, pg_stat_io, pg_stat_replication, pg_locks), the log parameters and tools (log_min_duration_statement, auto_explain, pgBadger), the extensions (pg_stat_kcache, pg_wait_sampling), the exporter and dashboard layer, the MySQL equivalents, OpenTelemetry database spans and query sanitization, application-side hooks in Go and Laravel, alert rules, and correlation of application traces with database waits. Lock modes are taught in Locks & Concurrency, vacuum in MVCC, VACUUM & Bloat, plans in Query Planning, EXPLAIN & Join Algorithms, replication in Replication, Read Replicas & Failover, and the pool in Connection Pooling. Here we only show how to see them.

Page map ​

If you are looking forGo to
The numbers to memoriseEverything in one minute
Why a database needs its own observabilityWhy database observability exists
Golden signals, USE and RED mapped to a databaseThe four golden signals
Which query costs the mostpg_stat_statements
What is happening right now, who waits for whatpg_stat_activity and wait events, pg_locks
Tables, indexes, vacuum, I/O, checkpoints, replicationTable and index statistics, pg_stat_io and checkpoints, Replication lag
Cache hit ratio and why it misleadsCache hit ratio
Logs, auto_explain, pgBadgerLogs and auto_explain
Kcache, wait sampling, pg_stat_monitor, vendor toolsExtensions and vendor tools
Exporter, Prometheus, GrafanaMetrics pipeline
MySQL, SQL Server, Oracle, MongoDB, Redis equivalentsPer-engine observability, MySQL in detail
OpenTelemetry spans, sanitizationTraces and semantic conventions
Go and Laravel hooksApplication side
Alert rules and the decision treeAlerting
Joining a trace to a database waitCorrelation
Reproduce it on a laptopLab

Everything in one minute ​

The questions and the tool that answers each.

QuestionPostgreSQLMySQLGo / Laravel side
Which statements cost the most in total?pg_stat_statements ordered by total_exec_timeevents_statements_summary_by_digest, sys.statement_analysisOTel span histograms per operation
What is running right now?pg_stat_activityperformance_schema.threads, SHOW PROCESSLISTDBStats.InUse
Who blocks whom?pg_locks + pg_blocking_pids()performance_schema.data_lock_waits, sys.innodb_lock_waitslock-wait errors in logs
Is the cache working?pg_stat_database blks_hit/blks_read, pg_stat_ioInnodb_buffer_pool_reads vs _read_requestsnone
Is vacuum keeping up?n_dead_tup, last_autovacuum, age(datfrozenxid)history list lengthnone
Is the replica behind?pg_stat_replication.replay_lagSeconds_Behind_Source (replica status)read-your-writes errors
What did the slow one do?auto_explain, EXPLAIN (ANALYZE, BUFFERS)slow log + EXPLAIN ANALYZEspan with db.query.text
Is the pool the bottleneck?connections in pg_stat_activityThreads_connectedDBStats.WaitCount, WaitDuration

The files and settings.

Setting or objectDefaultWhat it does
shared_preload_libraries = 'pg_stat_statements'not loadedNeeds a restart; allocates shared memory
compute_query_idautoComputes queryid, which pg_stat_statements needs
pg_stat_statements.max5000Number of distinct statements tracked
track_io_timingoffRecords read and write time per block; small cost on modern hardware
log_min_duration_statement-1 (off)Logs statements slower than the threshold
log_lock_waitsoffLogs a wait longer than deadlock_timeout (1 s default)
log_checkpointson since PostgreSQL 15One line per checkpoint with write and sync times
log_autovacuum_min_duration10min since PostgreSQL 15Logs slow autovacuum runs
long_query_time (MySQL)10 sSlow log threshold
slow_query_log (MySQL)OFFSwitch for the slow log

The three things to do first.

SituationDo this
New PostgreSQL serverLoad pg_stat_statements, set log_min_duration_statement, log_lock_waits, track_io_timing; add the exporter
Something is slow nowpg_stat_activity (who, state, wait), then pg_blocking_pids(); do not start with the log
Something got slower after a deployDiff pg_stat_statements per queryid before and after, then read the plan from auto_explain

Why database observability exists ​

An application dashboard says "p99 latency doubled". It does not say whether the cause is a new query, a lock, a full disk cache, a saturated pool or a replica that fell behind. The database is shared by every request and every service, so one bad query hurts unrelated endpoints, and the only place that sees all of them is the server. That is why the server keeps its own counters. The application sees what the user felt; the server sees why.

Look from the applicationLook from the server
Per-request, per-user latencyPer-statement totals across all callers
Includes pool wait and networkExcludes both
Knows the route and the trace idKnows the lock, the plan and the buffer reads
Sees errors the driver returnedSees errors the server raised, including those the app swallowed
Cannot see other services' queriesSees every client, including the ones you forgot

The analogy we reuse on this page: a hospital. The incident log notes every patient who waited more than an hour (the slow query log). The ward board shows who is in a bed, who waits and for how long (pg_stat_activity). The billing summary groups cost by procedure (pg_stat_statements). Telephone logs at the front desk show how long callers held the line before they were seen (application spans and DBStats). A hospital needs all four, because each answers a question the others cannot.

Three common misunderstandings, up front ​

  1. "pg_stat_statements shows the slowest queries." It shows cumulative cost since the last reset. A single 40-second query hides inside a mean; read max_exec_time and the log for outliers.
  2. "A high cache hit ratio means a healthy database." It says most block reads came from shared_buffers. A query can read a million cached rows and still be wrong.
  3. "If the database dashboard is green, the database is not the problem." The application can wait for its own pool, or for the network, and the server sees neither. Compare both sides.

The four golden signals applied to a database ​

The Google SRE book names four signals for a user-facing system: latency, traffic, errors, saturation. They map onto a database like this.

Latency Must-know ​

In plain words: how long a statement takes, from the moment the server starts it to the moment it finishes.

Common misunderstanding: "Latency is one number." It is a distribution. The mean hides the tail; a query with a 5 ms mean and a 3 s maximum ruins one request in a thousand.

Definition: per-statement execution time (mean_exec_time, max_exec_time, stddev_exec_time in pg_stat_statements), plus the server-wide transaction latency you can derive from pg_stat_database. Report percentiles from tracing or histograms; pg_stat_statements has no percentile column (MySQL's digest table has QUANTILE_95).

Real scenario: a report query averages 800 ms and runs twice an hour, a login query averages 2 ms and runs 5 000 times a second. The second costs far more in total.

Traffic Must-know ​

In plain words: how much work the database is asked to do.

Common misunderstanding: "Traffic means connections." Ten connections can issue a million statements a minute.

Definition: calls per statement, xact_commit + xact_rollback per second from pg_stat_database, tup_returned/tup_fetched/tup_inserted/tup_updated/tup_deleted, WAL bytes per second from pg_stat_wal.

Errors Must-know ​

In plain words: statements and transactions that failed.

Common misunderstanding: "No exceptions in the app, so no errors." ORMs retry and swallow serialization failures and deadlocks.

Definition: xact_rollback and deadlocks in pg_stat_database, conflicts in pg_stat_database_conflicts (standbys), ERROR lines in the log with their SQLSTATE (40001, 40P01, 55P03, 57014, 53300), SUM_ERRORS in MySQL's digest table, the error.type attribute on spans.

Saturation Must-know ​

In plain words: how full the most constrained resource is. Latency goes up sharply when a resource nears 100%.

Common misunderstanding: "CPU is the resource." For a database the first wall is usually connections (max_connections), then I/O, then locks, and CPU last.

Definition: connections used over max_connections, pool utilisation (DBStats.InUse over MaxOpenConnections), disk I/O and IO wait events, WAL generation against disk, replication lag, the age of the oldest transaction ID, and lock waits.

SignalPostgreSQL sourceMySQL sourceAlert shape
Latencymean_exec_time, max_exec_time, span histogramAVG_TIMER_WAIT, QUANTILE_95p99 per operation over baseline
Trafficcalls, xact_commit, wal_bytesCOUNT_STAR, Questionsanomaly vs last week
Errorsdeadlocks, xact_rollback, log SQLSTATESUM_ERRORS, Innodb_deadlocksrate above zero for deadlocks
Saturationconnections, IO waits, lag, xid ageThreads_connected, Threads_running, history list lengthutilisation above 80%

Two older checklists sit beside these. Brendan Gregg's USE method (utilisation, saturation, errors per resource) fits disks, connections and WAL. Tom Wilkie's RED method (rate, errors, duration per service) fits each query class or endpoint. A good dashboard uses RED per statement and USE per resource.

Mechanics: reading PostgreSQL from the inside ​

PostgreSQL has two separate mechanisms. The cumulative statistics system keeps counters inside the server and exposes them as views (pg_stat_*); it answers "how much, since the last reset". The server log writes events as they happen; it answers "what exactly happened at 14:03:12". Most confusion comes from mixing them up. Since PostgreSQL 15 the statistics live in shared memory rather than a stats collector process, and pg_stat_reset() and pg_stat_statements_reset() clear them.

pg_stat_statements Must-know ​

In plain words: a table of every distinct query shape the server has run, with how many times, how long in total and how many rows. It is the first thing to read when "the database is slow".

Common misunderstanding: "It lists individual executions." It lists shapes, aggregated. Constants are removed, so WHERE id = 7 and WHERE id = 9 are one row.

Definition: a contrib module. It must be in shared_preload_libraries (restart required) and enabled per database with CREATE EXTENSION pg_stat_statements. The manual says one row exists for each distinct combination of database id, user id, query id and whether it is a top-level statement. Normalization replaces constants with $1, $2; the docs word it this way: "When a constant's value has been ignored for purposes of matching the query to other queries, the constant is replaced by a parameter symbol, such as $1, in the pg_stat_statements display."

text
     Session A (app)                              pg_stat_statements
1    SELECT * FROM orders WHERE user_id = 7;      queryid 8812…  calls=1  query="… WHERE user_id = $1"
2    SELECT * FROM orders WHERE user_id = 9;      queryid 8812…  calls=2  (same shape, one row)
3    SELECT * FROM orders WHERE id = 9;           queryid 5120…  calls=1  (different shape, new row)
4    -- 5 001 distinct shapes with max=5000      least-used entries are evicted; see dealloc

Columns worth knowing:

ColumnMeaningUse
queryidHash of the normalized parse treeJoin key across resets and across time; also in pg_stat_activity.query_id and EXPLAIN VERBOSE
callsNumber of executionsTraffic
total_exec_timeSum of execution time, msRank by cost
mean_exec_time, min_exec_time, max_exec_time, stddev_exec_timePer-call latencyFind regressions and outliers
rowsRows returned or affectedRows per call: large for scans, 1 for key lookups
shared_blks_hit, shared_blks_readBlocks found in shared_buffers, blocks read from the OSCache behaviour per query
shared_blks_dirtied, shared_blks_writtenBlocks dirtied or written by the queryWrite-heavy statements
local_blks_*, temp_blks_read, temp_blks_writtenTemp table and spill-to-disk I/OSorts and hashes that exceed work_mem
shared_blk_read_time, shared_blk_write_timeI/O time (needs track_io_timing)Is the read time disk or CPU
plans, total_plan_timePlanning count and time (needs pg_stat_statements.track_planning, off by default)Slow planning of many-partition tables
wal_records, wal_fpi, wal_bytesWAL producedWhich statements flood the WAL
toplevelStatement was top-level, not inside a functionWith track = all, tells nested from outer
stats_since, minmax_stats_sinceWhen counters (or min/max) startedWindow of the numbers

Ranking recipes. The same view answers different questions depending on the ORDER BY.

Order byFindsTypical action
total_exec_time DESCWhere the server spends its timeIndex, rewrite, or cache the top three
mean_exec_time DESC (with calls > 100)Slow per callPlan investigation
calls DESCChatty code, N+1Batch, join, cache (see ORM Pitfalls)
rows / calls DESCQueries that return too muchPagination, a narrower SELECT
shared_blks_read DESCCache-missing queriesIndex, working set
temp_blks_written DESCSorts and hashes spillingwork_mem, index for ordering
wal_bytes DESCHeaviest writersBatch writes, drop unused indexes
stddev_exec_time / mean_exec_time DESCUnstable plansStatistics, parameter sniffing issues
sql
-- 1. Enable (postgresql.conf, restart): shared_preload_libraries = 'pg_stat_statements'
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;

-- 2. Top ten by total time, with share of all time and cache behaviour.
SELECT queryid,
       left(query, 70)                                              AS query,
       calls,
       round(total_exec_time::numeric, 1)                           AS total_ms,
       round(mean_exec_time::numeric, 2)                            AS mean_ms,
       round(max_exec_time::numeric, 1)                             AS max_ms,
       rows,
       round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct,
       round(100.0 * shared_blks_hit / nullif(shared_blks_hit + shared_blks_read, 0), 1) AS hit_pct
FROM pg_stat_statements
WHERE dbid = (SELECT oid FROM pg_database WHERE datname = current_database())
ORDER BY total_exec_time DESC
LIMIT 10;

-- 3. Evictions: if dealloc grows, raise pg_stat_statements.max.
SELECT dealloc, stats_reset FROM pg_stat_statements_info;

-- 4. Start a clean measurement window (for example before a load test).
SELECT pg_stat_statements_reset();

Limits. The query column is NULL when the external text file is discarded; counters remain. Statements are normalized, so you do not see which literal was slow (use the log or auto_explain). Utility statements are tracked by default (track_utility). The default track = top ignores statements inside functions; all includes them. A Go and Laravel reader is in Application side.

pg_stat_activity and wait events Must-know ​

In plain words: one row per server process, saying what each is doing right now and what it is waiting for.

Common misunderstanding: "A session in state = active is working." It can be active and blocked: the docs say "The wait_event and state columns are independent." Read both.

Definition: the view has one row per backend (client backends, autovacuum workers, WAL sender, background workers). Filter backend_type = 'client backend' for application sessions.

ColumnMeaning
pid, usename, datnameProcess, role, database
application_nameClient-provided label; set it per service (see Correlation)
client_addr, client_portWhere the connection comes from
backend_start, xact_start, query_start, state_changeWhen the connection, transaction, current query and last state change began
stateactive, idle, idle in transaction, idle in transaction (aborted), fastpath function call, disabled
wait_event_type, wait_eventWhat the backend waits for; NULL means running on CPU
backend_xid, backend_xminTransaction id and the oldest snapshot this backend holds; a high-age backend_xmin blocks vacuum
query, query_idCurrent or last statement text (truncated to track_activity_query_size, default 1024 bytes); query_id joins to pg_stat_statements
leader_pidParallel worker's leader

The state that causes most production incidents is idle in transaction. The docs define it: "The backend is in a transaction, but is not currently executing a query." The transaction keeps its locks and its snapshot while the application calls an HTTP API or waits for a user.

text
     Session A (app, idle in transaction)         Session B (autovacuum / a migration)
1    BEGIN;
2    SELECT * FROM orders WHERE id = 1;           -- A now holds a snapshot (backend_xmin = 1042)
3    -- application calls a payment API (40 s)
4                                                 DELETE FROM orders WHERE id < 1000; COMMIT;
5                                                 VACUUM orders;   -- cannot remove those rows: A may still see them
6    pg_stat_activity: A state='idle in transaction', xact_start 40 s old, backend_xmin=1042
7    -- n_dead_tup grows, the table bloats; ALTER TABLE in another session waits behind A
sql
-- Who is doing what, longest transaction first. Excludes this session.
SELECT pid, usename, application_name, state, wait_event_type, wait_event,
       now() - xact_start  AS xact_age,
       now() - query_start AS query_age,
       backend_xmin, left(query, 80) AS query
FROM pg_stat_activity
WHERE backend_type = 'client backend' AND pid <> pg_backend_pid()
ORDER BY xact_start NULLS LAST;

-- Count by state: the saturation view.
SELECT state, count(*) FROM pg_stat_activity
WHERE backend_type = 'client backend' GROUP BY state ORDER BY count DESC;

-- Wait profile right now: where is the server stuck?
SELECT wait_event_type, wait_event, count(*)
FROM pg_stat_activity WHERE state = 'active' AND backend_type = 'client backend'
GROUP BY 1, 2 ORDER BY count DESC;

Preventive settings: idle_in_transaction_session_timeout ends sessions that sit idle in a transaction; statement_timeout cancels long statements; lock_timeout bounds waiting for a lock; transaction_timeout (PostgreSQL 17) bounds a whole transaction. These are guard rails, not substitutes for fixing the application.

Wait events: the taxonomy ​

The wait_event_type column groups what a backend can wait for. NULL means the backend is executing on CPU; anything else means it is stopped.

pg_stat_activity: wait_event_type + wait_eventNULL means the backend is on CPUIdle or client sideContentionResourcesClient: ClientReadapp is slow; idle in transactionActivity: BgWriterMainbackground process restingTimeout: PgSleeppg_sleep, VacuumDelayLock: transactionid, relationpg_blocking_pids, find the holderLWLock: WALWrite, BufferMappinginternal hot spot, wal_buffersBufferPin: BufferPinVACUUM waits for a pinned pageIO: DataFileRead, WALSynccache miss, slow disk, pg_stat_ioIPC: SyncRep, ProcArrayGroupUpdatewaiting for another process or standbyExtension: extension-definedpg_wait_sampling can add more
wait_event_typeMeaningExample wait_eventFirst move
LockWaiting for a heavyweight lockrelation, transactionid, tuple, advisorypg_blocking_pids(); find the holder
LWLockWaiting for an internal lightweight lockWALWrite, BufferMapping, LockManagerContention inside the server; tune wal_buffers, reduce connections
BufferPinWaiting for exclusive access to a pageBufferPinA long cursor or query is pinning a page; VACUUM waits
IOWaiting for a read or write to finishDataFileRead, WALSync, WALWriteCache miss or slow disk; check pg_stat_io
IPCWaiting for another processSyncRep, ProcArrayGroupUpdate, BgWorkerStartupSyncRep means a synchronous standby is slow
ClientWaiting for the clientClientRead, ClientWriteThe application is slow; idle in transaction shows ClientRead
TimeoutWaiting for a timerPgSleep, VacuumDelay, RecoveryApplyDelayUsually intentional
ActivityA background process is idleBgWriterMain, AutoVacuumMain, WalSenderMainNothing; this is not a problem
ExtensionWaiting inside an extensiondefined by the extensionRead the extension's docs

The view shows a sample at one instant. One look at pg_stat_activity can mislead; sampling it many times builds a profile, which is what pg_wait_sampling does inside the server and what cloud "Performance Insights" tools do from outside (see Extensions and vendor tools).

pg_locks and pg_blocking_pids Must-know ​

In plain words: pg_locks lists every lock held or waited for; pg_blocking_pids(pid) answers "who is stopping this session".

Common misunderstanding: "The blocker is the session running the long query." The blocker is often idle: a transaction that took a lock and then went quiet.

Definition: pg_locks has columns locktype (relation, tuple, transactionid, advisory…), mode, granted, pid, relation, transactionid, waitstart (since PostgreSQL 14). pg_blocking_pids(int) returns the pids that hold or are queued ahead for the lock the given pid waits on. Lock modes are in Locks & Concurrency.

text
     Session A (blocker)                    Session B (victim)                 Monitor
1    BEGIN;
2    UPDATE accounts SET balance = 0
     WHERE id = 1;                          -- A holds a row lock and a transactionid
3                                           BEGIN;
4                                           UPDATE accounts SET ... WHERE id = 1;  -- waits
5                                                                              pg_stat_activity: B wait_event_type='Lock', wait_event='transactionid'
6                                                                              pg_blocking_pids(B) -> {A}
7                                                                              A: state='idle in transaction'  <- the real culprit
8    -- after deadlock_timeout (1 s) with log_lock_waits=on: "process B still waiting for ShareLock on transaction ..."
sql
-- Blocked sessions and their blockers (the same query as the Laravel command).
SELECT blocked.pid  AS blocked_pid,
       blocked.application_name AS blocked_app,
       now() - blocked.query_start AS waiting,
       left(blocked.query, 60) AS blocked_query,
       blocker.pid AS blocker_pid, blocker.state AS blocker_state,
       now() - blocker.xact_start AS blocker_xact_age,
       left(blocker.query, 60) AS blocker_query
FROM pg_stat_activity AS blocked
JOIN LATERAL unnest(pg_blocking_pids(blocked.pid)) AS b(pid) ON true
JOIN pg_stat_activity AS blocker ON blocker.pid = b.pid
WHERE blocked.wait_event_type = 'Lock';

-- Ungranted locks with the relation name.
SELECT l.pid, l.locktype, l.mode, l.granted, c.relname
FROM pg_locks l LEFT JOIN pg_class c ON c.oid = l.relation
WHERE NOT l.granted;

-- Cancel the query, or end the session (last resort).
SELECT pg_cancel_backend(12345);
SELECT pg_terminate_backend(12345);

Table and index statistics Important ​

In plain words: per-table and per-index counters that tell you whether queries use indexes and whether vacuum keeps up.

Common misunderstanding: "An index with idx_scan = 0 is unused, drop it." The counter covers the period since the last reset; an index used only by a quarterly job looks unused for months. Also check that it does not back a unique or primary key constraint.

Definition: pg_stat_user_tables (and pg_stat_all_tables, pg_statio_user_tables) and pg_stat_user_indexes.

ColumnViewReading
seq_scan, seq_tup_readtablesHigh on a large table: candidate for an index
idx_scan, idx_tup_fetchtables, indexesIndex usage; idx_scan = 0 over a long window, unused index
last_seq_scan, last_idx_scantables, indexes (PostgreSQL 16+)When last used; makes the "unused" test safe
n_tup_ins, n_tup_upd, n_tup_del, n_tup_hot_updtablesWrite mix; many non-HOT updates mean index churn
n_live_tup, n_dead_tuptablesDead tuples awaiting vacuum; the bloat precursor
n_mod_since_analyzetablesRows changed since the last ANALYZE; stale statistics
last_vacuum, last_autovacuum, last_analyze, last_autoanalyzetablesIs autovacuum reaching this table at all
vacuum_count, autovacuum_counttablesHow often
sql
-- Large tables read mostly by sequential scans.
SELECT relname, seq_scan, seq_tup_read, idx_scan, n_live_tup
FROM pg_stat_user_tables
WHERE n_live_tup > 100000 AND seq_scan > coalesce(idx_scan, 0)
ORDER BY seq_tup_read DESC LIMIT 20;

-- Unused indexes (not unique, not primary), with size.
SELECT s.schemaname, s.relname, s.indexrelname, s.idx_scan,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0 AND NOT i.indisunique AND NOT i.indisprimary
ORDER BY pg_relation_size(s.indexrelid) DESC;

-- Tables where dead tuples pile up.
SELECT relname, n_live_tup, n_dead_tup,
       round(100.0 * n_dead_tup / nullif(n_live_tup + n_dead_tup, 0), 1) AS dead_pct,
       last_autovacuum, last_autoanalyze
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 20;

-- Progress of a running vacuum.
SELECT * FROM pg_stat_progress_vacuum;

Wraparound age belongs here too: SELECT datname, age(datfrozenxid) FROM pg_database; counts how far each database's oldest unfrozen transaction id is from the 2^31 limit (about 2.1 billion); alert well before 1.5 billion. It is explained in MVCC, VACUUM & Bloat.

pg_stat_io, bgwriter and checkpointer Important ​

In plain words: how much the server reads and writes, who does it (client, background writer, checkpointer, autovacuum) and how often checkpoints are forced.

Common misunderstanding: "pg_stat_bgwriter has the checkpoint numbers." Since PostgreSQL 17 checkpoint counters moved to pg_stat_checkpointer; pg_stat_bgwriter keeps the background writer's.

Definition:

ViewSinceShows
pg_stat_io16I/O by backend_type x object (relation, temp relation, WAL) x context (normal, vacuum, bulkread, bulkwrite): reads, writes, extends, hits, evictions, reuses, fsyncs, and times with track_io_timing
pg_stat_bgwriteroldbuffers_clean, maxwritten_clean, buffers_alloc (and the checkpoint columns before 17)
pg_stat_checkpointer17num_timed, num_requested, write_time, sync_time, buffers_written
pg_stat_wal14wal_records, wal_fpi, wal_bytes, wal_buffers_full
pg_stat_databaseoldper database: xact_commit, xact_rollback, blks_read, blks_hit, temp_files, temp_bytes, deadlocks, idle_in_transaction_time (14+)

A rising num_requested against num_timed means checkpoints are triggered by WAL volume (max_wal_size too small) instead of by checkpoint_timeout; every one causes an I/O burst. log_checkpoints writes the details of each one to the log. pg_stat_io is the cleanest way to answer "who is reading from disk": evictions by client backends mean shared_buffers is too small for the working set; fsyncs by client backends mean the checkpointer or bgwriter fell behind.

sql
SELECT backend_type, object, context, reads, writes, hits, evictions, fsyncs
FROM pg_stat_io WHERE reads > 0 OR writes > 0 ORDER BY reads DESC NULLS LAST LIMIT 10;
SELECT num_timed, num_requested, write_time, sync_time, buffers_written
FROM pg_stat_checkpointer;   -- PostgreSQL 17+

Replication lag Important ​

In plain words: how far behind a standby is, in bytes and in time.

Common misunderstanding: "Lag is a single number." There are three stages: the standby has received the WAL, flushed it to disk, replayed it. Reads on a replica see only replayed data.

Definition: on the primary, pg_stat_replication has sent_lsn, write_lsn, flush_lsn, replay_lsn, and write_lag, flush_lag, replay_lag (time intervals). pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) gives bytes. On a standby, now() - pg_last_xact_replay_timestamp() gives time since the last replayed commit (misleading when the primary is idle). pg_replication_slots shows slots; an inactive slot retains WAL and can fill the disk.

sql
SELECT application_name, client_addr, state, sync_state,
       pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes,
       write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;

See Replication, Read Replicas & Failover for what to do about it.

Cache hit ratio and its limits Important ​

In plain words: the share of block reads served from memory instead of the OS or disk.

Common misunderstanding: "99% is good, below 95% is bad." A falling ratio is a symptom of a changed working set or a new scan, not a cause; and a 99.99% ratio can coexist with a full table scan on cached pages.

Definition: blks_hit / (blks_hit + blks_read) from pg_stat_database, or per statement from shared_blks_hit and shared_blks_read. blks_read counts reads requested from the OS, which can still be served by the OS page cache, so a "miss" is not always a disk read. The index hit ratio uses pg_statio_user_indexes (idx_blks_hit, idx_blks_read).

sql
SELECT datname, round(100.0 * blks_hit / nullif(blks_hit + blks_read, 0), 2) AS hit_pct
FROM pg_stat_database WHERE datname = current_database();

Limits. (1) It is cumulative since the last reset, so a recent change is diluted; compute the rate over a window. (2) It hides the OS cache. (3) It says nothing about how many blocks a query touched. (4) A lower ratio right after a restart is normal. Use it as a trend line, and pair it with pg_stat_io and IO waits.

Logs and auto_explain Must-know ​

In plain words: the log captures the individual events the counters average away: this exact query took this long, this lock wait lasted this long.

Common misunderstanding: "Log everything, then search." log_min_duration_statement = 0 logs every statement and becomes the bottleneck on a busy server. Log above a threshold, and sample the rest.

ParameterDefaultPurpose
log_min_duration_statement-1Log every statement taking at least this long; 0 logs all; the docs: "Causes the duration of each completed statement to be logged if the statement ran for at least the specified amount of time."
log_min_duration_sample, log_statement_sample_rate-1, 1.0Log a fraction of statements above a lower threshold; statements over log_min_duration_statement are always logged
log_transaction_sample_rate0Sample whole transactions
log_lock_waitsoffLog a wait that exceeds deadlock_timeout
log_checkpointson (15+)Each checkpoint's buffers, write and sync time
log_autovacuum_min_duration10min (15+)Autovacuum runs longer than this, with stats
log_temp_files-1Log temp files above a size (spilling sorts and hashes)
log_connections, log_disconnectionsoffConnection churn
log_line_prefix%m [%p] Put time, pid, user, database and %a application name on every line
log_statementnoneddl, mod, all; audit rather than performance
log_error_verbosity, log_destination (stderr, csvlog, jsonlog since 15)Structured logs for shippers

A line prefix that works with pgBadger and with application_name: log_line_prefix = '%t [%p]: user=%u,db=%d,app=%a,client=%h '.

text
     postgresql.conf                              server log
1    log_min_duration_statement = 250
2    log_lock_waits = on
3    ... request arrives ...                      LOG: duration: 812.4 ms  statement: SELECT … FROM orders …
4    ... UPDATE waits 1.2 s for a row lock ...   LOG: process 4417 still waiting for ShareLock on transaction 9021 after 1000.1 ms
5    ... checkpoint ...                           LOG: checkpoint complete: wrote 18032 buffers (11.0%); write=26.9 s, sync=0.03 s

auto_explain ​

auto_explain writes the execution plan of slow statements to the log, so you read the plan the server really chose, with the real parameters, at the moment it was slow. It fixes the usual dead end: a query that is fast when you run EXPLAIN by hand and slow in production.

ParameterDefaultMeaning
auto_explain.log_min_duration-1Plan of statements slower than this is logged; 0 logs all
auto_explain.log_analyzeoffInclude actual times and rows (adds timing overhead to every statement)
auto_explain.log_buffersoffBuffer hits and reads (needs log_analyze)
auto_explain.log_timingonPer-node timing; turn off to cut overhead, keeping row counts
auto_explain.log_nested_statementsoffStatements inside functions
auto_explain.log_formattexttext, xml, json, yaml
auto_explain.sample_rate1.0Fraction of statements explained
auto_explain.log_wal, log_triggers, log_verbose, log_settingsoffMore detail

Load it with session_preload_libraries (no restart for new sessions) or shared_preload_libraries. With log_analyze on, every statement pays the timing cost even if it is not logged; combine a threshold with sample_rate and log_timing = off on busy servers.

pgBadger ​

pgBadger is a Perl log analyser. It reads the PostgreSQL log (text, csvlog or jsonlog) and writes a static HTML report: the slowest and most frequent normalized queries, queries per second, connections, lock waits, temp files, checkpoints, autovacuum activity, errors. It is the offline counterpart of pg_stat_statements, and it needs log_line_prefix to contain time, pid and preferably user, database and application. Run pgbadger -f stderr -p '%t [%p]: user=%u,db=%d,app=%a,client=%h ' postgresql.log -o report.html. Use it for after-the-fact reviews and when you cannot install an extension; use pg_stat_statements for live data.

Extensions and vendor tools Good to know ​

ToolWhat it addsNote
pg_stat_kcachePer-statement physical reads and writes and CPU user/system time, taken from the operating system (getrusage)Requires pg_stat_statements; separates "slow because CPU" from "slow because disk"
pg_wait_samplingSamples wait_event of every backend (default 10 ms) into pg_wait_sampling_current, _history, _profileGives a real wait profile per query, which one look at pg_stat_activity cannot
pg_stat_monitor (Percona)Bucketed time windows, histograms, plan text, client address per statementAlternative to pg_stat_statements
pg_buffercacheWhat is in shared_buffersWorking-set investigation
pgstattuple, pg_visibilityExact bloat and visibility-map stateHeavier than estimates
pg_qualstats, HypoPG, PoWAPredicate statistics, hypothetical indexes, history of statisticsIndex advisors
pganalyze, Datadog Database Monitoring, Percona PMM, New RelicHosted or self-hosted dashboards on the same viewsThey add history, plans and alerts
AWS RDS Performance Insights, Google Cloud SQL Query Insights, Azure Query Performance InsightManaged wait profile and top SQLBased on sampling pg_stat_activity

Metrics pipeline: exporter, Prometheus, Grafana ​

In plain words: a small program reads the statistics views every few seconds and publishes them as numbers a time-series database can store.

Common misunderstanding: "Install the exporter and the top-query dashboard fills up." The exporter's stat_statements collector is off by default, and its README says the same: --[no-]collector.stat_statements (default: disabled). Enable it and set a limit, or the cardinality explodes.

ApplicationGo / LaravelDBStats, spansPostgreSQLpg_stat_* viewsserver logpostgres_exportermetricsLog shipperlogsOTel CollectortracesPrometheustime seriesLoki / pgBadgerlog searchTempo / Jaegertrace storeGrafanaAlertmanagerSQL + commentscrapeOTLP

Definition: postgres_exporter (prometheus-community) connects to PostgreSQL with a role that has pg_monitor, exposes /metrics, and Prometheus scrapes it. Grafana draws dashboards, and Alertmanager routes alerts. For MySQL use mysqld_exporter. Application and pool metrics (DBStats, span histograms) go to the same Prometheus through the application's own endpoint or an OpenTelemetry Collector.

Metric (exporter default)FromUse
pg_upconnection checkThe exporter can reach the server
pg_stat_activity_count{state=...}pg_stat_activityConnections by state
pg_settings_max_connectionspg_settingsDenominator for saturation
pg_stat_database_xact_commit, _xact_rollback, _blks_hit, _blks_read, _deadlocks, _temp_bytespg_stat_databaseTraffic, errors, cache, deadlocks
pg_stat_user_tables_n_dead_tup, _seq_scan, _idx_scanpg_stat_user_tablesVacuum and index health
pg_replication_lag_secondsstandbyReplica lag in seconds
pg_stat_statements_* (collector, opt-in)pg_stat_statementsTop statements per queryid
pg_stat_bgwriter_*, pg_stat_checkpointer_*bgwriter and checkpointerCheckpoint pressure

Wraparound age, the oldest transaction and the oldest backend_xmin are not in the default set; add them as custom queries in the exporter's queries file or with a separate collector.

Grafana dashboards worth knowing: the community "PostgreSQL Database" dashboard (id 9628), "PostgreSQL Overview" from the exporter docs, and Percona PMM's PostgreSQL dashboards. Build four rows on your own: saturation (connections, pool), latency/traffic (xact, top statements), I/O and cache, replication and vacuum. Keep high-cardinality labels (queryid, application_name) to top-N lists, since every distinct value is a separate time series.

Histograms and exemplars. A Prometheus histogram (for example db_client_operation_duration_seconds) gives percentiles across instances; an exemplar attaches a trace id to a bucket so a dashboard spike links to a trace.

Per-engine observability ​

Never name a feature without naming the product. This is what each engine gives.

EngineAggregate statementsLive sessions and locksPlans and slow logWait data
PostgreSQLpg_stat_statements, pg_stat_monitorpg_stat_activity, pg_locks, pg_blocking_pidslog_min_duration_statement, auto_explain, pgBadgerwait_event_type/wait_event, pg_wait_sampling
MySQL / InnoDBperformance_schema.events_statements_summary_by_digest, sys.statement_analysisSHOW PROCESSLIST, performance_schema.threads, data_locks, data_lock_waits, sys.innodb_lock_waitsSlow query log, pt-query-digest, EXPLAIN ANALYZEevents_waits_*, sys.waits_global_by_latency
SQL ServerQuery Store, sys.dm_exec_query_statssys.dm_exec_requests, sys.dm_tran_locks, sys.dm_os_waiting_tasksActual execution plans, Extended Eventssys.dm_os_wait_stats
OracleAWR, V$SQL, V$SQLSTATSV$SESSION, V$LOCK, DBA_BLOCKERSSQL Monitor, DBMS_XPLANASH (V$ACTIVE_SESSION_HISTORY), V$SYSTEM_EVENT
SQLitenone built innone (single process)EXPLAIN QUERY PLAN, sqlite3_trace_v2, sqlite_stmtnone
MongoDBDatabase profiler (system.profile), $queryStatsdb.currentOp(), serverStatusexplain("executionStats"), slow query log (slowms)serverStatus globalLock, wiredTiger
CockroachDBDB Console SQL Activity, crdb_internal.statement_statisticsSHOW SESSIONS, crdb_internal.cluster_locksStatement diagnostics bundles, EXPLAIN ANALYZEcontention events
RedisINFO commandstatsCLIENT LISTSLOWLOG GET, LATENCY DOCTORLATENCY HISTORY

MySQL in detail Important ​

In plain words: MySQL keeps its statistics in the performance_schema database and offers readable summaries in the sys schema (the sys database of views).

Common misunderstanding: "The slow log is the MySQL equivalent of pg_stat_statements." The slow log lists individual statements above a threshold; the digest table aggregates every statement. They are complementary.

Definition and tools:

ToolWhat it showsNotes
performance_schema.events_statements_summary_by_digestPer normalized statement (DIGEST, DIGEST_TEXT): COUNT_STAR, SUM_TIMER_WAIT, AVG_TIMER_WAIT, MAX_TIMER_WAIT, SUM_LOCK_TIME, SUM_ERRORS, SUM_ROWS_EXAMINED, SUM_ROWS_SENT, SUM_NO_INDEX_USED, QUANTILE_95Timers are in picoseconds; SUM_ROWS_EXAMINED much larger than SUM_ROWS_SENT means missing indexes
performance_schema.data_locks, data_lock_waitsInnoDB locks held and waited for (MySQL 8.0+)Replaced information_schema.INNODB_LOCKS
sys schemaViews over performance_schema: statement_analysis, statements_with_full_table_scans, innodb_lock_waits, schema_unused_indexes, schema_redundant_indexes, host_summaryHuman-readable; the x$ variants return raw numbers
Slow query logslow_query_log=ON, long_query_time (10 s default), log_queries_not_using_indexes, min_examined_row_limit, log_slow_extra, log_output (FILE or TABLE)Entries have Query_time, Lock_time, Rows_sent, Rows_examined
pt-query-digest (Percona Toolkit)Groups slow log entries by fingerprint and ranks by total timeThe MySQL counterpart of pgBadger; mysqldumpslow is the bundled simpler tool
SHOW ENGINE INNODB STATUSSections: SEMAPHORES, LATEST DETECTED DEADLOCK, TRANSACTIONS, FILE I/O, LOG, BUFFER POOL AND MEMORY, ROW OPERATIONSinnodb_print_all_deadlocks=ON writes every deadlock to the error log
information_schema.INNODB_TRX, INNODB_METRICSOpen transactions with trx_started, rows locked; countersA large history list length means purge is behind, MySQL's version of bloat
mysqld_exporterPrometheus metrics from status variables and performance_schemaThreads_running, Innodb_buffer_pool_reads, Innodb_row_lock_waits
sql
-- MySQL 8: top statements by total time (timers are picoseconds, so divide).
SELECT schema_name, LEFT(digest_text, 70) AS query, count_star AS calls,
       ROUND(sum_timer_wait / 1e12, 2) AS total_s,
       ROUND(avg_timer_wait / 1e9, 2)  AS avg_ms,
       sum_rows_examined, sum_rows_sent, sum_no_index_used
FROM performance_schema.events_statements_summary_by_digest
ORDER BY sum_timer_wait DESC LIMIT 10;

-- Who blocks whom (InnoDB).
SELECT wait_age, locked_table, waiting_query, blocking_pid, blocking_query
FROM sys.innodb_lock_waits;

-- Enable the slow log at runtime.
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL long_query_time = 0.5;
SET GLOBAL log_queries_not_using_indexes = 'ON';

Traces and semantic conventions ​

In plain words: a trace shows one request as a tree of timed steps; a database span is the step that waited for the database. It is the only signal that includes the pool wait and the network.

Common misunderstanding: "Put the SQL text in the span so people can debug." The text can hold personal data in literals. The OpenTelemetry specification says: "The db.query.text SHOULD be collected by default only if there is sanitization that excludes sensitive information."

Definition: OpenTelemetry's stable database semantic conventions define a client span with these attributes.

AttributeMeaningExample
db.system.nameThe database productpostgresql, mysql
db.namespaceDatabase nameshop
db.collection.nameTable or collectionorders
db.operation.nameOperationSELECT
db.query.summaryLow-cardinality summary, used for the span nameSELECT orders
db.query.textThe statement, sanitized or parameterizedSELECT * FROM orders WHERE id = ?
db.response.status_codeDatabase error code23505, 40P01
error.typeError class40P01
server.address, server.portWhere the server isdb-primary, 5432

The span kind is CLIENT. The span name is the db.query.summary when available; otherwise {db.operation.name} {target} such as SELECT orders; never the raw SQL. Metrics: db.client.operation.duration (a histogram, in seconds) and the connection-pool metrics (db.client.connection.count, .pending_requests, .timeouts).

Sanitization of db.query.text. Parameterized statements ($1, ?) are safe to collect by default, because the values are not in the text. Statements with inline literals must be sanitized: replace every literal with ?. Never put bindings or arguments in a span attribute, a log field or an exception message.

text
     Request GET /orders/42                        Spans
1    http.server  GET /orders/{id}                 [──────────────── 118 ms ────────────────]
2      pool wait (DBStats.WaitDuration)               [── 31 ms ──]
3      SELECT orders  db.system.name=postgresql           [─────── 62 ms ───────]
4         server side (pg_stat_statements mean)            [──── 45 ms ────]   (network + decode = the rest)
5      render JSON                                                          [─ 9 ms ─]

Context propagation with SQLCommenter ​

A span cannot travel into the server on its own. SQLCommenter appends a comment such as /*route='/orders/%7Bid%7D',traceparent='00-…-01'*/ to the statement. It appears in the server log, in pg_stat_activity.query and in cloud query-insights tools, which then group by route and link to the trace. It does not change the plan, and pg_stat_statements ignores comments when computing queryid (the parse tree has none). The OpenTelemetry convention describes the same idea under "Context propagation". Go and Laravel examples follow.

Application side: Go and Laravel ​

Go ​

database/sql has built-in statistics. DB.Stats returns DBStats, and the Go docs describe WaitDuration as "The total time blocked waiting for a new connection." That is the pool half of latency, invisible to pg_stat_statements. A rising WaitCount with a low MaxOpenConnections means the application waits on its own pool, not on the database.

Before: the query runs and returns. If it becomes slow nothing records it.

go
// Package before shows a query path with no timing, no statistics and no
// visibility beyond the request that runs it.
package before

import (
	"context"
	"database/sql"
)

type Order struct {
	ID         int64
	Status     string
	TotalCents int64
}

// ListOrders runs the query and returns the rows. Nothing records how long it
// took, how often it runs, or whether it has become the slowest statement in
// the database. The first sign of a problem is a user complaint.
func ListOrders(ctx context.Context, db *sql.DB, userID int64) ([]Order, error) {
	rows, err := db.QueryContext(ctx,
		`SELECT id, status, total_cents FROM orders WHERE user_id = $1 ORDER BY created_at DESC LIMIT 50`,
		userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []Order
	for rows.Next() {
		var o Order
		if err := rows.Scan(&o.ID, &o.Status, &o.TotalCents); err != nil {
			return nil, err
		}
		out = append(out, o)
	}
	return out, rows.Err()
}

After: Observed.Query times each call, logs only slow or failed ones and never the arguments; Publish exposes db.Stats() through expvar; TopStatements and ActiveSessions run read-only monitoring queries.

go
// Package after wraps database/sql with three things: per-query timing, pool
// statistics exposed through expvar, and read-only monitoring queries against
// the PostgreSQL statistics views. It has no OpenTelemetry dependency.
package after

import (
	"context"
	"database/sql"
	"expvar"
	"log/slog"
	"time"
)

// Observed times every query issued through it.
type Observed struct {
	DB     *sql.DB
	SlowAt time.Duration
	Logger *slog.Logger
}

// Publish exposes db.Stats() under name, as JSON at /debug/vars once an
// expvar-serving net/http server is running.
func Publish(name string, db *sql.DB) {
	expvar.Publish(name+".db_stats", expvar.Func(func() any {
		return db.Stats()
	}))
}

// Query runs a query and reports its duration. The duration covers waiting for
// a pooled connection, the network round trip and the server's execution up to
// the moment rows are returned. It does not cover iterating the rows.
//
// This is where a tracing span would start: a client span named after the
// operation (for example "SELECT orders"), with db.system.name set to
// "postgresql" and db.query.text set only to a sanitized form of the SQL.
// Arguments are never logged.
func (o *Observed) Query(ctx context.Context, query string, args ...any) (*sql.Rows, error) {
	start := time.Now()
	rows, err := o.DB.QueryContext(ctx, query, args...)
	elapsed := time.Since(start)

	if err != nil || elapsed >= o.SlowAt {
		o.Logger.WarnContext(ctx, "query",
			slog.String("sql", query),
			slog.Duration("elapsed", elapsed),
			slog.Bool("failed", err != nil),
		)
	}
	return rows, err
}

// TopStatementsSQL reads the most expensive normalized statements. The query
// column is NULL when the server has discarded the text, so it is scanned as
// a NullString.
const TopStatementsSQL = `
SELECT queryid, left(query, 200), calls, total_exec_time, mean_exec_time, rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT $1`

type Statement struct {
	QueryID  sql.NullInt64
	Query    sql.NullString
	Calls    int64
	TotalMS  float64
	MeanMS   float64
	RowCount int64
}

// TopStatements returns the statements with the highest total execution time.
// The extension must be installed with CREATE EXTENSION pg_stat_statements.
func TopStatements(ctx context.Context, db *sql.DB, limit int) ([]Statement, error) {
	rows, err := db.QueryContext(ctx, TopStatementsSQL, limit)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []Statement
	for rows.Next() {
		var s Statement
		if err := rows.Scan(&s.QueryID, &s.Query, &s.Calls, &s.TotalMS, &s.MeanMS, &s.RowCount); err != nil {
			return nil, err
		}
		out = append(out, s)
	}
	return out, rows.Err()
}

// ActiveSessionsSQL lists this database's non-idle backends, with the age of
// their transaction. A transaction older than a few seconds is a warning sign.
const ActiveSessionsSQL = `
SELECT pid, state, wait_event_type, wait_event,
       EXTRACT(EPOCH FROM now() - xact_start) AS xact_age_seconds
FROM pg_stat_activity
WHERE datname = current_database()
  AND state IS DISTINCT FROM 'idle'
ORDER BY xact_start NULLS LAST`

type Session struct {
	PID        int64
	State      sql.NullString
	WaitType   sql.NullString
	WaitEvent  sql.NullString
	XactAgeSec sql.NullFloat64
}

// ActiveSessions returns the current non-idle backends.
func ActiveSessions(ctx context.Context, db *sql.DB) ([]Session, error) {
	rows, err := db.QueryContext(ctx, ActiveSessionsSQL)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var out []Session
	for rows.Next() {
		var s Session
		if err := rows.Scan(&s.PID, &s.State, &s.WaitType, &s.WaitEvent, &s.XactAgeSec); err != nil {
			return nil, err
		}
		out = append(out, s)
	}
	return out, rows.Err()
}

poolmetrics turns DBStats into the numbers an alert needs: utilisation, average wait since the last sample and idle/lifetime churn.

go
// Package poolmetrics turns sql.DBStats into the numbers an alert needs:
// saturation of the pool, the average wait for a connection since the last
// sample, and the churn caused by idle and lifetime limits.
package poolmetrics

import (
	"database/sql"
	"time"
)

// Sample is one reading of the pool, with rates against the previous reading.
type Sample struct {
	At time.Time

	InUse       int
	Idle        int
	Open        int
	MaxOpen     int
	Utilization float64 // InUse / MaxOpen, 0 when MaxOpen is unlimited

	// Since the previous sample.
	Waits       int64         // connections that had to wait for a free slot
	AvgWait     time.Duration // total wait divided by Waits
	IdleClosed  int64         // closed because of SetMaxIdleConns
	LifeClosed  int64         // closed because of SetConnMaxLifetime
	IdleTimeout int64         // closed because of SetConnMaxIdleTime
}

// Collector keeps the previous DBStats so it can compute deltas.
type Collector struct {
	db   *sql.DB
	prev sql.DBStats
	have bool
}

// New returns a collector for db.
func New(db *sql.DB) *Collector { return &Collector{db: db} }

// Sample reads db.Stats() and compares it with the previous call. The first
// call returns the absolute gauges and zero rates.
func (c *Collector) Sample(now time.Time) Sample {
	st := c.db.Stats()
	s := Sample{
		At:      now,
		InUse:   st.InUse,
		Idle:    st.Idle,
		Open:    st.OpenConnections,
		MaxOpen: st.MaxOpenConnections,
	}
	if st.MaxOpenConnections > 0 {
		s.Utilization = float64(st.InUse) / float64(st.MaxOpenConnections)
	}
	if c.have {
		s.Waits = st.WaitCount - c.prev.WaitCount
		if s.Waits > 0 {
			s.AvgWait = (st.WaitDuration - c.prev.WaitDuration) / time.Duration(s.Waits)
		}
		s.IdleClosed = st.MaxIdleClosed - c.prev.MaxIdleClosed
		s.LifeClosed = st.MaxLifetimeClosed - c.prev.MaxLifetimeClosed
		s.IdleTimeout = st.MaxIdleTimeClosed - c.prev.MaxIdleTimeClosed
	}
	c.prev, c.have = st, true
	return s
}

// ShouldAlert is the rule of thumb used in the page: the pool is the
// bottleneck when most of it is busy and callers are queueing.
func (s Sample) ShouldAlert() bool {
	return s.Utilization >= 0.9 && s.Waits > 0
}

sqlcomment appends the SQLCommenter-style comment so the server log and pg_stat_activity name the route and the trace.

go
// Package sqlcomment appends a sqlcommenter-style trailing comment to a
// statement, so a line in pg_stat_activity or the server log can be traced back
// to a route, a controller and a trace.
package sqlcomment

import (
	"context"
	"database/sql"
	"net/url"
	"sort"
	"strings"
)

// Tags holds the key/value pairs that go into the comment.
type Tags map[string]string

// Append returns query followed by /*key='value',key2='value2'*/ with keys
// sorted and values URL-encoded, which is the layout the SQLCommenter format
// uses. The comment goes AFTER the statement so the text before it is
// unchanged. Keep the set of keys small and the values low-cardinality for
// anything that must stay groupable: pg_stat_statements strips comments when
// it computes queryid, so a comment does not split statistics, but a log line
// or a statement text that differs on every call is harder to search.
func Append(query string, tags Tags) string {
	if len(tags) == 0 {
		return query
	}
	keys := make([]string, 0, len(tags))
	for k := range tags {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	parts := make([]string, 0, len(keys))
	for _, k := range keys {
		parts = append(parts, url.QueryEscape(k)+"='"+strings.ReplaceAll(url.QueryEscape(tags[k]), "'", "%27")+"'")
	}
	return strings.TrimRight(query, "; \n") + " /*" + strings.Join(parts, ",") + "*/"
}

// Query runs a statement with the comment appended. traceparent is the W3C
// trace context header value of the current span, or an empty string.
func Query(ctx context.Context, db *sql.DB, route, traceparent, query string, args ...any) (*sql.Rows, error) {
	tags := Tags{"route": route}
	if traceparent != "" {
		tags["traceparent"] = traceparent
	}
	return db.QueryContext(ctx, Append(query, tags), args...)
}

slowlog holds the read-only alert queries as constants plus a runner (connections, oldest transaction, idle in transaction, replay lag, xid age, dead tuples).

go
// Package slowlog holds the read-only monitoring queries behind the alert
// rules in the page, as constants plus one runner. Every query touches only
// statistics views.
package slowlog

import (
	"context"
	"database/sql"
	"fmt"
)

// Alert is one rule: a name, the SQL, and the value above which it fires.
type Alert struct {
	Name      string
	SQL       string
	Threshold float64
}

// Rules are the checks that matter most. Each returns a single number.
var Rules = []Alert{
	{
		Name: "connections_used_ratio",
		SQL: `SELECT count(*)::float8 / current_setting('max_connections')::float8
FROM pg_stat_activity WHERE backend_type = 'client backend'`,
		Threshold: 0.8,
	},
	{
		Name: "oldest_transaction_seconds",
		SQL: `SELECT coalesce(max(extract(epoch FROM now() - xact_start)), 0)
FROM pg_stat_activity WHERE state <> 'idle' AND backend_type = 'client backend'`,
		Threshold: 300,
	},
	{
		Name: "idle_in_transaction_seconds",
		SQL: `SELECT coalesce(max(extract(epoch FROM now() - state_change)), 0)
FROM pg_stat_activity WHERE state = 'idle in transaction'`,
		Threshold: 60,
	},
	{
		Name: "replay_lag_seconds",
		SQL: `SELECT coalesce(max(extract(epoch FROM replay_lag)), 0)
FROM pg_stat_replication`,
		Threshold: 30,
	},
	{
		Name: "xid_age_ratio",
		SQL: `SELECT max(age(datfrozenxid))::float8 / 2000000000
FROM pg_database`,
		Threshold: 0.5,
	},
	{
		Name: "dead_tuple_ratio",
		SQL: `SELECT coalesce(max(n_dead_tup::float8 / nullif(n_live_tup + n_dead_tup, 0)), 0)
FROM pg_stat_user_tables WHERE n_live_tup + n_dead_tup > 100000`,
		Threshold: 0.2,
	},
}

// Result is the outcome of one rule.
type Result struct {
	Name   string
	Value  float64
	Firing bool
}

// Run evaluates every rule once.
func Run(ctx context.Context, db *sql.DB) ([]Result, error) {
	out := make([]Result, 0, len(Rules))
	for _, r := range Rules {
		var v sql.NullFloat64
		if err := db.QueryRowContext(ctx, r.SQL).Scan(&v); err != nil {
			return nil, fmt.Errorf("rule %s: %w", r.Name, err)
		}
		out = append(out, Result{Name: r.Name, Value: v.Float64, Firing: v.Float64 >= r.Threshold})
	}
	return out, nil
}

otelsql wraps database/sql so every query becomes a span and pool statistics become metrics, without touching call sites. The libraries are github.com/XSAM/otelsql (a database/sql wrapper) and, for pgx, github.com/exaring/otelpgx. This block is not part of the compiled snippets, so check option names against the version you install.

go
db, err := otelsql.Open("pgx", dsn,
    otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL),
    otelsql.WithSQLCommenter(true), // inject traceparent as a trailing comment
)
if err != nil {
    return err
}
// pool metrics: db.client.connection.* from DBStats
reg, err := otelsql.RegisterDBStatsMetrics(db, otelsql.WithAttributes(semconv.DBSystemNamePostgreSQL))
if err != nil {
    return err
}
defer reg.Unregister()

Pass the request context.Context through the whole chain. A fresh context.Background() inside a repository makes the query untraceable, and a client timeout can no longer stop the wait.

Laravel ​

Before: the service runs the query and nothing else.

php
<?php

// app/Services/OrderQueries.php. Nothing here records how long the query took,
// how often it runs, or what it does to the database under load.
namespace App\Services;

use Illuminate\Support\Facades\DB;

final class OrderQueries
{
    /** @return array<int, object> */
    public function recentForUser(int $userId): array
    {
        return DB::select(
            'select id, status, total_cents from orders where user_id = ? order by created_at desc limit 50',
            [$userId]
        );
    }
}

After: DB::listen receives every query ($query->sql, $query->bindings, $query->time). Log the SQL with its ? placeholders and the duration, never the bindings. DB::whenQueryingForLongerThan is a per-request budget: Laravel "can invoke a closure or callback of your choice when it spends too much time querying the database during a single request." It cannot tell you which single query was slow.

php
<?php

// app/Providers/AppServiceProvider.php
namespace App\Providers;

use Illuminate\Database\Connection;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

final class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        //
    }

    public function boot(): void
    {
        // Runs for every query. Log the SQL with its ? placeholders and the
        // duration, never the bindings: they carry emails, tokens and other
        // personal data. $query->time is Laravel's per-query duration.
        DB::listen(function (QueryExecuted $query): void {
            if ($query->time < 200) {
                return;
            }

            Log::warning('slow query', [
                'sql' => $query->sql,
                'time' => $query->time,
            ]);
        });

        // Runs once per request when cumulative query time passes 500 ms.
        // It is a per-request budget, not a per-statement threshold.
        DB::whenQueryingForLongerThan(500, function (Connection $connection, QueryExecuted $event): void {
            Log::warning('request spent too long in queries', [
                'last_sql' => $event->sql,
            ]);
        });
    }
}

The Artisan command reads pg_stat_statements through the same connection:

php
<?php

// app/Console/Commands/TopQueriesCommand.php
// Requires: CREATE EXTENSION pg_stat_statements; (and the module in shared_preload_libraries).
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class TopQueriesCommand extends Command
{
    protected $signature = 'db:top-queries {--limit=10 : How many statements to show}';

    protected $description = 'List the most expensive normalized statements from pg_stat_statements';

    public function handle(): int
    {
        $limit = max(1, (int) $this->option('limit'));

        $sql = <<<'SQL'
            select left(query, 80) as query,
                   calls,
                   round(total_exec_time::numeric, 1) as total_ms,
                   round(mean_exec_time::numeric, 2) as mean_ms
            from pg_stat_statements
            order by total_exec_time desc
            limit ?
            SQL;

        $rows = DB::select($sql, [$limit]);

        $this->table(
            ['query', 'calls', 'total_ms', 'mean_ms'],
            array_map(fn (object $row): array => (array) $row, $rows),
        );

        return self::SUCCESS;
    }
}

A second command lists blocked sessions through pg_blocking_pids:

php
<?php

// app/Console/Commands/BlockingCommand.php
// Shows who blocks whom right now, using pg_blocking_pids().
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class BlockingCommand extends Command
{
    protected $signature = 'db:blocking';

    protected $description = 'List sessions that are blocked and the sessions blocking them';

    public function handle(): int
    {
        $sql = <<<'SQL'
            select blocked.pid                                as blocked_pid,
                   blocked.application_name                   as blocked_app,
                   left(blocked.query, 60)                    as blocked_query,
                   round(extract(epoch from now() - blocked.query_start)::numeric, 1) as waiting_s,
                   blocker.pid                                as blocker_pid,
                   blocker.application_name                   as blocker_app,
                   blocker.state                              as blocker_state,
                   left(blocker.query, 60)                    as blocker_query
            from pg_stat_activity as blocked
            join lateral unnest(pg_blocking_pids(blocked.pid)) as b(pid) on true
            join pg_stat_activity as blocker on blocker.pid = b.pid
            where blocked.wait_event_type = 'Lock'
            order by waiting_s desc
            SQL;

        $rows = DB::select($sql);

        if ($rows === []) {
            $this->info('Nothing is blocked.');

            return self::SUCCESS;
        }

        $this->table(
            ['blocked_pid', 'blocked_app', 'blocked_query', 'waiting_s', 'blocker_pid', 'blocker_app', 'blocker_state', 'blocker_query'],
            array_map(fn (object $row): array => (array) $row, $rows),
        );

        return self::FAILURE;
    }
}

application_name in config/database.php is the cheapest correlation key:

php
<?php

// config/database.php (excerpt). application_name shows up in
// pg_stat_activity.application_name, in the server log through %a in
// log_line_prefix, and in pg_stat_replication for replicas.
return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'app'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            'charset' => 'utf8',
            'prefix' => '',
            'search_path' => 'public',
            'sslmode' => 'prefer',
            // One name per deployable, so a blocked query points at a service
            // and a role (web, queue worker, scheduler), not just at "php".
            'application_name' => env('DB_APPLICATION_NAME', 'shop-web'),
        ],
    ],
];

Laravel Telescope records each request's queries in development and flags slow ones (QueryWatcher, slow in milliseconds). Laravel Pulse is for production: its Slow Queries card aggregates by SQL with a threshold (PULSE_SLOW_QUERIES_THRESHOLD). Both read the same query events as DB::listen. Both write to storage, so sample or restrict them on busy production systems, and do not enable Telescope there by default. The excerpt below shows the settings; verify the key names in the installed versions.

php
<?php

// Environment and config excerpts for the two first-party Laravel tools.
// .env
//   PULSE_SLOW_QUERIES_THRESHOLD=1000     # milliseconds; Pulse "Slow Queries" card
//   TELESCOPE_QUERY_SLOW=100              # milliseconds; Telescope tags slow queries
//
// config/telescope.php (excerpt)
return [
    'watchers' => [
        Laravel\Telescope\Watchers\QueryWatcher::class => [
            'enabled' => env('TELESCOPE_QUERY_WATCHER', true),
            'ignore_packages' => true,
            'slow' => 100,
        ],
    ],
];

For OpenTelemetry in PHP there is the open-telemetry/opentelemetry-auto-laravel auto-instrumentation, which creates database spans; it relies on the PDO instrumentation (opentelemetry-auto-pdo).

Alerting ​

Alert on symptoms users feel and on resources that will run out, with a fixed action for each. Alert on rates and trends, not single readings: a cache hit ratio dipping for ten minutes after a restart is normal.

AlertSourceWarningPageFirst action
Connections usedpg_stat_activity_count / pg_settings_max_connections> 70% for 5 min> 90%Pool size, leaks, idle in transaction
Long transactionnow() - xact_start max> 5 min> 30 minpg_blocking_pids, find the owner by application_name
Idle in transactionnow() - state_change where state is idle in transaction> 1 min> 10 minFix the code; set idle_in_transaction_session_timeout
Lock waitssessions with wait_event_type = 'Lock'> 5 sessions for 1 min> 30 sessionsBlocker query, lock order
Deadlocksrate(pg_stat_database_deadlocks[5m])> 0sustainedLock ordering and retries (Deadlocks)
Replication lagreplay_lag / pg_replication_lag_seconds> 5 s> 30 sReplica I/O, long standby queries, WAL volume
Inactive slotpg_replication_slots where not activeanyWAL > 20% of diskDrop the slot or restore the consumer
Dead tuplesn_dead_tup ratio> 10%> 30% on hot tablesAutovacuum settings, long transactions holding backend_xmin
Wraparoundage(datfrozenxid)> 500 M> 1.5 BVacuum freeze; see MVCC
Cache hit / IO waitsblks_hit, IO waitstrend down 10%sustainedWorking set, new scan, index
Disk and WALfilesystem, pg_wal size> 70%> 85%Slots, archive failures, big transactions
Top statement regressionmean_exec_time per queryid vs baseline+50%+200%Plan change, stats
Pool saturation (app)DBStats utilisation and wait> 80%> 95% with waitsPool size, query time
Error ratexact_rollback, SQLSTATE 53300, 40001risespikePer code
yaml
# Prometheus alert rules (names from postgres_exporter defaults).
groups:
  - name: postgres
    rules:
      - alert: PostgresConnectionsHigh
        expr: sum(pg_stat_activity_count) / max(pg_settings_max_connections) > 0.8
        for: 5m
        labels: {severity: warning}
      - alert: PostgresDeadlocks
        expr: rate(pg_stat_database_deadlocks[5m]) > 0
        for: 10m
        labels: {severity: warning}
      - alert: PostgresReplicaLag
        expr: pg_replication_lag_seconds > 30
        for: 5m
        labels: {severity: page}
      - alert: PostgresDown
        expr: pg_up == 0
        for: 1m
        labels: {severity: page}

The decision tree below is the order to ask the questions when a latency alert fires.

Sessions waitingon Lock events?Connections nearmax_connections?replay_lag orflush_lag high?Dead tuples or xidage rising?IO waits and lowcache hit?pg_blocking_pids,end the longblocker or fix orderidle in transaction?pool leak? checkapplication_namepg_stat_replication,replica I/O, queryconflicts, WAL volumebackend_xmin, oldtransaction, slot,autovacuum stucktop by shared_blks_read,missing index, planchange, working setNo match: diff pg_stat_statements before and after the deploy, then read the plan (auto_explain)nonononoyesyesyesyesyes

SLOs and error budgets. Give each critical operation a service-level objective (for example, 99% of checkout queries under 100 ms over 30 days) and alert on the burn rate of the error budget instead of on every spike. Capacity dashboards chart the slow-moving saturation series: database and table size growth, WAL per day, peak connections, peak IOPS, and the date at which each hits its limit.

Correlating app traces with database waits ​

A trace says "this request spent 900 ms in the database"; the server says "a session waited 850 ms on a lock". The join key is the label you attach on the way in.

KeyWhere to set itWhere it appearsCardinality
application_nameConnection string or session SET application_name (63 chars)pg_stat_activity, log with %a, pg_stat_replicationlow: one per service role
SQL comment (SQLCommenter)Appended to each statementlog, pg_stat_activity.query, cloud query insightsmedium: route, controller
traceparent in the commentPer statementlog lines, auto_explain outputhigh: only in logs and traces
queryidComputed by the serverpg_stat_statements, pg_stat_activity.query_id, EXPLAIN VERBOSE, log with compute_query_idper shape
SET LOCAL ... custom GUCs (for example app.request_id)At transaction startcurrent_setting('app.request_id') in audit triggers and logshigh
text
     Application / trace                            PostgreSQL
1    span http.server GET /checkout  trace=4bf9…
2    pool wait 30 ms (DBStats.WaitDuration)
3    BEGIN; SELECT … FOR UPDATE /*route='/checkout',traceparent='00-4bf9…'*/   app=shop-web
4                                                    pg_stat_activity: wait_event_type=Lock, application_name=shop-web
5                                                    log (log_lock_waits): process 77 still waiting … Statement: … /*route='/checkout',traceparent='00-4bf9…'*/
6    span db  SELECT orders  duration 912 ms         pg_blocking_pids(77) -> {61}, 61 = app=shop-worker, idle in transaction
7    -- query the log or trace store for trace=4bf9…: the request, the statement and the blocker meet in one place

Rules: one application_name per deployable and role (shop-web, shop-queue, shop-migrate); keep high-cardinality values (user id, trace id) out of metric labels and in the comment or span only; never put personal data in a comment, since it lands in the log.

Solving the classic incidents ​

Each row is a symptom you meet in production, the observation that proves the cause, and the fix. The detailed fixes live in the sibling pages.

SymptomProof (view or log)CauseFix
p99 doubled after a deploypg_stat_statements diff by queryid; auto_explain planNew query or plan changeIndex, rewrite, ANALYZE; see Query Planning
Everything slow, CPU lowMany Lock waits; pg_blocking_pidsOne blocker holding locksEnd it, add idle_in_transaction_session_timeout, fix the code
FATAL: too many connections (SQLSTATE 53300)pg_stat_activity by state and application_namePool too large or leakingPooler and sizing; see Connection Pooling
Table size grows, queries slown_dead_tup, last_autovacuum, old backend_xminVacuum blocked by a long transaction or a slotEnd the transaction, drop the stale slot, tune autovacuum
Replica returns stale datareplay_lag, pg_stat_replicationReplica I/O, long standby query, WAL burstThrottle, tune, route read-your-writes to the primary
Disk full of WALpg_replication_slots retained size; archive errorsInactive slot or failing archiverFix the consumer or drop the slot
Regular I/O spikespg_stat_checkpointer, log_checkpointsForced checkpointsRaise max_wal_size, spread with checkpoint_completion_target
N+1 from the ORMcalls very high, mean_exec_time tinyLazy loadingEager load or batch; see ORM Pitfalls
Sorts spill to disktemp_blks_written, log_temp_fileswork_mem too low or a missing indexIndex for the order, raise work_mem per role
Deadlock errors (40P01, MySQL 1213)pg_stat_database.deadlocks; LATEST DETECTED DEADLOCKOpposite lock orderLock ordering, retry; see Deadlocks
sql
-- Kill sessions stuck idle in a transaction for more than five minutes (review first, then run).
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE state = 'idle in transaction' AND now() - state_change > interval '5 minutes'
  AND backend_type = 'client backend';

-- Guard rails per role, so one service cannot hold the database hostage.
ALTER ROLE shop_web SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE shop_web SET statement_timeout = '15s';
ALTER ROLE shop_web SET lock_timeout = '3s';

Choosing what to use ​

SituationUseExtraReason
New PostgreSQL serverpg_stat_statements, log_min_duration_statement, log_lock_waits, track_io_timing, exporterauto_explain with a sampleCheap to start; costly to add after the incident
Server is slow nowpg_stat_activity, then pg_blocking_pidspg_wait_sampling if installedLive state first, history second
Slower after deployDiff pg_stat_statements by queryidauto_explain planRegression found by shape, not by guess
Plan fast by hand, slow in prodauto_explain.log_min_duration + log_analyzesample_rateReal parameters, real cache state
Rare 30-second outlierlog_min_duration_statementmax_exec_time, tracesCounters average it away
Offline review of a weekpgBadgerpt-query-digest on MySQLWorks from logs alone
Managed cloud databaseProvider insights (Performance Insights, Query Insights)Exporter if allowedExtensions may be restricted
MySQLperformance_schema digests, sys, slow logpt-query-digestAggregate plus individual events
Need OS-level cost per querypg_stat_kcacheCPU vs disk
AlertingFew symptom alerts plus saturationSLO burn rateAvoids alert fatigue

Cost of observing. log_min_duration_statement = 0 logs every statement, which is expensive on busy servers; use log_min_duration_sample. pg_stat_statements costs shared memory and a small per-statement overhead. track_io_timing adds a clock read per I/O (negligible on current hardware; measure with pg_test_timing). auto_explain.log_analyze adds instrumentation to every statement. High-cardinality metric labels cost Prometheus memory.

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

One application, one PostgreSQL. Start with pg_stat_statements, three log settings, the exporter and one Grafana dashboard. A Laravel monolith adds DB::listen with a threshold and Pulse; a Go service adds Observed and DBStats. The whole problem fits in one screen: top five statements, connection count, oldest transaction. The most common finding at this stage is an N+1 pattern (high calls, low mean_exec_time) and an idle in transaction leak.

Modular monolith / multiple databases ​

Several modules share one server or use one schema each. pg_stat_statements is server-wide, so filter by dbid and role. Use a role or application_name per module (billing, catalog) so a lock or a top query names its owner. pg_stat_user_tables per schema tells you which module owns the bloat.

Microservices ​

Each service has its own database, so each needs its own exporter and dashboard, but one request crosses several. The trace is the connective tissue: every database span carries db.system.name, db.namespace and server.address, and traceparent goes into the SQL comment. Example: checkout calls inventory and payments; the trace shows 700 ms in inventory's UPDATE stock; its pg_stat_activity shows Lock: transactionid on application_name=inventory-worker. Standardise names and labels across services, or dashboards cannot be compared.

Distributed data: replicas, caches, pooled and sharded databases ​

With read replicas, monitor each node and the lag (Replication): a stale read looks like a correctness bug but is a lag alert you did not have. Behind a pooler (PgBouncer, see Connection Pooling), pg_stat_activity shows the pooler's server connections, not your clients; use the pooler's own statistics (SHOW POOLS, SHOW STATS) and keep application_name working (track_extra_parameters in recent PgBouncer, or per-session SET). A cache in front hides load from the database, so a cache outage appears as a database traffic spike: alert on both. With sharding or distributed SQL (Citus, CockroachDB, Spanner), you need per-node statistics and an aggregated view (citus_stat_statements, CockroachDB's SQL Activity page).

Scaling path ​

ScaleObservability design
1x (one server)pg_stat_statements, three log settings, exporter, one dashboard, 5 alerts
10x (replicas, pooler)Per-node dashboards, lag alerts, pooler stats, auto_explain with sampling, slow-log shipping to Loki or Elastic
100x (many clusters, many teams)Fleet view (per cluster golden signals), SLOs per service, central OpenTelemetry Collector with sampling and redaction, queryid fingerprint registry that maps a shape to a code owner, long retention for capacity forecasts

Lab ​

Everything runs on a laptop with Docker and pgbench (shipped with PostgreSQL). Outputs are illustrative; yours will differ.

Setup (terminal 1). Start PostgreSQL with pg_stat_statements, and set auto_explain to sample later.

bash
docker run -d --name obs -e POSTGRES_PASSWORD=pw -p 5432:5432 postgres:17 \
  -c shared_preload_libraries='pg_stat_statements,auto_explain' \
  -c pg_stat_statements.track=all -c track_io_timing=on \
  -c log_min_duration_statement=200 -c log_lock_waits=on \
  -c log_line_prefix='%t [%p] app=%a '
export PGPASSWORD=pw
psql -h localhost -U postgres -c "CREATE EXTENSION pg_stat_statements;"
pgbench -h localhost -U postgres -i -s 20 postgres      # 2 million rows in pgbench_accounts

Experiment 1: run load and find the top queries (terminal 2).

bash
pgbench -h localhost -U postgres -c 8 -j 4 -T 60 -P 10 postgres
sql
SELECT left(query, 60) AS query, calls, round(total_exec_time::numeric, 1) AS total_ms,
       round(mean_exec_time::numeric, 3) AS mean_ms, rows
FROM pg_stat_statements WHERE query NOT LIKE '%pg_stat%' ORDER BY total_exec_time DESC LIMIT 5;
-- UPDATE pgbench_accounts SET abalance = abalance + $1 WHERE aid = $2   ~ top by total_ms
-- UPDATE pgbench_branches ... (the hot row: only 20 branches, so many sessions wait)

The branches UPDATE is cheap per call but waits on row locks, because 8 clients update the same 20 rows. Check SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state='active' GROUP BY 1,2; during the run: expect Lock | transactionid.

Experiment 2: make a query slow and see the missing index.

sql
SELECT pg_stat_statements_reset();
SELECT count(*) FROM pgbench_accounts WHERE bid = 7;      -- no index on bid: sequential scan
SELECT relname, seq_scan, seq_tup_read, idx_scan FROM pg_stat_user_tables WHERE relname = 'pgbench_accounts';
-- seq_scan increased by 1, seq_tup_read by ~2 000 000

Experiment 3: add auto_explain and read a plan from the log.

sql
LOAD 'auto_explain';
SET auto_explain.log_min_duration = '100ms';
SET auto_explain.log_analyze = on;
SET auto_explain.log_buffers = on;
SELECT count(*) FROM pgbench_accounts WHERE bid = 7;
bash
docker logs obs 2>&1 | grep -A 14 'duration:' | tail -n 30
# LOG:  duration: 188.4 ms  plan:
#   Query Text: SELECT count(*) FROM pgbench_accounts WHERE bid = 7;
#   Finalize Aggregate (actual time=188.1..188.1 rows=1 loops=1)
#     -> Gather -> Partial Aggregate
#          -> Parallel Seq Scan on pgbench_accounts (actual time=0.04..177 rows=33333 loops=3)
#               Filter: (bid = 7)   Rows Removed by Filter: 633333
#               Buffers: shared hit=… read=…

Read it from the inside out: a Seq Scan that removes 633 333 rows to keep 33 333 asks for an index. Create it with CREATE INDEX CONCURRENTLY ON pgbench_accounts (bid);, run the query again and compare.

Experiment 4: a blocker you can see. In terminal A: BEGIN; UPDATE pgbench_branches SET bbalance = 0 WHERE bid = 1; and leave it. In terminal B: the same UPDATE (it waits). In terminal C run the blocking query from pg_locks: B is blocked, A is idle in transaction. After 1 s the log shows process … still waiting for ShareLock. End A with ROLLBACK.

Experiment 5: an unused index and a checkpoint. SELECT * FROM pg_stat_user_indexes WHERE idx_scan = 0; lists the indexes pgbench never used. CHECKPOINT; then docker logs obs | grep checkpoint shows the checkpoint complete line.

Common misconceptions ​

BeliefReality
pg_stat_statements shows the slowest queriesIt shows the costliest in total and on average since reset; use max_exec_time and the log for outliers
High cache hit ratio means healthyIt means reads came from memory; a cached full scan is still a full scan
Log every query to find the slow onesLogging is a cost; threshold plus sampling plus aggregates find them with less overhead
The session in active state is workingIt can be active and waiting on a lock or I/O; read wait_event
The blocker is the long queryThe blocker is often idle in transaction and doing nothing
idx_scan = 0 means drop the indexCheck the window, last_idx_scan, and that no constraint depends on it
The exporter shows top queries by defaultstat_statements collector is disabled by default
Server and app latency should matchThe span includes pool wait and the network; both are right
The statement text in a trace is harmlessLiterals can hold personal data; sanitize or parameterize
A SQL comment splits statisticsqueryid ignores comments; only the text differs
More alerts is saferAlert fatigue hides the page that matters; few symptoms, few resources
pg_stat_bgwriter has checkpoint statsSince PostgreSQL 17 they are in pg_stat_checkpointer

Cheat sheet ​

TopicWhat to remember
Golden signalsLatency, traffic, errors, saturation; USE per resource, RED per service
First installshared_preload_libraries='pg_stat_statements', restart, CREATE EXTENSION
Top queriesORDER BY total_exec_time DESC; also calls, rows, shared_blks_read, temp_blks_written
Live viewpg_stat_activity: state, wait_event_type, xact_start, backend_xmin
Blockerspg_blocking_pids(pid); the blocker is often idle in transaction
Slow query loglog_min_duration_statement; sample with log_min_duration_sample
Plans in the logauto_explain.log_min_duration, log_analyze, sample_rate
Lock waitslog_lock_waits = on, reported after deadlock_timeout
Vacuum healthn_dead_tup, last_autovacuum, age(datfrozenxid)
I/Opg_stat_io (16), pg_stat_checkpointer (17), track_io_timing
Replicationreplay_lag, pg_wal_lsn_diff, slots retain WAL
MySQLevents_statements_summary_by_digest, sys, slow log, pt-query-digest
TracesSpan name from summary; db.query.text parameterized or sanitized
Correlationapplication_name, SQLCommenter, traceparent, queryid
AlertsConnections, lag, dead tuples, wraparound, long transactions, deadlocks, burn rate

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why can a 2 ms query cost more than a 2 s query? Must-know ​

Answer

Answer: Total cost is calls times mean_exec_time. A 2 ms query called 5 000 times a second dominates a report that runs once a day. Rank by total_exec_time.

2 — What does normalization in pg_stat_statements do, and what does it hide? Important ​

Answer

Answer: Constants become $1, $2, so queries of one shape share a row and queryid. It hides which literal was slow; use the log or auto_explain.

3 — A session is active and wait_event_type = 'Lock'. What do you do next? Must-know ​

Answer

Answer: Call pg_blocking_pids(pid), look at each blocker's state and xact_start; the blocker is often idle in transaction. Fix the owner (find it by application_name), then consider a lock_timeout or idle_in_transaction_session_timeout.

4 — Why is idle in transaction dangerous even though the session runs nothing? Must-know ​

Answer

Answer: It holds its locks and its snapshot (backend_xmin), so vacuum cannot remove rows it may still see and DDL queues behind it.

5 — Why is a high cache hit ratio not proof of health? Must-know ​

Answer

Answer: It is cumulative, ignores the OS cache and the count of blocks touched; a cached full scan still wastes CPU. Use it as a trend with pg_stat_io and IO waits.

6 — Which parameter logs the plan of a slow statement, and what is the cost? Important ​

Answer

Answer: auto_explain.log_min_duration. With log_analyze every statement is instrumented; reduce it with sample_rate and log_timing = off.

7 — Where did checkpoint statistics go in PostgreSQL 17? Good to know ​

Answer

Answer: To pg_stat_checkpointer (num_timed, num_requested, write_time, sync_time); pg_stat_bgwriter keeps the background writer's counters.

8 — Why must db.query.text be sanitized or parameterized? Must-know ​

Answer

Answer: Literals can contain personal data; the OpenTelemetry convention says collect it by default only if sanitization excludes sensitive information. Parameterized text ($1, ?) contains no values.

9 — How do you link a trace to a database wait? Important ​

Answer

Answer: Set application_name per service, append an SQLCommenter comment with the route and traceparent, and search the log or pg_stat_activity.query; queryid joins to pg_stat_statements.

10 — List the alerts you would set first and why. Must-know ​

Answer

Answer: Connections over 80% of max_connections (saturation), replay lag, deadlocks above zero, long and idle-in-transaction sessions, dead tuples ratio, xid age (wraparound), plus app pool wait; they cover symptoms and resources that run out.

11 — Why does the server's number differ from the span's? Important ​

Answer

Answer: The span includes pool wait, the network round trip and decoding; the server measures execution only.

Glossary ​

TermMeaning
Four golden signalsLatency, traffic, errors, saturation
USE / RED methodUtilisation, saturation, errors per resource / rate, errors, duration per service
pg_stat_statementsContrib module with per-shape statement statistics
queryidHash of the normalized query, the join key across views
NormalizationReplacing constants with $1, $2 so shapes group
total_exec_time, mean_exec_timeSummed and average execution time in ms
shared_blks_hit / shared_blks_readBlocks found in shared_buffers / read from the OS
pg_stat_activityOne row per backend: state, wait, transaction ages
wait_event_type, wait_eventWhat a backend waits for: Lock, LWLock, IO, Client, IPC…
idle in transactionOpen transaction with no running statement; holds locks and snapshot
backend_xminOldest snapshot a backend holds; blocks vacuum
pg_locks, pg_blocking_pidsLock list; function returning the blockers of a pid
pg_stat_user_tables / _indexesScan, tuple, vacuum counters per table and index
seq_scan, idx_scanSequential and index scans started
n_dead_tupDead tuples awaiting vacuum
pg_stat_ioI/O by backend type, object and context (PostgreSQL 16)
pg_stat_checkpointer, pg_stat_bgwriterCheckpoint (17) and background writer counters
pg_stat_replication, replay_lagPrimary's view of standbys and their lag
Cache hit ratioblks_hit / (blks_hit + blks_read)
log_min_duration_statementLog statements slower than a threshold
log_lock_waits, log_checkpointsLog long lock waits, log each checkpoint
auto_explainModule that logs plans of slow statements
pgBadgerPerl log analyser producing an HTML report
pg_stat_kcachePer-statement OS reads, writes, CPU
pg_wait_samplingWait event sampling extension
postgres_exporterPrometheus exporter for PostgreSQL
Grafana, AlertmanagerDashboards, alert routing
performance_schemaMySQL's instrumentation database
events_statements_summary_by_digestMySQL per-digest statement summary
data_locks, data_lock_waitsMySQL 8 InnoDB lock tables
sys schemaReadable views over performance_schema
Slow query log, pt-query-digestMySQL slow statements; Percona digest tool
SHOW ENGINE INNODB STATUSInnoDB internal report incl. latest deadlock
OpenTelemetry, semantic conventionsTelemetry standard and its attribute names
db.query.text, sanitizationStatement attribute; removing literals before export
SQLCommenterTrailing SQL comment carrying route and trace context
application_nameSession label shown in pg_stat_activity and logs
DBStats, otelsqlGo pool statistics; OpenTelemetry wrapper for database/sql
DB::listen, whenQueryingForLongerThanLaravel query hooks
Telescope, PulseLaravel debugging and production monitoring tools
Wraparound ageage(datfrozenxid), distance to the xid limit
Burn rateSpeed at which an SLO error budget is used

References ​

Built by Morteza Negahi