Sub topic 10
The background writer and who writes dirty pages
This chapter explains how modified pages leave shared_buffers and reach disk, and which process does the writing. It assumes you can run queries in psql, edit postgresql.conf, and read the earlier chapters on shared_buffers, WAL, and checkpoints. Some views differ by version. The chapter notes this where it matters.
Dirty pages and the three writers
When a session changes a row, PostgreSQL modifies an 8 kB page in shared_buffers. The change is already safe in the WAL, so the page does not have to go to disk immediately. A buffer whose contents differ from the data file is called dirty. Dirty buffers must eventually be written out, and three kinds of process do that:
| Writer | When it writes | Why it matters |
|---|---|---|
| Checkpointer | At each checkpoint, and it also performs the `fsync` calls | Bounds crash recovery time and lets old WAL be recycled |
| Background writer | Continuously, in small rounds | Keeps clean buffers available so sessions rarely wait |
| Backend (your session) | When it needs a buffer and the only candidate is dirty | Adds write latency to a query |
The goal of tuning is to move writes away from backends and spread them out. Backend writes slow individual queries. Checkpoint writes done in one burst cause latency spikes for everyone.
Note that a "write" here is a write() call into the OS page cache. The data is durable only after fsync. The checkpointer issues those calls and collects requests forwarded from other processes.
What the background writer does
The background writer wakes every bgwriter_delay and works through three steps:
- It looks at how many buffers sessions allocated recently. It keeps a moving average of that rate.
- It multiplies that estimate by
bgwriter_lru_multiplierto decide how many clean, reusable buffers it should have ready. - It scans ahead of the clock-sweep position and writes dirty buffers that are unpinned and have a usage count of zero, up to
bgwriter_lru_maxpagesper round.
It writes the buffers that the clock sweep is about to evict. This is why it differs from the checkpointer. It does not try to write everything. It tries to keep a supply of clean victims.
| Setting | Default | Meaning |
|---|---|---|
| `bgwriter_delay` | 200ms | Sleep between rounds |
| `bgwriter_lru_maxpages` | 100 | Maximum buffers written per round. `0` disables the background writer |
| `bgwriter_lru_multiplier` | 2.0 | Scales the estimate of upcoming buffer demand |
| `bgwriter_flush_after` | 512kB on Linux | Asks the OS to start writeback after this much data is written |
With the defaults, the background writer can write at most 100 pages × 5 rounds per second × 8 kB, which is about 4 MB/s. That is small on modern hardware. It is a deliberate limit, because pages written early may be dirtied again and would then be written twice.
All of these settings take effect on a reload. No restart is needed.
How backends end up writing
When a session needs a buffer for a new page, it asks the clock sweep for a victim. If the victim is dirty, the backend must write it out first. Before that, WAL up to the page's LSN must be flushed, so the backend may also wait for a WAL flush.
This happens when the background writer cannot keep up, or when bgwriter_lru_maxpages stops it early. It also happens on a cold-then-busy workload where allocations jump suddenly.
Some backend writes are normal. Large sequential scans, VACUUM, and bulk writes such as COPY use a small ring buffer instead of the whole cache. The backend recycles the ring's buffers and writes them itself if they are dirty. This protects the main cache from being flushed out. Backend writes in a ring are expected and are not a sign of misconfiguration.
Measuring who writes
Versions before 17
pg_stat_bgwriter held every counter:
SELECT checkpoints_timed,
checkpoints_req,
buffers_checkpoint,
buffers_clean,
maxwritten_clean,
buffers_backend,
buffers_alloc
FROM pg_stat_bgwriter;buffers_checkpoint counts pages written by the checkpointer, buffers_clean counts pages written by the background writer, and buffers_backend counts pages written directly by sessions. maxwritten_clean counts how often the background writer stopped because it hit bgwriter_lru_maxpages. buffers_alloc is the number of buffer allocations.
Version 17 and later
PostgreSQL 17 moved the checkpoint counters into pg_stat_checkpointer. The backend write counter left pg_stat_bgwriter earlier, when PostgreSQL 16 introduced pg_stat_io.
SELECT num_timed, num_requested, buffers_written, write_time, sync_time
FROM pg_stat_checkpointer;
SELECT buffers_clean, maxwritten_clean, buffers_alloc
FROM pg_stat_bgwriter;Version 16 and later: pg_stat_io
pg_stat_io splits I/O by process type and by context. This is the best view for finding backend writes that matter:
SELECT backend_type, context, writes, fsyncs
FROM pg_stat_io
WHERE object = 'relation'
AND writes > 0
ORDER BY writes DESC;Read the context column carefully:
normalis the shared buffer pool. Writes byclient backendhere are the ones to worry about.bulkread,bulkwrite, andvacuumare ring-buffer contexts. Writes there are expected.
What is dirty right now
The pg_buffercache extension shows the current state of the pool:
CREATE EXTENSION IF NOT EXISTS pg_buffercache;
SELECT count(*) AS total_buffers,
count(*) FILTER (WHERE isdirty) AS dirty_buffers,
round(100.0 * count(*) FILTER (WHERE isdirty) / count(*), 2) AS dirty_pct
FROM pg_buffercache;Scanning pg_buffercache takes brief locks on the buffer mapping. Run it occasionally. Do not poll it every second on a large pool.
Measuring over an interval
Counters are cumulative since the last reset, so the totals mix old and new behavior. Reset them before an experiment and read them after a representative period:
SELECT pg_stat_reset_shared('bgwriter');On version 17 and later, also run SELECT pg_stat_reset_shared('checkpointer');. For pg_stat_io, use SELECT pg_stat_reset_shared('io'); on version 16 and later.
Interpreting the numbers
Compare the three writers' shares of total writes, not the raw totals.
| Observation | Likely meaning | Action |
|---|---|---|
| Most writes come from the checkpointer | Normal for write-heavy loads with a large `shared_buffers` | Check that checkpoints are spread out (see the WAL chapter) |
| `maxwritten_clean` grows steadily | The background writer is being capped | Raise `bgwriter_lru_maxpages` |
| Many `client backend` writes in the `normal` context | The background writer is not keeping up | Raise `bgwriter_lru_maxpages` and perhaps `bgwriter_lru_multiplier`; check for too-frequent checkpoints |
| `buffers_clean` is near zero and `buffers_alloc` is low | Few evictions are happening, so the cache is mostly stable | Leave it alone |
| Many requested checkpoints (`num_requested`, `checkpoints_req`) | `max_wal_size` is too small, so checkpoints are forced early | Increase `max_wal_size` |
A concrete change might look like this:
ALTER SYSTEM SET bgwriter_lru_maxpages = 400;
ALTER SYSTEM SET bgwriter_lru_multiplier = 4.0;
SELECT pg_reload_conf();Then reset the counters and compare after a comparable workload period. Raising the numbers has a cost. The background writer will write pages that may be dirtied again moments later. That extra I/O is only worthwhile if backends were stalling.
Writeback hints: the flush_after settings
Writing into the OS page cache can still produce a burst. The kernel may hold many dirty pages and then flush them all at once, which stalls later fsync calls. PostgreSQL can ask the kernel to begin writeback earlier:
checkpoint_flush_afterapplies to checkpointer writes. Default 256kB on Linux.bgwriter_flush_afterapplies to the background writer. Default 512kB on Linux.backend_flush_afterapplies to backends. Default 0, which disables it.
These defaults suit most systems. They matter when you see long fsync times (sync_time in pg_stat_checkpointer) or periodic latency spikes that match checkpoint completion. Change them only after measuring, and test on the real storage, because the effect depends on the kernel's own writeback tuning.
Edge cases
- Setting
bgwriter_lru_maxpages = 0turns the background writer off. Do this only for experiments, as backends then absorb the work. - Very small
shared_bufferscauses high turnover. Backend writes rise because evictions are constant, and the background writer cannot fix an undersized cache. - Temporary tables are not written by the background writer or checkpointer. Their buffers are local to the session, and the session writes them. They do not appear in these shared counters.
- Unlogged tables skip WAL but are still written by all three writers. Only the crash behavior differs.
- Hot standbys run a background writer and checkpointer too, which write pages replayed from WAL. Look at the standby's own statistics.
A short procedure
- Reset the shared statistics and run a normal workload period.
- Read
pg_stat_io(orpg_stat_bgwriterbefore 16) and findclient backendwrites in thenormalcontext. - Check
maxwritten_clean. If it is climbing, raisebgwriter_lru_maxpagesfirst. - Check requested versus timed checkpoints. If requested checkpoints dominate, fix
max_wal_sizebefore touching the background writer. - Reload, reset counters, and repeat the same workload. Keep the change only if backend writes or latency dropped.
Exercise
After a busy hour you see maxwritten_clean at 5,200 and many client backend writes with context normal in pg_stat_io. Checkpoints are almost all timed, not requested. Which setting do you change first, and why? Which setting would you leave alone?
Show answer
Raise bgwriter_lru_maxpages first. A high maxwritten_clean means the background writer stopped each round at its page limit while backends still had to write dirty victim buffers. Leave max_wal_size alone, because the checkpoints are almost all timed, so forced early checkpoints are not the problem. Reload, reset the statistics, and repeat the workload to confirm that backend writes drop.
Exercise
A query shows many writes by client backend in pg_stat_io, all with context bulkwrite and vacuum. Does this indicate a background writer problem?
Show answer
No. Those contexts use ring buffers, where backends recycle a small set of buffers and write dirty ones themselves. This is expected behavior. Only client backend writes in the normal context point to the background writer falling behind.