Sub topic 4
Measuring bloat with statistics and pgstattuple
This chapter assumes you know basic SQL and can use psql. It also assumes you have read the earlier chapters on MVCC row versions, dead tuples, and what table bloat costs. Here you will learn to measure bloat. The next chapters cover what to do about it.
Two kinds of measurement
PostgreSQL gives you two ways to see bloat. They differ in cost and accuracy.
| Source | What it reports | Cost | Accuracy |
|---|---|---|---|
| `pg_stat_user_tables` | Counters of live and dead rows, plus vacuum timestamps | Almost free | Estimate |
| `pgstattuple` extension | Dead rows and free space found by reading pages | Reads the whole table | Exact |
| `pgstattuple_approx` | Same figures, skipping pages the visibility map marks all-visible | Reads only pages that may hold dead rows | Close to exact |
A common routine is to watch the cheap statistics all the time. When they look suspicious, run the exact measurement on that one table.
Cheap estimates from pg_stat_user_tables
The view pg_stat_user_tables has one row per user table. PostgreSQL's statistics system maintains these counters as the table is used. The columns that matter for bloat are:
n_live_tup: the estimated number of live rows.n_dead_tup: the estimated number of dead rows that VACUUM has not yet removed.last_vacuumandlast_autovacuum: when a manual and an automatic vacuum last finished on the table.n_mod_since_analyze: rows changed since the lastANALYZE.
This query ranks tables by dead rows and shows what share of the table they make 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_vacuum,
last_autovacuum
FROM pg_stat_user_tables
ORDER BY n_dead_tup DESC
LIMIT 10;The nullif call turns a zero denominator into NULL. Without it, an empty table would raise a division-by-zero error and abort the whole query.
Read the output as a set of clues:
- A high
dead_pctwith a recentlast_autovacuummeans vacuum is running but not removing the rows. Something is probably blocking cleanup, such as a long transaction. A later chapter covers that case. - A high
dead_pctwithlast_autovacuumempty or very old means autovacuum is not reaching the table. Its thresholds may be too lax for the table. - A low
dead_pctdoes not prove the table is compact. Vacuum may have already turned dead rows into free space inside the file.
Limits of the counters
These numbers are estimates, so treat them that way:
- They are incremental counters, not a fresh count.
ANALYZEresetsn_live_tupfrom a sample of the table. - The counters can be lost after a crash or an unclean shutdown, and they restart from zero. A table with a clean-looking row may still be bloated.
- They count rows, not bytes. A table with a few very wide rows can bloat badly while showing small row counts.
- They say nothing about free space that earlier vacuums already created inside the file.
For a size view, add the on-disk sizes. They show how big the table really is, which row counts cannot:
SELECT relname,
pg_size_pretty(pg_relation_size(relid)) AS table_size,
pg_size_pretty(pg_indexes_size(relid)) AS index_size,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_stat_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 10;pg_relation_size counts only the main table file. pg_total_relation_size also includes indexes and TOAST storage, which holds oversized values. A table whose size is much larger than n_live_tup times its average row width suggests bloat.
Exact figures with pgstattuple
The pgstattuple extension is part of the standard contrib modules. It reads the table's pages and reports what it finds in them.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT table_len,
tuple_count,
dead_tuple_count,
dead_tuple_percent,
free_space,
free_percent
FROM pgstattuple('public.orders');Its output columns break the file into three parts:
| Column | Meaning |
|---|---|
| `table_len` | Physical size of the table file in bytes |
| `tuple_count`, `tuple_len` | Live rows and the bytes they occupy |
| `dead_tuple_count`, `dead_tuple_len` | Dead rows not yet removed, and their bytes |
| `dead_tuple_percent` | Dead bytes as a share of `table_len` |
| `free_space`, `free_percent` | Reusable space inside pages, left by earlier cleanup |
Together, live bytes, dead bytes, and free space account for nearly the whole file. The rest is page headers and item pointers.
Privileges and cost
By default only superusers can run these functions. You can grant the built-in pg_stat_scan_tables role to a monitoring user instead. The function reads every page of the table, so on a table of several hundred gigabytes it generates heavy I/O. Run it off-peak, or use the approximate version.
The cheaper variant
pgstattuple_approx uses the visibility map to skip pages where every row is visible to all transactions. Those pages cannot contain dead rows, so skipping them costs nothing in accuracy for the dead-row count.
SELECT table_len,
scanned_percent,
approx_tuple_count,
dead_tuple_count,
dead_tuple_percent,
approx_free_percent
FROM pgstattuple_approx('public.orders');The scanned_percent column tells you how much of the table it really read. On a well-vacuumed table it is small, and the call is fast.
Reading the two numbers: dead space and free space
The most useful skill is telling dead space from free space. They need different responses.
- High
dead_tuple_percentmeans dead rows are still waiting for vacuum. A plainVACUUMfixes this, unless something blocks it. - High
free_percentwith low dead percent means vacuum already ran and the space is reusable, but the file is still large. New inserts and updates will fill it over time. The file shrinks only if the free pages sit at the very end, or if you rewrite the table.
A table with a lot of free space is not necessarily a problem. If the table's write rate would fill that space soon, leave it alone. The space is only a concern if it stays unused, and you can see that from a free percent that stays high over several measurements.
A worked example you can run
This example builds a bloated table on purpose. Autovacuum is turned off for the table so the result is predictable.
CREATE EXTENSION IF NOT EXISTS pgstattuple;
CREATE TABLE bloat_demo (id int PRIMARY KEY, payload text);
ALTER TABLE bloat_demo SET (autovacuum_enabled = false);
INSERT INTO bloat_demo
SELECT g, repeat('x', 100) FROM generate_series(1, 100000) AS g;
SELECT pg_size_pretty(pg_relation_size('bloat_demo')) AS size_after_insert;
UPDATE bloat_demo SET payload = repeat('y', 100);
SELECT pg_size_pretty(pg_relation_size('bloat_demo')) AS size_after_update;
SELECT dead_tuple_count, dead_tuple_percent, free_percent
FROM pgstattuple('bloat_demo');
VACUUM bloat_demo;
SELECT pg_size_pretty(pg_relation_size('bloat_demo')) AS size_after_vacuum;
SELECT dead_tuple_count, dead_tuple_percent, free_percent
FROM pgstattuple('bloat_demo');What you should see:
- After the insert, the table has some size, for example about 13 MB.
- The update writes a new version of every row, so the size roughly doubles.
- The first
pgstattuplecall shows about 100000 dead rows and a dead percent near 50. - After
VACUUM, the size stays about the same. Dead rows drop to 0, andfree_percentrises to near 50.
That last step shows plain VACUUM's behavior. It makes the space reusable but does not shrink the file. Drop the demo table afterwards with DROP TABLE bloat_demo;.
Common mistakes
- Treating
n_dead_tupas a measurement of bloat. It tracks only dead rows, not free space already created by vacuum. - Running
pgstattupleon every table during peak hours. Use the approximate function, or pick the few tables the statistics flagged. - Reacting to a high free percent on a table that is busy enough to reuse it.
- Comparing percentages across tables of very different sizes. A table of 5 MB at 60% bloat matters less than one of 200 GB at 15%. Always read the percentage next to the byte count.
Exercise
A table shows dead_tuple_percent of 1 and free_percent of 45 in pgstattuple. Autovacuum ran an hour ago. Is a plain VACUUM likely to help, and what does the result tell you?
Show answer
A plain VACUUM will not help. Few dead rows remain, so earlier vacuums already cleaned the table. The 45% free space is reusable room inside the file. Whether it is a problem depends on whether the table's write load will fill it. If the free percent stays high across measurements, reclaiming it needs a rewrite (VACUUM FULL, pg_repack, or REPACK), which later chapters cover.
Exercise
Why might you choose pgstattuple_approx over pgstattuple on a 500 GB table that is vacuumed regularly?
Show answer
pgstattuple reads every page, which creates heavy I/O on a large table. pgstattuple_approx skips pages the visibility map marks all-visible. Those pages hold no dead rows, so the dead-row figures stay reliable. On a well-vacuumed table most pages are skipped, so the call is much faster. The cost is that the live row count and free space figures are approximate.
Exercise
pg_stat_user_tables reports n_dead_tup of 2 million, and last_autovacuum was ten minutes ago. What does that combination suggest, and which view would you check next?
Show answer
Autovacuum is reaching the table, but it cannot remove the dead rows, because something holds an old snapshot or horizon. Check pg_stat_activity for long-running transactions (look at backend_xmin and xact_start). Replication slots and prepared transactions are the other usual causes.