Appearance
Real-Time Performance Monitoring
pg_stat_statements Deep Dive
sql
-- PostgreSQL 18
-- Enable (once): set shared_preload_libraries = 'pg_stat_statements' in postgresql.conf, restart, then run in each database:
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
-- Top queries by total time (counters are cumulative since the last pg_stat_statements_reset(); resetting erases the history, so avoid it on a shared server)
SELECT query, calls, total_exec_time, mean_exec_time
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;
-- Identify issues:
-- High total_exec_time + High calls = URGENT
-- High mean_exec_time + Low calls = Lower priority
-- Increasing calls over time = Growing volume
-- Illustrative example (made-up numbers, not a measurement):
-- Query: 50,000 ms total, 10,000 calls, 5 ms/call
-- Impact: 50 seconds of total execution time over the period you measured
-- Action: Add an index to cut 5 ms/call toward 0.1 ms/call, then re-measureQuery Ranking & Analysis
sql
-- Rank by consistency (low variance = predictable)
SELECT query,
stddev_exec_time / NULLIF(mean_exec_time, 0) as variance_ratio
FROM pg_stat_statements
WHERE stddev_exec_time > 100
ORDER BY variance_ratio DESC;
-- High variance: Sometimes fast, sometimes slow
-- ├─ Cause: work_mem spilling, cache misses
-- └─ Action: Investigate inconsistency
-- Frequency analysis
SELECT query, calls FROM pg_stat_statements
ORDER BY calls DESC
LIMIT 10;
-- High-frequency queries: Even 10ms improvement = major impactIndex Usage Statistics
sql
-- PostgreSQL 18
SELECT indexrelname, idx_scan, idx_tup_read, idx_tup_fetch,
ROUND(100.0 * idx_tup_fetch / NULLIF(idx_tup_read, 0), 2) as fetch_ratio
FROM pg_stat_user_indexes
ORDER BY idx_scan DESC;
-- Red flags:
-- idx_scan = 0 since the last stats reset: candidate for REVIEW, not an automatic drop.
-- Check a longer window, standbys (their counters are separate), and whether the index backs a PRIMARY KEY / UNIQUE / FK constraint.
-- idx_tup_read >> idx_tup_fetch is normal for bitmap scans and index-only scans (no heap fetch counted); not by itself a sign of inefficiency
-- Large index, zero scans: Waste of space
-- Cache efficiency (shared_buffers hits only; a "read" may still be served by the OS cache)
SELECT indexrelname, idx_blks_hit, idx_blks_read,
ROUND(100.0 * idx_blks_hit / NULLIF(idx_blks_hit + idx_blks_read, 0), 2) as cache_ratio
FROM pg_statio_user_indexes
WHERE idx_blks_read + idx_blks_hit > 0;
-- Reference target: >99% for frequently used indexes (rule of thumb; measure the baseline of your own system first)Cache Hit Ratio Monitoring
sql
-- PostgreSQL 18
-- Cache ratio over user tables (heap blocks only; counters since the last stats reset)
SELECT
ROUND(100.0 * sum(heap_blks_hit) / NULLIF(sum(heap_blks_hit) + sum(heap_blks_read), 0), 2) as table_cache_hit_pct
FROM pg_statio_user_tables;
-- Reference ranges (rule of thumb; measure the baseline of your own system first):
-- >99% = Excellent
-- 90-99% = Good
-- 80-90% = Watch (compare with your own baseline)
-- <80% = Poor (need optimization)
-- If low: working set larger than shared_buffers (and the OS cache), or many cold/sequential reads
-- A "read" here may still be served from the OS page cache; use track_io_timing / pg_stat_io for real disk timeBloat Detection & Alerting
sql
-- PostgreSQL 18
SELECT relname, n_dead_tup, n_live_tup,
ROUND(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) as dead_ratio,
CASE
WHEN 100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0) > 50 THEN 'CRITICAL'
WHEN 100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0) > 20 THEN 'HIGH'
ELSE 'OK'
END as severity
FROM pg_stat_user_tables
ORDER BY dead_ratio DESC NULLS LAST;
-- Alert thresholds (reference only; autovacuum normally handles this, measure the baseline of your system first):
-- >50%: investigate now (is autovacuum running / blocked by a long transaction?), VACUUM if needed
-- >20%: schedule a VACUUM or tune autovacuum for the table
-- >10%: Monitor
-- n_dead_tup is an estimate and dead tuples are not the same as physical bloat: confirm with pgstattuple_approx() belowpgstattuple: Complete Metrics Reference
Purpose: pgstattuple provides precise, low-level table and index statistics at the page level. Unlike pg_stat_user_tables (n_live_tup / n_dead_tup are documented as "Estimated number of live/dead rows", kept from counters), pgstattuple scans the entire relation for exact metrics. Needs superuser or the pg_stat_scan_tables role.
⚠️ Warning: pgstattuple() performs a full table scan → slow on large tables, a WHERE clause does not reduce the scan; use pgstattuple_approx() or run off-peak.
Installation & Basic Usage
Fixture used by every block below (run once; the later blocks use orders, orders_pkey and idx_orders_customer):
sql
-- PostgreSQL 18
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE IF NOT EXISTS orders (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id int,
created_at timestamptz DEFAULT now()
);
INSERT INTO orders (customer_id) SELECT g % 1000 FROM generate_series(1, 200000) g;
CREATE INDEX IF NOT EXISTS idx_orders_customer ON orders (customer_id);
ANALYZE orders;sql
-- Install extension (one-time per database)
CREATE EXTENSION IF NOT EXISTS pgstattuple;
-- Check if installed
\dx pgstattuple
-- Basic usage: table statistics
SELECT * FROM pgstattuple('orders');
-- Basic usage: index statistics
SELECT * FROM pgstattuple('orders_pkey');
-- Check specific index by name
SELECT * FROM pgstattuple('idx_orders_customer');Table Metrics: pgstattuple()
Function signature: pgstattuple(regclass) → record
sql
-- PostgreSQL 18
SELECT * FROM pgstattuple('orders');Returned columns:
text
┌─────────────────────┬───────────┬──────────────────────────────────┐
│ Column │ Type │ Description │
├─────────────────────┼───────────┼──────────────────────────────────┤
│ table_len │ bigint │ Physical table size (bytes) │
│ tuple_count │ bigint │ Number of live tuples │
│ tuple_len │ bigint │ Total length of live tuples │
│ tuple_percent │ float │ % of table used by live tuples │
│ dead_tuple_count │ bigint │ Number of dead tuples │
│ dead_tuple_len │ bigint │ Total length of dead tuples │
│ dead_tuple_percent │ float │ % of table used by dead tuples │
│ free_space │ bigint │ Free space in pages (bytes) │
│ free_percent │ float │ % of table that is free space │
└─────────────────────┴───────────┴──────────────────────────────────┘Detailed Metrics Explanation:
sql
-- PostgreSQL 18
SELECT
pg_size_pretty(table_len) AS table_size,
tuple_count AS live_tuples,
dead_tuple_count AS dead_tuples,
ROUND(tuple_percent::numeric, 2) AS live_pct,
ROUND(dead_tuple_percent::numeric, 2) AS dead_pct,
ROUND(free_percent::numeric, 2) AS free_pct
FROM pgstattuple('orders');Illustrative output (made-up numbers, not a real run):
text
-- Example healthy table:
table_size | live_tuples | dead_tuples | live_pct | dead_pct | free_pct
-----------+-------------+-------------+----------+----------+---------
50 GB | 100M | 2M | 92.5 | 3.2 | 4.3
Interpretation:
- live_pct = 92.5% -> good density (rows packed efficiently)
- dead_pct = 3.2% -> low bloat (autovacuum working)
- free_pct = 4.3% -> little unused space
-- Example table with a lot of free space (e.g. after a large DELETE whose space was not reused yet):
table_size | live_tuples | dead_tuples | live_pct | dead_pct | free_pct
-----------+-------------+-------------+----------+----------+---------
78 GB | 100M | 0 | 58.3 | 0.0 | 41.7
Interpretation:
- live_pct = 58.3% -> poor density
- dead_pct = 0% -> no dead tuples left (not a VACUUM backlog)
- free_pct = 41.7% -> heap pages hold unused space (deletes/updates not yet reused, or a low fillfactor)
- Random UUIDv4 keys fragment the primary-key B-tree index, not the heap: check it with pgstatindex() belowIndex Metrics: pgstattuple()
Same function works for indexes:
sql
-- PostgreSQL 18
SELECT * FROM pgstattuple('orders_pkey');Returns the same columns, but for index pages:
text
table_len: Index size in bytes
tuple_count: Number of index entries
tuple_len: Total length of index entries
tuple_percent: % of index pages used by entries
free_space: Unused space in index pages
free_percent: % of the index that is unused space
Reference only (measure the baseline of your own index first, e.g. right after REINDEX):
- B-tree leaf pages are filled to fillfactor 90 by default, so density above ~90% is not expected.
- Measured in a PostgreSQL 18 Docker test: 200,000 random UUIDv4 keys, no deletes, no vacuum activity:
pgstattuple('orders_pkey') gave tuple_percent 55.43, free_percent 33.75 (pgstatindex avg_leaf_density 65.83).
Low density alone is not proof of damage; random keys naturally leave pages part-empty.
- Compare against the same index after REINDEX CONCURRENTLY and weigh the size saved before rebuilding.Advanced Function: pgstatindex()
Function signature: pgstatindex(regclass) → record
Purpose: More detailed B-Tree index statistics. B-tree indexes only: other index types raise ERROR: relation "..." is not a btree index (use pgstatginindex for GIN, pgstathashindex for hash).
sql
-- PostgreSQL 18
SELECT * FROM pgstatindex('orders_pkey');Returned columns:
text
┌──────────────────┬────────┬──────────────────────────────────────┐
│ Column │ Type │ Description │
├──────────────────┼────────┼──────────────────────────────────────┤
│ version │ int │ B-Tree version number │
│ tree_level │ int │ Height of B-Tree (1-5 typical) │
│ index_size │ bigint │ Total index size (bytes) │
│ root_block_no │ bigint │ Block number of root page │
│ internal_pages │ bigint │ Number of internal (non-leaf) pages │
│ leaf_pages │ bigint │ Number of leaf pages │
│ empty_pages │ bigint │ Number of empty pages (bloat!) │
│ deleted_pages │ bigint │ Number of deleted pages (bloat!) │
│ avg_leaf_density │ float │ Average leaf page density (%) │
│ leaf_fragmentation│ float │ Leaf page fragmentation (%) │
└──────────────────┴────────┴──────────────────────────────────────┘Detailed Example:
sql
-- PostgreSQL 18
SELECT
pg_size_pretty(index_size) AS size,
tree_level,
leaf_pages,
empty_pages,
deleted_pages,
ROUND(avg_leaf_density::numeric, 2) AS leaf_density_pct,
ROUND(leaf_fragmentation::numeric, 2) AS fragmentation_pct
FROM pgstatindex('orders_pkey');Illustrative output (made-up numbers, not a real run):
text
-- Healthy index (sequential INT primary key):
size | tree_level | leaf_pages | empty | deleted | density | fragmentation
------+------------+------------+-------+---------+---------+--------------
2 GB | 3 | 250,000 | 50 | 0 | 90.0 | 2.1
Interpretation:
- tree_level = 3 -> efficient height (grows logarithmically)
- empty_pages = 50 -> minimal bloat (0.02% of leaf pages)
- deleted_pages = 0 -> no deleted pages
- leaf_density = 90.0% -> as expected for a fresh B-tree (default fillfactor 90)
- fragmentation = 2.1% -> minimal fragmentation
-- Index with random UUIDv4 primary key and many deletes:
size | tree_level | leaf_pages | empty | deleted | density | fragmentation
------+------------+------------+--------+---------+---------+--------------
5 GB | 4 | 625,000 | 125,000| 50,000 | 58.7 | 42.3
Interpretation:
- tree_level = 4 -> taller tree (more page visits per lookup)
- empty_pages = 125,000 -> 20% of leaf pages empty (bloat)
- deleted_pages = 50,000 -> 8% deleted (bloat)
- leaf_density = 58.7% -> poor packing
- fragmentation = 42.3% -> leaf pages far out of physical order
- Diagnosis: random UUIDv4 inserts cause page splits and scattered leaf pages
- Fix: time-ordered keys (UUIDv7/ULID) for new data, or REINDEX CONCURRENTLY to rebuild the existing indexLightweight Alternative: pgstattuple_approx()
Function signature: pgstattuple_approx(regclass) → record
Purpose: Faster approximation: skips pages that the visibility map marks all-visible (assuming no dead tuples there, estimating their free space from the FSM) and fully scans the remaining pages. Dead tuple statistics are exact; live tuple counts and free space are approximate.
sql
-- PostgreSQL 18
SELECT * FROM pgstattuple_approx('orders');Returned columns:
text
┌─────────────────────┬────────┬──────────────────────────────────┐
│ Column │ Type │ Description │
├─────────────────────┼────────┼──────────────────────────────────┤
│ table_len │ bigint │ Physical table size (exact) │
│ scanned_percent │ float │ % of table scanned │
│ approx_tuple_count │ bigint │ Estimated live tuples │
│ approx_tuple_len │ bigint │ Estimated live tuple length │
│ approx_tuple_percent│ float │ Estimated % used by live tuples │
│ dead_tuple_count │ bigint │ Dead tuples (exact) │
│ dead_tuple_len │ bigint │ Dead tuple length (exact) │
│ dead_tuple_percent │ float │ % used by dead tuples (exact) │
│ approx_free_space │ bigint │ Estimated free space │
│ approx_free_percent │ float │ Estimated % free │
└─────────────────────┴────────┴──────────────────────────────────┘Comparison query:
sql
-- PostgreSQL 18
SELECT
'pgstattuple' AS method,
table_len,
tuple_percent,
dead_tuple_percent,
free_percent
FROM pgstattuple('orders')
UNION ALL
SELECT
'pgstattuple_approx',
table_len,
approx_tuple_percent,
dead_tuple_percent,
approx_free_percent
FROM pgstattuple_approx('orders');text
pgstattuple: exact, reads every page
pgstattuple_approx: skips all-visible pages; speed-up depends on how much of the table is all-visible
(large right after VACUUM on a mostly-static table, close to none on a heavily updated one).
Measure on your own table with \timing.
When to use:
pgstattuple: when you need exact metrics (troubleshooting)
pgstattuple_approx: regular monitoring, large tablesMonitoring Dashboard Query
Production-ready query for all tables (reads every page that is not all-visible in each table: run off-peak and test on one table first):
sql
-- PostgreSQL 18
SELECT c.relname AS tablename,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size,
ROUND(s.approx_tuple_percent::numeric, 2) AS live_pct,
ROUND(s.dead_tuple_percent::numeric, 2) AS dead_pct,
ROUND(s.approx_free_percent::numeric, 2) AS free_pct,
CASE
WHEN s.dead_tuple_percent > 20 THEN 'VACUUM NOW'
WHEN s.approx_free_percent > 30 THEN 'FRAGMENTED'
WHEN s.approx_tuple_percent < 80 THEN 'LOW DENSITY'
ELSE 'HEALTHY'
END AS status
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
CROSS JOIN LATERAL pgstattuple_approx(c.oid) s
WHERE n.nspname = 'public'
AND c.relkind = 'r'
AND pg_total_relation_size(c.oid) > 100 * 1024 * 1024 -- >100MB
ORDER BY pg_total_relation_size(c.oid) DESC;Illustrative output (made-up numbers; status cut-offs 20% / 30% / 80% are reference values, measure your own baseline):
text
tablename | total_size | live_pct | dead_pct | free_pct | status
----------+------------+----------+----------+----------+------------
orders | 78 GB | 58.3 | 0.0 | 41.7 | FRAGMENTED
users | 12 GB | 92.1 | 4.2 | 3.7 | HEALTHY
events | 45 GB | 85.2 | 22.3 | 7.5 | VACUUM NOWAlert Thresholds & Actions
Cut-offs below are reference values: measure the baseline of your own system before alerting on them.
sql
-- PostgreSQL 18
-- Rule 1: Dead tuple bloat
SELECT 'orders' AS tablename, dead_tuple_percent
FROM pgstattuple_approx('orders')
WHERE dead_tuple_percent > 20;
-- Action: check why autovacuum is behind, then VACUUM the table
-- Alert: "Table 'orders' has 25% dead tuples, VACUUM needed"
-- Rule 2: Free space in heap pages
SELECT 'orders' AS tablename, approx_free_percent
FROM pgstattuple_approx('orders')
WHERE approx_free_percent > 30;
-- Action: Investigate (large deletes? low fillfactor? index bloat checked separately with pgstatindex)
-- Alert: "Table 'orders' has 42% free space"
-- Rule 3: Low density (tuple_percent)
SELECT 'orders' AS tablename, approx_tuple_percent
FROM pgstattuple_approx('orders')
WHERE approx_tuple_percent < 70;
-- Action: Check for bloat or fragmentation
-- Alert: "Table 'orders' only 58% utilized (poor density)"
-- Rule 4: Index bloat (compare with the index's own baseline after REINDEX, see Index Metrics above)
SELECT 'orders_pkey' AS indexname, avg_leaf_density
FROM pgstatindex('orders_pkey')
WHERE avg_leaf_density < 70;
-- Action: REINDEX CONCURRENTLY if the size saved is worth it
-- Alert: "Index 'orders_pkey' has 62% leaf density"Performance Impact & Best Practices
Cost of pgstattuple (the timings and sizes below are illustrative, not measurements; check yours with \timing):
sql
-- PostgreSQL 18
-- Illustration: 100GB table
-- pgstattuple (full scan):
SELECT * FROM pgstattuple('orders');
-- Time: minutes (reads every page)
-- I/O: 100GB read, size of the table
-- Impact: High disk I/O, use off-peak only
-- pgstattuple_approx (skips all-visible pages):
SELECT * FROM pgstattuple_approx('orders');
-- Time: depends on the share of pages that are not all-visible (seconds on a mostly-static table, close to a full scan on a heavily updated one)
-- I/O: the visibility map (~3MB for 100GB) plus every page that is not all-visible
-- Impact: usually much lower than pgstattuple; still measure before scheduling it on production
-- pgstatindex (reads all index pages):
SELECT * FROM pgstatindex('orders_pkey');
-- Time: grows with index size
-- I/O: the whole index (e.g. 2GB index = 2GB read)
-- Impact: moderate, use during a maintenance windowBest Practices:
sql
-- PostgreSQL 18
-- GOOD: regular monitoring with approx (e.g. hourly, one table at a time, after a test run with \timing):
SELECT * FROM pgstattuple_approx('orders');
-- GOOD: detailed analysis on one specific table when investigating an issue:
SELECT * FROM pgstattuple('orders'); -- replace 'orders' with the table you suspect
-- GOOD: index health check during a maintenance window (B-tree indexes only, else pgstatindex raises an error):
SELECT c.relname AS indexname, (pgstatindex(c.oid)).*
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
JOIN pg_am am ON am.oid = c.relam
WHERE n.nspname = 'public' AND c.relkind = 'i' AND am.amname = 'btree';
-- BAD: exact full scan of every large table (hours of I/O on a 1TB database):
SELECT c.relname, (pgstattuple(c.oid)).*
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE n.nspname = 'public' AND c.relkind = 'r';
-- BAD: running the exact scan during peak hours (for example 2pm production traffic).
-- Do it in a low-traffic window instead.Comparison: pg_stat_user_tables vs pgstattuple
sql
-- PostgreSQL 18
-- pg_stat_user_tables (fast, counter-based estimates):
SELECT
relname,
n_live_tup, -- Estimated
n_dead_tup, -- Estimated
last_vacuum,
last_autovacuum
FROM pg_stat_user_tables
WHERE relname = 'orders';
-- Speed: instant (reads statistics counters)
-- Accuracy: an estimate, no fixed error rate; can drift between VACUUM/ANALYZE runs
-- Use for: Regular monitoring, dashboards
-- pgstattuple (exact counts):
SELECT
tuple_count, -- Exact (full scan)
dead_tuple_count, -- Exact (full scan)
tuple_percent,
dead_tuple_percent,
free_percent
FROM pgstattuple('orders');
-- Speed: slow (full table scan)
-- Accuracy: exact at the moment it reads the pages
-- Use for: Deep analysis, troubleshooting
-- If the two disagree a lot, trust pgstattuple for that moment and look at why autovacuum/analyze is behind.Real-World Troubleshooting Example
Illustrative scenario with made-up numbers, not an incident from a real system.
sql
-- PostgreSQL 18
-- Scenario: Slow queries on 'orders' table
-- Step 1: Quick check with pg_stat_user_tables
SELECT n_live_tup, n_dead_tup,
ROUND(100.0 * n_dead_tup / NULLIF(n_live_tup + n_dead_tup, 0), 2) AS dead_pct
FROM pg_stat_user_tables
WHERE relname = 'orders';
-- Result: dead_pct = 15% (above the 10% "monitor" level used earlier: worth a look, not an emergency)
-- Step 2: Check exact metrics
SELECT
pg_size_pretty(table_len) AS size,
ROUND(tuple_percent::numeric, 2) AS live_pct,
ROUND(dead_tuple_percent::numeric, 2) AS dead_pct,
ROUND(free_percent::numeric, 2) AS free_pct
FROM pgstattuple('orders');
-- Result: size = 78GB, live_pct = 58%, dead_pct = 0%, free_pct = 42%
-- Step 3: Diagnosis
-- dead_pct = 0% -> dead tuples already vacuumed (the 15% in step 1 was a stale estimate)
-- free_pct = 42% -> heap pages hold lots of unused space (earlier deletes/updates, not reused)
-- This is the HEAP. A UUIDv4 key hurts the INDEX, so check the index next.
-- Step 4: Check primary key type
SELECT data_type FROM information_schema.columns
WHERE table_name = 'orders' AND column_name = 'id';
-- Result: uuid (check how ids are generated: random UUIDv4 vs time-ordered UUIDv7)
-- Step 5: Verify with index stats
SELECT avg_leaf_density, leaf_fragmentation
FROM pgstatindex('orders_pkey');
-- Result: density = 59.2%, fragmentation = 40.8%
-- Low density plus scattered leaf pages on a random-UUID key is consistent with page splits;
-- a fresh random-UUID index is already ~65% dense (measured above), so compare with a REINDEX baseline before acting.
-- Step 6: Fix options: REINDEX INDEX CONCURRENTLY for the index; for the heap, rewrite only if the space matters
-- (VACUUM FULL / pg_repack take heavy locks or extra space: plan a window); time-ordered keys (UUIDv7/ULID) for new rows.Summary: pgstattuple Functions
| Function | Speed | Accuracy | Use Case |
|---|---|---|---|
| pgstattuple() | Slow (full scan) | Exact at read time | Deep troubleshooting, exact bloat analysis |
| pgstattuple_approx() | Faster (skips all-visible pages) | Dead tuples exact, live tuples and free space approximate | Regular monitoring, large tables |
| pgstatindex() | Reads all index pages (B-tree only) | Exact at read time | Index health check, bloat detection |
| pg_stat_user_tables | Instant (counters) | Estimate, can drift | Dashboards, quick checks |
Recommendation:
- Regular monitoring:
pgstattuple_approx()on selected tables (test its cost first) - Occasional deep dive:
pgstattuple()+pgstatindex()on a few suspect relations in a low-traffic window, not on every table - Troubleshooting:
pgstattuple()when you need exact numbers
Phải nhớ:
- Mọi hàm pgstattuple đọc cả trang dữ liệu: đo thời gian trên một bảng trước, chạy ngoài giờ cao điểm.
pgstatindex()chỉ chạy với B-tree; mật độ lá thấp chưa chắc là hỏng, so với baseline của chính index đó.- Mọi ngưỡng cảnh báo trong mục này là giá trị tham khảo: đo baseline của hệ thống bạn trước.
Further Reading: