Sub topic 3
The background writer and who writes dirty pages
This chapter assumes you can run SQL in psql, edit postgresql.conf, reload the server, and that you know the operating system caches files in RAM.
When PostgreSQL changes a page held in shared_buffers, the page is "dirty" until its new contents reach disk. Three kinds of process write dirty pages:
- The checkpointer writes all dirty pages at each checkpoint.
- The background writer (bgwriter) writes some dirty pages ahead of need, so backends find clean buffers.
- Regular backends write a dirty page themselves when they need a buffer and none is clean. This slows the query that triggered it.
On PostgreSQL 16 and earlier, the buffers_backend column in pg_stat_bgwriter counts backend writes. On PostgreSQL 17 and later, use pg_stat_io instead. A growing backend count suggests the bgwriter is not keeping up.
Telling the planner about your storage
The planner uses relative costs: seq_page_cost (default 1.0) and random_page_cost (default 4.0). On SSDs, a random read costs little more than a sequential one, so a lower random_page_cost makes index scans more attractive. Both settings take effect on reload.
ALTER SYSTEM SET random_page_cost = 1.1;
SELECT pg_reload_conf();
SHOW random_page_cost;I/O concurrency and prefetching
effective_io_concurrency sets how many concurrent I/O requests a bitmap heap scan may issue. The default is 1. A value of 100 to 200 is a common starting point on SSDs. Set it with ALTER SYSTEM and reload.
Huge pages for large shared memory
Huge pages are large memory pages that reduce page-table overhead for big sharedbuffers. `hugepages = try uses them when the operating system has reserved them. hugepages requires a restart, so check pendingrestart in pg_settings` after you change it.
Operating system settings: overcommit and swap
Setting vm.overcommit_memory = 2 makes the kernel refuse allocations beyond its commit limit. PostgreSQL then gets an error it can handle, instead of a sudden out-of-memory kill, but you must budget memory correctly. Keep swapping low, because swapped-out shared memory makes queries very slow:
sudo sysctl -w vm.overcommit_memory=2
sudo sysctl -w vm.swappiness=1A repeatable tuning workflow
- Record a baseline:
pg_stat_bgwriterorpg_stat_io, the hit ratio frompg_stat_database, andEXPLAIN (ANALYZE, BUFFERS)output for a key query. - Change one setting.
- Reload or restart as the setting requires.
- Run the same workload and compare with the baseline.
- Keep the change if it helps, or revert it.
Exercise
Exercise
Your pgstatbgwriter shows buffersbackend growing much faster than bufferscheckpoint. What does this suggest, and which settings would you examine first?
Show answer
Backends are writing dirty pages during queries, so the background writer is not keeping up. Examine bgwriterlrumaxpages (raise it) and bgwriter_delay (lower it) first, change one at a time, and compare the counters before and after each change.