Sub topic 5
What happens at COMMIT: flushing WAL
This chapter assumes you have read the earlier chapters on the write-ahead rule, WAL records and LSNs, and WAL segment files. You should be comfortable with psql, with BEGIN and COMMIT, and with the idea that a flush (an fsync call) forces data from the operating system cache onto stable storage.
The short version
When you run COMMIT, PostgreSQL does not write the changed table or index pages to disk. It writes one small WAL record that says "transaction N committed". It then waits until WAL up to the end of that record is flushed to disk. Only then does it report success to the client.
The data pages stay dirty in shared buffers. A later checkpoint or the background writer will write them out. If the server crashes first, recovery replays the flushed WAL. That is the payoff of the write-ahead rule: the commit cost is one sequential WAL flush, not many random page writes.
Three positions in the WAL stream
A running server tracks several WAL positions. Three are visible from SQL:
| Function | Meaning |
|---|---|
| `pg_current_wal_insert_lsn()` | End of WAL that backends have placed into WAL buffers in memory. |
| `pg_current_wal_lsn()` | End of WAL that has been written to the operating system, but not necessarily flushed. |
| `pg_current_wal_flush_lsn()` | End of WAL that is known to be on stable storage. |
The order is always insert ≥ write ≥ flush. A commit is durable only when the flush position has reached the end of the transaction's commit record.
Step by step through a commit
- Each data-changing statement in your transaction builds WAL records and copies them into the WAL buffers (sized by
wal_buffers). The transaction has been assigned a transaction ID by its first write. COMMITbuilds a commit record and inserts it into the WAL buffers. This gives the record an end LSN.- The backend calls the internal flush routine (
XLogFlush) with that LSN. If the flush position is already past it, nothing more is needed. Otherwise the backend writes the buffered WAL to the current segment file and callsfsync(or the method set bywal_sync_method). - Once the flush returns, the backend marks the transaction as committed in shared memory and in the commit status data (
pg_xact). Other sessions can now see the transaction's rows. - The backend returns
COMMITto the client.
Step 4 does not flush pg_xact to disk. It does not need to, because the commit record in WAL is the durable proof. If the server crashes, recovery sets the status again from that record.
Seeing it from SQL
The following script runs a small transaction, then compares the insert and flush positions. On an otherwise idle server, the gap after COMMIT is zero.
CREATE TABLE commit_demo (id int PRIMARY KEY, note text);
BEGIN;
INSERT INTO commit_demo VALUES (1, 'first');
SELECT pg_current_wal_insert_lsn() AS insert_lsn,
pg_current_wal_flush_lsn() AS flush_lsn;
COMMIT;
SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),
pg_current_wal_flush_lsn()) AS unflushed_bytes;Inside the transaction, the flush LSN usually trails the insert LSN, because nothing has asked for a flush yet. After COMMIT, unflushed_bytes is 0 unless other sessions are writing WAL at the same moment. Treat the in-transaction numbers as illustrative, since the WAL writer may flush at any time.
Who else flushes WAL
Backends are not the only processes that flush. The WAL writer process wakes every wal_writer_delay (default 200 ms) and flushes completed WAL. It also flushes when at least wal_writer_flush_after (default 1 MB) has accumulated. If the WAL buffers fill, a backend must write some out to make room, even without committing.
This means WAL for an uncommitted transaction can reach disk. That is safe, because recovery only treats a transaction as committed if its commit record is present.
Group commit
An fsync is slow compared with memory operations, so PostgreSQL lets concurrent commits share one. When several backends reach the flush step together, one of them performs the flush for all of them. The others wait, then find their LSN already covered. Throughput on a busy system is therefore much higher than one flush per commit would allow.
Two settings can widen the batching window:
commit_delay(microseconds, default 0) makes the flushing backend wait before it flushes, so more commits can join.commit_siblings(default 5) is the number of other open transactions required before that delay is used.
synchronous_commit
synchronous_commit controls how far the commit must progress before the client gets an answer. It can be set globally, per role, per session, or per transaction.
| Value | Waits for | Effect on a crash |
|---|---|---|
| `on` (default) | Local WAL flush, plus the synchronous standby flush if `synchronous_standby_names` is set | No committed transaction is lost. |
| `remote_apply` | Local flush and standby replay | No loss, and standby reads see the commit. |
| `remote_write` | Local flush and standby write to its operating system | Loses data only if the standby also crashes. |
| `local` | Local flush only | No local loss. A failover may lose it. |
| `off` | Nothing | The last few transactions can be lost. |
With off, the commit record is inserted and the backend returns at once. The WAL writer flushes it shortly after. The loss window is up to about three times wal_writer_delay, which is 600 ms by default. The database stays consistent. The lost transactions simply behave as if they had been rolled back, in commit order, so you never lose a later transaction while keeping an earlier one.
You can relax durability for one low-value transaction without changing the server default:
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO commit_demo VALUES (2, 'can be lost in a crash');
COMMIT;
SELECT pg_wal_lsn_diff(pg_current_wal_insert_lsn(),
pg_current_wal_flush_lsn()) AS unflushed_bytes;Here unflushed_bytes may be above zero for a moment after the commit, until the WAL writer catches up. SET LOCAL lasts only until the end of the transaction. Setting it after other writes in the same transaction is fine, since the value in force at commit time is the one used.
Cases where COMMIT does not flush
- A read-only transaction writes no WAL and has no transaction ID, so
COMMITreturns without a flush. - A transaction that only touches unlogged or temporary tables writes no WAL for them, so it has nothing to flush for that work.
- With
synchronous_commit = off, the flush is deferred as described above. - A transaction that rolls back does not need a flush. An abort record is written, but nobody waits for it.
What can go wrong
- Disks that lie. If a drive or controller reports a flush as complete while data sits in a volatile cache, the commit guarantee is void. Use storage with power-loss protection, or one that honors flush requests. The bundled
pg_test_fsynctool shows how fast your system completes flushes. An implausibly high rate on a spinning disk is a warning sign. - Failed fsync. If a WAL
fsyncfails, PostgreSQL raises aPANICand restarts into crash recovery instead of continuing. The kernel may have already dropped the dirty pages, so retrying could report a false success. - Slow commits. If commits are slow, check WAL flush latency first. A busy shared disk, or a synchronous standby on a slow network, adds directly to each commit.
Checking your settings
SELECT name, setting, unit
FROM pg_settings
WHERE name IN ('synchronous_commit', 'fsync', 'wal_sync_method',
'wal_buffers', 'wal_writer_delay', 'wal_writer_flush_after',
'commit_delay', 'commit_siblings')
ORDER BY name;To measure time spent in WAL writes and syncs, enable track_wal_io_timing and read the WAL counters in pg_stat_wal. In PostgreSQL 17 and earlier that view has wal_write, wal_sync, wal_write_time and wal_sync_time. In PostgreSQL 18 the I/O counters moved to pg_stat_io. Timing adds a small overhead on systems with slow clock reads, so check with pg_test_timing first.
Summary
Commit durability rests on one thing: the commit record is on stable storage before the client hears "committed". Group commit spreads the flush cost across concurrent sessions. synchronous_commit lets you trade a short window of possible loss for lower latency, without risking corruption. The dirty data pages still need to reach disk eventually, and the next chapter covers how checkpoints do that.
Exercise
A session runs SET synchronous_commit = off;, commits a transaction, and receives "COMMIT" immediately. The server loses power 100 ms later. After restart, can the database be corrupted, and can that transaction be missing? Explain.
Show answer
The database cannot be corrupted. WAL flushing is only delayed, not skipped, and crash recovery replays whatever WAL reached disk. The transaction can be missing, because its commit record may still have been in WAL buffers or the OS cache when power failed, and the WAL writer flushes only every wal_writer_delay (200 ms by default). If the commit record was not on disk, recovery treats the transaction as never committed. Any transactions committed after it are also lost, so the surviving state is a consistent earlier point in commit order.
Exercise
Why does a read-only COMMIT return quickly, even with synchronous_commit = on?
Show answer
A read-only transaction generates no WAL and is not assigned a transaction ID, so there is no commit record to flush and nothing to wait for.