Sub topic 2
Measuring before tuning: statistics views, EXPLAIN, and logs
This chapter assumes you can run queries in psql, edit postgresql.conf and reload or restart the server, and read a simple EXPLAIN plan. It covers the three sources of evidence you will use for every later change in this tutorial: the cumulative statistics views, EXPLAIN (ANALYZE, BUFFERS), and the server log. Tuning without a measurement is guesswork. With a measurement, you can say what changed and whether it helped.
The working model
PostgreSQL reports its behavior at three levels of detail.
| Source | Scope | Best for | Cost |
|---|---|---|---|
| `pg_settings` | Configuration | Current values and whether a change needs a restart | None |
| `pg_stat_*` views | Cumulative counters since the last reset | Trends across the whole database | Very low |
| `EXPLAIN (ANALYZE, BUFFERS)` | One query | Why a specific query is slow | Runs the query |
| Server log | Individual events | Checkpoints, temporary files, slow statements | Depends on settings |
The statistics views answer "is there a problem somewhere?". EXPLAIN answers "which query, and which plan node?". The log answers "when did it happen?". You usually move through them in that order.
Reading current settings from pg_settings
SHOW returns one value. pg_settings returns the value together with its unit, its source, and the kind of change it needs. Query it for the settings this tutorial covers.
SELECT name, setting, unit, context, pending_restart
FROM pg_settings
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem',
'effective_cache_size', 'max_wal_size', 'checkpoint_timeout',
'random_page_cost', 'max_connections');Two points about the output:
settingis expressed in the baseunit. Forshared_buffersthe unit is usually8kB, so asettingof131072means 1 GB.SHOW shared_buffersprints a friendlier1GB.contexttells you how to apply a change.
| `context` value | How the change takes effect |
|---|---|
| `postmaster` | Requires a server restart. `shared_buffers` and `max_connections` are in this group. |
| `sighup` | A reload is enough. `max_wal_size` and `checkpoint_timeout` are in this group. |
| `superuser` or `user` | Can be changed per session, and can be set per role or database. `work_mem` is in this group. |
pending_restart is true when the configuration file holds a new value for a postmaster setting that the running server has not yet picked up. Check it after editing the file, so you do not assume a change is live when it is not.
Applying and confirming a change
ALTER SYSTEM writes the value to postgresql.auto.conf, which is read after postgresql.conf. A reload applies it to new sessions when the setting does not require a restart.
ALTER SYSTEM SET work_mem = '32MB';
SELECT pg_reload_conf();
SHOW work_mem;Existing sessions keep the value they started with unless they run SET themselves. If SHOW work_mem in a fresh psql session still shows the old value, look at pg_settings.source. A value set with ALTER ROLE or ALTER DATABASE overrides the file and wins.
The cache hit ratio
The view pg_stat_database keeps cumulative counters per database. Two of them describe block requests: blks_hit counts requests served from shared_buffers, and blks_read counts requests that went to the operating system.
SELECT datname,
blks_hit,
blks_read,
round(blks_hit::numeric / nullif(blks_hit + blks_read, 0), 4) AS hit_ratio
FROM pg_stat_database
WHERE datname = current_database();The nullif call avoids a division by zero on a database with no activity. Interpret the ratio with care:
- A block counted in
blks_readmay still have come from the operating system page cache, not from disk. A low ratio therefore does not prove that the disk is busy. - A high ratio on an OLTP workload is normal, often above 0.99. A reporting workload that scans large tables will have a lower ratio, and that can be correct.
- The counters accumulate from the last statistics reset. A database that has run for months blends old and new behavior. Take two samples a known interval apart and compute the difference, or reset with
pg_stat_reset()on a test system.
Do not treat the ratio as a target to maximize. It is a symptom. If you raise shared_buffers and the ratio moves from 0.985 to 0.987 while latency stays the same, the change had no practical value.
Per-query evidence: EXPLAIN (ANALYZE, BUFFERS)
EXPLAIN alone shows the plan the planner expects. ANALYZE runs the query and adds actual timings and row counts. BUFFERS adds block counts for each node.
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY created_at;Look for these lines in the output.
| Output line | Meaning |
|---|---|
| `Sort Method: quicksort Memory: 2048kB` | The sort fit in `work_mem`. |
| `Sort Method: external merge Disk: 184320kB` | The sort did not fit and spilled to a temporary file. |
| `Buffers: shared hit=120 read=900` | 120 blocks came from `shared_buffers`. 900 were requested from the OS. |
| `Buffers: temp read=23040 written=23040` | The node used temporary files. |
| `actual time=... rows=... loops=N` | Per-loop averages. Multiply time and rows by `loops` for totals. |
Edge cases worth knowing:
EXPLAIN ANALYZEreally executes the statement. ForINSERT,UPDATE, orDELETE, wrap it in a transaction and roll back:BEGIN; EXPLAIN (ANALYZE, BUFFERS) UPDATE ...; ROLLBACK;.- The first run of a query may show many
readblocks and the second run mostlyhit. Compare runs under the same cache state, or run each twice and discard the first. - Timing overhead can inflate times on some systems. If a plan looks slow only under
ANALYZE, tryEXPLAIN (ANALYZE, TIMING OFF, BUFFERS). - With parallel queries, the
Buffersnumbers for a node include the work of its workers.
Finding spills across the whole database
One EXPLAIN shows one query. To see whether spills are common, read the temporary file counters.
SELECT datname, temp_files, pg_size_pretty(temp_bytes) AS temp_size
FROM pg_stat_database
ORDER BY temp_bytes DESC;A large temp_files count means many operations exceeded work_mem. It does not mean work_mem is too small everywhere. A single nightly report can produce thousands of files. Use the log, described next, to find which statements are responsible. When only a few roles run heavy queries, raise the value for them alone.
ALTER ROLE reporting SET work_mem = '256MB';Log settings that make events visible
The statistics views tell you how much. The log tells you which statement and when. Add these lines to postgresql.conf.
# postgresql.conf
log_checkpoints = on
log_temp_files = 0
max_wal_size = 4GB
checkpoint_timeout = 15min
checkpoint_completion_target = 0.9What each line does:
log_checkpoints = onwrites one line at the start and one at the end of every checkpoint. The end line includes how many buffers were written, the sync time, and the distance covered in WAL.log_temp_files = 0logs every temporary file along with its size. A value of0logs all files, and a positive value logs only files at least that many kilobytes. On a busy system, start with a threshold such as10MBto limit log volume.max_wal_size,checkpoint_timeout, andcheckpoint_completion_targetare the WAL settings covered in a later chapter. They appear here so that the checkpoint log lines have something to measure. All three need only a reload.
In the checkpoint log, the words starting: time mean the checkpoint was triggered by checkpoint_timeout. The words starting: wal mean it was triggered because WAL reached max_wal_size. Frequent wal checkpoints indicate that max_wal_size is too small for the write load.
Two further log settings help find slow statements:
log_min_duration_statementlogs any statement slower than a threshold in milliseconds. A value like500is a reasonable start.auto_explainis an extension that logs the plan of slow statements, including those inside functions. It lets you see spills in production without reproducing them by hand.
Making a fair comparison
A measurement is useful only if the before and after are comparable. Keep these rules.
- Record the baseline before changing anything: the settings, the counters, and the timing of the target query.
- Use the same data, the same query parameters, and a similar cache state.
- Run each test more than once. Report the median, not the best run.
- Change one setting at a time. Two changes at once make it impossible to attribute the result.
- Keep a note of the date and time of each change, so you can match it to log lines.
Common errors
- Reading
blks_readas disk reads. The operating system page cache may have served them. - Concluding from one
EXPLAIN ANALYZErun. The cache state changes between runs. - Forgetting that
loopsmultiplies the per-loop numbers. - Assuming
pg_reload_conf()applied a setting that needs a restart. Checkpending_restart. - Setting
log_temp_files = 0on a busy server and filling the log volume. - Running
EXPLAIN ANALYZEon a data-modifying statement without a rollback.
Exercise
You run EXPLAIN (ANALYZE, BUFFERS) on a report query and see Sort Method: external merge Disk: 512000kB and Buffers: temp read=64000 written=64000. pg_stat_database shows a high temp_files count for the whole database. Only the reporting role runs queries like this one. What should you change first, how do you apply it, and how do you confirm it worked?
Show answer
Raise work_mem for the reporting role only, for example ALTER ROLE reporting SET work_mem = '256MB';, because the spill comes from one role and a global increase would raise worst-case memory for every connection. The change affects new sessions of that role, so reconnect, then check with SHOW work_mem. Run the same query again under EXPLAIN (ANALYZE, BUFFERS) and look for Sort Method: quicksort Memory: ... and the absence of temp read/written buffers. Over time, check that temp_files and temp_bytes stop growing quickly, and use log_temp_files to confirm no new files for this statement. If the sort still spills, the data is larger than 256MB and you can raise the value again or accept the spill.
Exercise
After editing postgresql.conf to change shared_buffers, you run SELECT pg_reload_conf(); and it returns t. How do you find out whether the new value is active, and what do you do if it is not?
Show answer
Query pg_settings for shared_buffers and check pending_restart. If it is true, or if setting still shows the old value, the server has not applied it, because shared_buffers has context = postmaster and needs a restart. Schedule a restart, then confirm with SHOW shared_buffers that the new value is live.