dataiotech Labs
Back to Performance Guide
[PostgreSQL]RUNBOOKPostgreSQL 16 / 1718 minSenior DBA / SRE

[PostgreSQL] RUNBOOK: Finding Top 20 Expensive Queries with pg_stat_statements

System CPU is saturated. This runbook identifies the top 20 queries by cumulative execution time, isolates the top 3 offenders, and directs remediation without premature hardware scaling.

Production Incident Scenario

11:42 AM. SRE and Dev teams report latency degradation. CPU is pinned. Guesswork index creation is forbidden. We measure cumulative execution telemetry first.

Overview and Architecture

In production, query performance issues are rarely isolated to a single slow query. Optimizing based on guesswork—such as randomly adding indexes or bumping server resources—creates technical debt and exacerbates resource starvation. Production tuning requires empirical measurement: telemetry first, triage second, modification last.

This runbook guides you through isolating the top 20 statements by cumulative execution time, triaging the top 3 offenders across 4 structural query failure modes, and applying verified remediations using pg_stat_statements.


Scenario

11:42 AM. The application engineering team raises an incident:

*"The application is sluggish and response times are spiking. Is the database bottlenecked?"*

Host CPU utilization is pegged at 88%, but the root cause remains ambiguous. Nobody knows which queries are running, which ones execute at high frequency, or which statement consumes the largest share of cumulative compute time.

At this stage, premature hardware upgrades, random index creation, and ad-hoc configuration changes are strictly prohibited. We measure first.

Objective of this runbook:

Identify the top 20 queries by cumulative runtime, diagnose the top 3 offenders with precision, and execute targeted remediations.

Prerequisites

  • •PostgreSQL 13+ (PostgreSQL 16 / 17 recommended)
  • •Superuser privileges or membership in the pg_monitor default role
  • •The pg_stat_statements extension installed and preloaded

Verify whether the extension exists:

sql
SELECT * FROM pg_extension WHERE extname = 'pg_stat_statements';

If uninstalled, initialize the extension:

sql
CREATE EXTENSION pg_stat_statements;

Critical Note: pg_stat_statements must be declared in shared_preload_libraries within postgresql.conf. Without shared memory allocation, statistics will fail to persist across restarts or will not track statements at all:

sql
SHOW shared_preload_libraries;

If absent, append it to postgresql.conf:

conf
shared_preload_libraries = 'pg_stat_statements' pg_stat_statements.track = all pg_stat_statements.max = 10000

Then restart the PostgreSQL instance during an approved maintenance slot.


Step 1: Evaluating Statistics Freshness

Never interpret pg_stat_statements telemetry without knowing its sampling window and when statistics were last reset.

sql
SELECT (SELECT stats_reset FROM pg_stat_statements_info) AS last_reset_timestamp, (SELECT count(*) FROM pg_stat_statements) AS tracked_distinct_queries, now() - (SELECT stats_reset FROM pg_stat_statements_info) AS sample_duration;

Triage Matrix:

Sample Window DurationOperational Guidance
Sample Duration < 15 minSample too small; wait for steady-state traffic before drawing conclusions.
Sample Duration 1–24 hoursOptimal window; representative of active operational workload.
Sample Duration > 7 daysStale telemetry; legacy query regressions may skew real-time incident analysis.

If the instance recently restarted or metrics are days old, reset the counter to capture a pristine observation window:

sql
SELECT pg_stat_statements_reset();

Observe traffic for 30–60 minutes. Under active incident conditions where waiting is not an option, proceed with existing telemetry but explicitly note: *"Sample Window: X hours"*.


Step 2: Extracting the Top 20 Expensive Queries

This is the primary diagnostic query of this runbook. Statements are sorted by cumulative execution time (`total_exec_time`), because cumulative compute consumption—not isolated outliers—drives database saturation.

sql
SELECT round(total_exec_time::numeric, 2) AS total_time_ms, calls, round(mean_exec_time::numeric, 2) AS mean_time_ms, round(max_exec_time::numeric, 2) AS max_time_ms, round((100.0 * total_exec_time / sum(total_exec_time) OVER ())::numeric, 2) AS pct_of_total_time, rows AS total_rows, round((rows::numeric / NULLIF(calls, 0)), 1) AS rows_per_call, left(query, 250) AS query_snippet FROM pg_stat_statements WHERE query NOT LIKE '%pg_stat_statements%' ORDER BY total_exec_time DESC LIMIT 20;

▸Reading and Categorizing the Output

Production queries fall into four distinct operational profiles. Each profile demands a specific remediation strategy:

▸Type 1: Low Frequency, Extremely Slow

Symptoms:

  • •Low calls count
  • •High mean_time_ms (e.g., > 1,500 ms)
  • •Significant pct_of_total_time

Example: 45 invocations with an average latency of 4.2 seconds.

Root Causes:

  • •Missing index on filtering or join columns
  • •Degradation into a multi-million-row Sequential Scan (Seq Scan)
  • •Stale catalog statistics leading to sub-optimal execution plans

Immediate Action: Execute EXPLAIN (ANALYZE, BUFFERS) to inspect physical node scans.


▸Type 2: High Frequency, Modest Latency (N+1 Query Pattern)

Symptoms:

  • •Astronomical calls count (e.g., 1.5 million calls)
  • •Low individual mean_time_ms (e.g., 6–12 ms)
  • •Huge cumulative total_time_ms

Example: 8 ms × 1,200,000 invocations = 9,600 seconds of CPU time.

This is the signature of the N+1 query pattern.

Root Causes:

  • •Application loops executing ORM lookups per record
  • •Lack of multi-value batching (WHERE id IN (...))
  • •Absence of application-side caching for hot lookup tables

Immediate Action: Audit the application codebase. Reduce invocation counts through batching rather than micro-optimizing individual queries.


▸Type 3: Excessive Row Volume Transfers

Symptoms:

  • •Extremely high rows_per_call (e.g., > 50,000 rows returned per execution)
  • •Massive aggregate total_rows

Root Causes:

  • •Unbounded SELECT * retrieving unnecessary columns (e.g., large text, BLOBs, JSONB)
  • •Missing pagination or offset limits
  • •Inadequate application filtering forcing the database to act as an in-memory filter

Immediate Action: Verify if the client actually requires that row volume. Enforce cursor-based or keyset pagination.


▸Type 4: Uniform Low-Impact Queries (Systemic Non-Query Bottleneck)

Symptoms:

  • •The top 20 queries combined account for less than 30% of total execution time
  • •No single query pattern dominates compute consumption

The bottleneck is outside the query layer.

Root Causes:

  • •Row-level or table-level lock contention
  • •Connection pool exhaustion and client thread queueing
  • •I/O saturation or autovacuum lag causing aggressive page eviction
  • •Noisy neighbors on the underlying hypervisor

Immediate Action: Discontinue query rewriting; immediately inspect pg_stat_activity and pg_locks for wait event blocking chains.


Step 3: Deconstruct the Top 3 Offenders

Select the top 3 statements from your ranking. Perform deep-dive triage on each:

▸3A. Inspect the Physical Execution Plan

sql
EXPLAIN (ANALYZE, BUFFERS) -- Paste exact parameterized query here SELECT * FROM orders WHERE customer_id = 123 AND status = 'open';

Verify 4 Key Signals:

  1. 1Sequential Scan on Large Tables: If a Seq Scan is present with high Rows Removed by Filter, a targeted index is absent.
  2. 2Estimated vs Actual Rows Delta: If the planner estimated 10 rows but processed 100,000, statistics are stale. Run ANALYZE.
  3. 3Buffer Telemetry (`shared hit` vs `shared read`): High read indicates data is read from disk storage rather than the RAM buffer pool.
  4. 4Work Memory Spills: Look for Sort Method: external merge Disk indicating insufficient work_mem.

▸3B. Check for Concurrency and Lock Queues

Inspect whether the target query is actively blocked by concurrent transactions:

sql
SELECT pid, state, wait_event_type, wait_event, now() - query_start AS duration, left(query, 150) AS query_text FROM pg_stat_activity WHERE state <> 'idle' AND query ILIKE '%orders%' ORDER BY query_start;

If wait_event_type = 'Lock', the issue is not execution efficiency, but a blocking lock held by another session.


▸3C. Audit Existing Index Coverage

sql
SELECT indexname, indexdef FROM pg_indexes WHERE tablename = 'orders';

Assessment:

  • •Do indexes cover the predicate columns (WHERE, JOIN)?
  • •Does an index exist that the planner ignores? If so, evaluate column selectivity and statistics targets.

Step 4: Execute Remediations

Choose one precise remediation based on triage findings. Never deploy multiple changes simultaneously.

▸Remediation A: Add an Index (For Type 1)

Test in staging first, then apply to production using non-blocking DDL:

sql
-- Always use CONCURRENTLY in production to prevent table lockouts CREATE INDEX CONCURRENTLY idx_orders_customer_status ON orders (customer_id, status);
Rule: Never execute CREATE INDEX without CONCURRENTLY on production tables. Doing so acquires an AccessExclusiveLock, queueing all reads and writes.

▸Remediation B: Eliminate Iterative Invocations (For Type 2 / N+1)

Provide concrete telemetry to backend developers:

*"The statement executes 1.2M times per hour with an average 8ms latency, consuming 2.6 cumulative CPU hours. Batching this into a single WHERE customer_id = ANY($1) or JOIN will reduce database load by approximately 40%."*

▸Remediation C: Slim Down Projections and Paginate (For Type 3)

  • •Replace SELECT * with explicit column projections.
  • •Eliminate redundant joins.
  • •Enforce keyset (cursor-based) pagination instead of unbounded scans.

▸Remediation D: Shift Focus to Infrastructure and Concurrency (For Type 4)

If query runtime does not explain high latency, inspect systemic locking and dead tuple accumulation:

sql
-- Active Lock Wait Events SELECT wait_event_type, wait_event, count(*) FROM pg_stat_activity WHERE state <> 'idle' GROUP BY 1, 2 ORDER BY 3 DESC; -- Table Bloat and Dead Tuples SELECT relname, n_dead_tup, last_autovacuum FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;

Step 5: Post-Change Verification

Validate results with telemetry rather than assumptions.

Before change: Note the target statement's total_exec_time and calls.

After change: Wait for a 30-minute observation window, then re-query pg_stat_statements:

sql
SELECT query, calls, mean_exec_time, total_exec_time FROM pg_stat_statements WHERE query ILIKE '%orders%' ORDER BY total_exec_time DESC;

Success Criteria:

  • •Has mean_exec_time dropped significantly?
  • •Has its percentage share of cumulative instance runtime reduced?
  • •Have concurrent transactions remained stable without regressions?

If the index or modification failed to improve metrics, revert it immediately. Avoid leaving redundant indexes that inflate storage and degrade write throughput.


5 Common Pitfalls in Production

  1. 1Focusing Solely on `mean_exec_time`: A 5-second report running once a month is harmless; an 8ms query called millions of times per hour saturates hardware. Always prioritize total_exec_time.
  2. 2Ignoring Statistics Freshness: Drawing conclusions from a 3-week-old sample window masks recent performance regressions.
  3. 3Running `CREATE INDEX` Without `CONCURRENTLY`: Acquires an exclusive lock that queues incoming application queries, leading to immediate cascading outages.
  4. 4Creating Indexes Without Reading Query Plans: In many cases, sequential scans stem from stale statistics or type mismatches rather than missing indexes. Always run ANALYZE first.
  5. 5Applying Multiple Changes at Once: Deploying multiple indexes and query rewrites simultaneously obscures which change yielded the improvement or caused collateral regressions.

Operational Checklist

  • pg_stat_statements installed and configured in shared_preload_libraries
  • Telemetry reset timestamp and sampling window verified
  • Top 20 statements ordered by total_exec_time extracted
  • Top 3 offenders categorized into structural failure modes (Type 1–4)
  • EXPLAIN (ANALYZE, BUFFERS) inspected for top offenders
  • Active wait events and lock contention evaluated
  • Single remediation selected and tested in staging
  • Production indexes deployed with CONCURRENTLY
  • Re-measured performance after a 30-minute observation window
  • Before-and-after metric deltas documented and verified

Next Cluster in Series

Following this runbook, proceed to:

[Engine-Agnostic] DEEP DIVE: The N+1 Query Problem and Connection Pool Saturation

This investigates Type 2 failure modes where rapid, individual query lookups silently deplete connection pools and saturate compute capacity.


Related Guides in Series

  • •Pillar: Performance & Query Optimization
  • •Cluster: Reading and Deconstructing EXPLAIN ANALYZE
  • •Cluster: Index Architecture: B-Tree, Hash, GiST, GIN, BRIN Deep Dive
  • •Cluster: Vacuum, Analyze, and Autovacuum Tuning
Operational Checklist

Verify each operational safety check before completing the task: