Sub topic 15
A repeatable tuning workflow
This chapter ties the earlier ones together into a loop you can run on any PostgreSQL server. It assumes you can run queries in psql, edit postgresql.conf, reload or restart the server, and read a simple EXPLAIN plan. It also assumes you know the settings from earlier chapters: shared_buffers, work_mem, max_wal_size and random_page_cost.
Why a workflow matters
Memory and I/O settings interact. A larger shared_buffers leaves less RAM for the OS page cache. A larger work_mem multiplies across connections and plan nodes. A smaller random_page_cost changes which plans the planner picks. If you change several of these at once and performance moves, you cannot tell which change caused it.
The workflow has one rule: change one thing, then measure it against a baseline you took first.
Step 1: Take a baseline
A baseline is a record of how the server behaves before you touch anything. The counters in pg_stat_database only grow, so a single reading says little. Save snapshots and compare differences between them.
CREATE TABLE IF NOT EXISTS tuning_snapshot AS
SELECT now() AS taken_at, datname, blks_hit, blks_read,
temp_files, temp_bytes, xact_commit
FROM pg_stat_database
WHERE false;
INSERT INTO tuning_snapshot
SELECT now(), datname, blks_hit, blks_read,
temp_files, temp_bytes, xact_commit
FROM pg_stat_database
WHERE datname = current_database();Run the INSERT at the start and end of a representative period, such as a busy business hour or a benchmark run. Then compute the change between the two rows:
SELECT taken_at,
temp_files - lag(temp_files) OVER (ORDER BY taken_at) AS temp_files_delta,
pg_size_pretty(temp_bytes - lag(temp_bytes) OVER (ORDER BY taken_at)) AS temp_bytes_delta,
blks_read - lag(blks_read) OVER (ORDER BY taken_at) AS blks_read_delta
FROM tuning_snapshot
WHERE datname = current_database()
ORDER BY taken_at;Besides the counters, record these items:
- The slowest queries, from
pg_stat_statementsif it is installed, or fromlog_min_duration_statement. EXPLAIN (ANALYZE, BUFFERS)output for two or three of those queries.- Checkpoint counts. In PostgreSQL 17 and later they are in
pg_stat_checkpointer. In earlier versions they are inpg_stat_bgwriter. - The current settings, using the
pg_settingsquery from the earlier chapters.
Turn on log_checkpoints = on and log_temp_files = 0 before the baseline period, so the log can confirm what the counters show.
Step 2: Match a symptom to one setting
Pick the setting from evidence, not from a rule of thumb. The table below links each symptom to the likely setting and to how it is applied.
| Symptom | Evidence | Setting to try | Applied by |
|---|---|---|---|
| Sorts or hashes write temporary files | `Sort Method: external merge Disk`, growing `temp_files`, `log_temp_files` entries | `work_mem` (or `hash_mem_multiplier` for hashes) | Reload, or per role or session |
| Checkpoints triggered by WAL volume instead of time | Log lines saying `checkpoint starting: wal`, frequent write spikes | `max_wal_size` | Reload |
| Planner prefers sequential scans on fast storage | Plans scan a table although an index on SSD would be faster | `random_page_cost` | Reload, or per tablespace |
| Planner underuses indexes on a cache-heavy server | Estimated costs assume disk reads for data that is cached | `effective_cache_size` | Reload |
| Hit ratio low and the working set nearly fits in RAM | Low `hit_ratio`, high `blks_read` | `shared_buffers` | Restart |
| Autovacuum or index builds are slow | Long `VACUUM` or `CREATE INDEX` times | `maintenance_work_mem` | Reload |
Remember that a low hit ratio does not prove shared_buffers is too small. A block counted as read may have come from the OS page cache, so check whether the disk is really busy before you change it.
Step 3: Change one setting, at the narrowest scope
Test at the smallest scope that proves the point. A session-level SET affects only your connection and disappears when you disconnect. This is the safest way to check a work_mem hypothesis:
SHOW work_mem;
SET work_mem = '64MB';
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders ORDER BY created_at;
RESET work_mem;If the plan changes from external merge Disk to quicksort Memory, the hypothesis holds. Next, choose the scope for the real change:
ALTER ROLE reporting SET work_mem = '256MB'when only one workload needs it.ALTER DATABASE appdb SET work_mem = '32MB'for one database.ALTER SYSTEM SET ...for the whole server.
For a server-wide change, apply it and check whether it took effect:
ALTER SYSTEM SET max_wal_size = '4GB';
SELECT pg_reload_conf();
SELECT name, setting, unit, source, pending_restart
FROM pg_settings
WHERE name = 'max_wal_size';If a setting needs a restart, pg_reload_conf() does not apply it. The new value sits in the file and pending_restart shows t. List every such setting at once:
SELECT name, setting, pending_restart
FROM pg_settings
WHERE pending_restart;Schedule restarts for a quiet period. Do not bundle a restart-only change such as shared_buffers with reloadable changes, because that breaks the one-change rule.
Step 4: Measure the same workload
Run the same workload, for the same length of time, and take a second snapshot. Then compare:
- The target metric. For a
work_memchange, temporary file counts and bytes should fall. For a WAL change, the share of checkpoints started bywalshould fall. - The user-facing metric. Query latency from
pg_stat_statementsor your application should improve, or at least not worsen. - Side effects. Check memory use of the server, swap activity and the hit ratio.
Two conditions make a comparison unfair:
- Cold caches. Right after a restart,
shared_buffersand the page cache are empty, so reads are slow. Wait until the cache is warm before you measure. - Different load. A quiet Tuesday and a month-end Friday are not comparable. Replay the same workload, or compare equal hours of the same weekday.
Step 5: Keep or revert, and record the change
Keep the change only if the target metric improved and nothing else got worse. Before you keep a memory increase, redo the worst-case budget:
shared_buffers
+ max_connections * work_mem * (memory-hungry nodes per query)
+ maintenance_work_mem * concurrent maintenance jobs
+ OS and page cache headroomThis estimate is deliberately pessimistic. If the total approaches physical RAM, lower the setting or scope it to a role. Never accept a gain that raises the risk of an out-of-memory kill.
To revert a setting made with ALTER SYSTEM, remove it and reload:
ALTER SYSTEM RESET work_mem;
SELECT pg_reload_conf();Keep a change log with the date, the setting, the old and new values, the evidence for it, and the measured result. When a problem appears three months later, this log tells you what changed.
Worked example: a reporting database that spills
Suppose the baseline shows about 400 temporary files per hour, and the log shows log_temp_files entries of roughly 150 MB for a nightly report. EXPLAIN (ANALYZE, BUFFERS) shows Sort Method: external merge Disk: 148000kB.
- Hypothesis. The sort needs about 150 MB, but
work_memis 4MB. - Test. In one session,
SET work_mem = '256MB'and rerun the query. The sort now usesquicksort Memory, and the runtime drops. - Scope. Only the
reportingrole runs this query, so runALTER ROLE reporting SET work_mem = '256MB'. The new value applies to that role's new sessions. - Budget. The role has at most 4 connections, and a query uses at most 3 sort or hash nodes. That is 4 × 3 × 256 MB = 3 GB worst case, which fits on this server.
- Measure. After a night of reports, temporary files from that role drop to near zero, and the report finishes sooner.
- Record. Write the change in the log.
The global work_mem stayed at its small default, so the other 200 connections carry no extra risk.
Common mistakes
- Changing several settings at once. You lose the ability to attribute the result.
- Editing
postgresql.confwhilepostgresql.auto.confoverrides it.ALTER SYSTEMvalues win. Check thesourceandsourcefilecolumns ofpg_settings. - Assuming a reload applied a restart-only setting. Check
pending_restart. - Wrong units. A bare number for
work_memis in kilobytes, so write'64MB'explicitly. - Raising
work_memglobally to fix one query. Use a role, database or session scope. - Tuning from a hit ratio alone. The counters ignore the OS page cache.
- Skipping the baseline. Without it, "faster" is only an impression.
Exercise
Your baseline shows a hit ratio of 0.93 and no temporary files. The log shows many "checkpoint starting: wal" lines, with I/O spikes at each one. Which single setting do you change first, does it need a restart, and what do you measure afterward?
Show answer
Raise maxwalsize, for example from 1GB to 4GB. It needs only a reload (pgreloadconf()), not a restart. Afterward, run the same workload and compare the checkpoint log lines and checkpoint counters. Checkpoints should now start mainly because of checkpointtimeout, not WAL volume, and the I/O spikes should shrink. Also confirm that crash recovery time stays acceptable, since a larger maxwal_size can mean more WAL to replay.
Exercise
You run ALTER SYSTEM SET sharedbuffers = '8GB'; followed by SELECT pgreloadconf();. SHOW sharedbuffers still returns the old value. Which query explains this, and what must you do?
Show answer
Run SELECT name, setting, pendingrestart FROM pgsettings WHERE name = 'sharedbuffers'; and you will see pendingrestart = t. shared_buffers can only change at server start, so restart PostgreSQL in a planned window. Then take a new baseline, because the cache is cold after the restart.