Relational databases
PostgreSQL WAL, checkpoints and durability
PostgreSQL can return COMMIT while a changed table page is still in shared buffers. The durable copy is in its write-ahead log, or WAL. A later page write catches the table file up; a checkpoint gives restart a safe place to begin replay. Those are three different kinds of progress, with different controls.
Follow the shop's independent price experiment. P7, the blue mug, starts at 20.00 and changes to 22.00. Stock stays P3 10, P7 0 and P9 4. Order 103 remains pending, has no payment, and keeps its agreed line prices totalling 29.00. We will read PostgreSQL's WAL positions, decide what a commit must wait for, then test a restart against what the client actually heard.
Storage and durability establishes the write-ahead rule and the difference between a process crash, power loss and lost storage. Inside PostgreSQL follows shared buffers and row versions. Here the controls and diagnostic views are PostgreSQL 18's. The drawings are selected schedules; the restart evidence below comes from a separate disposable server.
Inserted, written and flushed WAL
An LSN, or log sequence number, identifies a byte position in WAL. PostgreSQL prints it as two hexadecimal numbers separated by a slash, such as 0/1600040. It describes a place in an identified history. It is neither a transaction number nor a timestamp.
The end of the history has three useful positions. Inserted WAL has been generated into PostgreSQL's WAL buffers. Written WAL has left those buffers for the WAL file, possibly reaching only the operating system's cache. Flushed WAL is known durable under the storage system's flush contract. The synchronous_commit setting determines whether the application must wait for the required flush before hearing success.
Figure as text
Update and commit records enter WAL buffers, are written to the WAL file, then flushed to durable storage. With synchronous_commit on, acknowledgement waits for flush. With off it may leave before the flush, risking loss after a crash.
At the commit reply with the setting on, the flush has reached the required commit record. The table page need not have reached its file. With the setting off, the reply can leave earlier. The same price can therefore be visible to another session before its commit is protected against a crash.
On a running primary, these functions report the three current positions:
SELECT pg_current_wal_insert_lsn() AS inserted,
pg_current_wal_lsn() AS written,
pg_current_wal_flush_lsn() AS flushed;These are observations of moving server-wide progress, not one atomic measurement of a transaction. Other connections and background work can advance them, and the functions can be evaluated at different moments. Equal positions mean the sampled progress has caught up; unequal ones are not by themselves a fault.
In the native drill below, one sample after P7's successful commit reported 0/1C55B10 for all three. That is an observed caught-up sample on that instance. It does not identify the exact start of P7's commit record or say that the heap page was already written.
Subtract positions from the same history to get bytes:
SELECT pg_wal_lsn_diff('0/1600040'::pg_lsn,
'0/1600000'::pg_lsn) AS bytes;
-- bytes: 64The two positions above are invented. Their 64-byte difference is arithmetic, not the measured cost of P7's update. Sampling before and after an update on a busy server includes other WAL too. Neither a byte difference nor a flush position alone identifies which application request committed. Keep the request's outcome and the identity of the server and history alongside the positions, especially across restores or promotion.
What COMMIT waits for
With fsync = on and synchronous_commit = on, PostgreSQL waits for the required local WAL flush before reporting success. Several transactions can share that flush. They retain separate outcomes; group commit changes how the work is shared, not the promise made to each caller.
With synchronous_commit = off, commit can acknowledge before that flush. The WAL writer flushes in the background. PostgreSQL documents the maximum risk window as three times wal_writer_delay, whose default is 200 ms: about 600 ms with that setting. This describes the asynchronous commit mechanism, not an outage duration, and does not make a false storage flush report safe. Other activity can flush the records sooner.
The setting is useful only when losing recent reported work is acceptable and there is a sound way to account for the loss. A replaceable counter differs from a purchase confirmation. If an application sends an email after an early commit reply, the message can survive outside PostgreSQL while the database loses the change it confirmed. PostgreSQL does not keep a dependent later database transaction while losing the earlier transaction on which it relied.
Choosing the setting for one transaction
Choose at the transaction boundary, where the application knows what loss means. SET LOCAL lasts until that transaction ends. For the price change whose confirmation must survive, make the intended wait explicit:
BEGIN;
SET LOCAL synchronous_commit = on;
UPDATE products SET price = 22.00 WHERE product_id = 'P7';
COMMIT;The value in effect when commit begins controls that transaction. Putting SET LOCAL synchronous_commit = off inside a replayable ingestion transaction can choose the other trade without leaving the borrowed connection set that way for its next user. It still needs a durable upstream input and a resume protocol that detects missing work. A queue message acknowledged and removed after an early database reply may no longer be available to rebuild it.
| Work | Question before changing the setting | Local choice |
|---|---|---|
| Confirmed orders, payments or price changes | Can the application honour its confirmation if the database forgets it? | Keep the required durable commit wait. |
| Counts whose recent loss is accepted | Has that loss been accepted explicitly? | Off may suit those transactions. |
| Replayable events | Will the source and resume identity survive the same failure? | Off can be considered only with that recovery path. |
Do not substitute fsync = off. That disables the ordering safeguards on which recovery depends and can permit corruption after an operating-system or hardware failure. Likewise, full_page_writes protects recovery from interrupted page writes. Turning either off changes the consistency risk, not merely the acknowledgement time.
The local example assumes no synchronous standby. When synchronous_standby_names selects standbys, the commit setting can add a remote wait. on then also waits for the chosen synchronous copies' durable flush; local waits only for the local flush. PostgreSQL physical replicas and promotion develops the other levels and their failure promises. A local setting alone cannot establish survival on another machine.
Completing a checkpoint
A checkpoint reduces how far back crash recovery must look. PostgreSQL writes and synchronises the required changed data pages, then records a checkpoint from which restart can find a safe redo point. That point is earlier than the checkpoint's completion: the server keeps accepting writes while the checkpointer works.
Suppose the redo position for a checkpoint is R. The products page is written during that checkpoint, then changed again before it finishes. Completion must protect the earlier required state; it need not leave that page caught up with every later concurrent update.
Figure as text
A checkpoint begins at redo point R. Writes continue while required dirty pages reach storage. Only completion at K makes the earlier R safe for restart. K is not the new redo point.
At the end, the products page is dirty again, yet the checkpoint is complete. The earlier required changes have reached the data files; WAL from R covers the later work. Treating the later checkpoint record's own location as “every page includes everything up to here” would move the recovery boundary too far forwards.
Three settings shape this work. checkpoint_timeout schedules checkpoints, normally every five minutes. WAL growth can request one sooner through max_wal_size, normally 1 GB. checkpoint_completion_target, normally 0.9, spreads page writing across most of the anticipated interval. It is a pacing target, not a promise that a checkpoint finishes at an exact wall-clock time.
More frequent checkpoints can shorten the history recovery examines, but can write the same busy page more often. They can also generate more WAL: with full_page_writes = on, the first modification of a page after a checkpoint normally logs a full-page image. An interrupted page write can leave a mixture of old and new bytes. Recovery needs that usable whole-page starting copy; small change records cannot repair every such mixture.
A page updated repeatedly between checkpoints need not produce a full image for every update. Consequently the same SQL can generate different WAL volumes depending on checkpoint history, pages touched and page-image compression. The number of rows changed alone cannot predict the log cost. Keep the protection in place and measure the work before changing checkpoint frequency.
Reading WAL and checkpoint work
Start with an interval, such as the period containing the shop's import, and compare two samples from the same instance without a statistics reset between them. A lifetime count says how much has happened since its reset, not why the current request is slow. Cumulative statistics also lag and can be cached within a transaction; take fresh observations rather than repeatedly querying an old transaction's view.
SELECT clock_timestamp() AS sampled_at, stats_reset,
wal_records, wal_fpi, wal_bytes, wal_buffers_full
FROM pg_stat_wal;
SELECT clock_timestamp() AS sampled_at, stats_reset,
num_timed, num_requested, num_done,
buffers_written, write_time, sync_time
FROM pg_stat_checkpointer;For each counter, subtract the earlier sample from the later one only when the reset boundary still agrees. Divide the wal_bytes increase by elapsed seconds to describe the interval's average generation rate. It is not a prediction of the next interval, and it is not the size of the pg_wal directory.
| Observation | What it establishes | What to inspect next |
|---|---|---|
wal_bytes and wal_fpi increased | Generated bytes and page-image count during this interval. | Which work touched pages, and whether checkpoint frequency changed. An image count is not an image byte total. |
wal_buffers_full increased | WAL had to be written because its buffers filled. | Generation bursts and WAL I/O; this alone does not choose a buffer size. |
num_requested increased | Checkpoint requests, including ones skipped. | Checkpoint log reasons: WAL growth and explicit requests can both contribute. |
num_done increased | Completed checkpoints. | Page counts and writing/synchronisation phases; a request need not become completed work. |
| Client backends wrote many relation pages | Some page-write work reached request-serving processes. | Buffer pressure, background writing, checkpoint work and the affected requests. |
PostgreSQL 18 separates checkpoint counters into pg_stat_checkpointer. The background writer's buffers_clean and maxwritten_clean remain in pg_stat_bgwriter. For the processes actually performing relation and WAL I/O, use pg_stat_io:
SELECT backend_type, object, context, writes, write_bytes,
write_time, fsyncs, fsync_time, stats_reset
FROM pg_stat_io
WHERE object IN ('relation', 'wal')
ORDER BY backend_type, object, context;These are PostgreSQL operations, not a count of physical drive writes: caches and the storage stack still intervene. Time fields need track_io_timing for relations and track_wal_io_timing for WAL; zero with timing disabled does not mean free I/O. Untracked operations can appear as null rather than zero.
Read checkpoint logs alongside the samples. A start line records a reason such as time, wal or immediate force wait. A completion line reports pages written, the writing and synchronisation phases and the overall duration. A long writing phase can include intentional pacing; it is not all storage service time. Correlate the interval with request latency and workload before deciding that checkpoints caused the problem.
Why pg_wal can keep growing
Generated WAL is a stream of new history. pg_wal holds segment files containing parts of that history and files prepared for reuse. These are different measurements. Recycling renames an old segment for future use; it can keep allocated space steady while the logical WAL positions advance.
max_wal_size is a soft checkpoint control, not a disk quota. After local recovery no longer needs an old segment, another obligation may still retain it. A failed archive command cannot release unarchived segments. A replica's replication slot can retain history while that replica is behind. wal_keep_size, recycling estimates and, where enabled, WAL summarisation also affect what remains.
An administrator with the necessary inspection privileges can measure segment-file space without changing it:
SELECT count(*) AS files,
pg_size_pretty(sum(size)::bigint) AS total_size
FROM pg_ls_waldir();Compare that result with free storage and its trend. Then identify the retention requirement through archive and slot evidence; adding checkpoints cannot satisfy a failed archive or advance a disconnected consumer. Restoring PostgreSQL to a recovery target owns the archive chain, and PostgreSQL physical replicas and promotion owns standby progress. Removing a slot can sacrifice its consumer's ability to catch up, so repair requires knowing that consumer's recovery path. Never delete files from pg_wal by hand.
Testing crash recovery
A useful restart drill connects three records: the client's outcome before the stop, the recovered rows, and the server's account of recovery. Merely reconnecting proves that a server accepts a connection. It does not prove which price or unfinished transaction survived.
Use an explicitly identified disposable instance whose data and WAL survive the stop. Permanent logged tables matter: an unlogged table can be reset after a crash and would test a different promise. Keep the client transcript and server logs outside the stopped instance. Capture its version, data directory and system identifier, the effective durability and checkpoint settings, and a log baseline so earlier startup messages cannot be mistaken for this recovery.
This run used native PostgreSQL 18.6 on Linux, in an isolated container under Docker Desktop, with 2 CPUs, 1 GiB memory and no database network listener. Its fsync and full_page_writes were on, wal_sync_method was fdatasync, and no synchronous standby was configured. The same container and database system identifier were checked before and after restart. The test used a logged copy of the products and order-103 rows described here.
Record committed and unfinished work
Our drill begins with a checkpoint, establishing a known starting boundary before the price update. Connection A then commits P7's 20.00 → 22.00 change with synchronous_commit = on, and the outside client records the successful COMMIT. Connection B changes P9 from 35.00 to 36.00 but sends no commit. Its own RETURNING shows the attempted price; that is not an acknowledgement that it committed.
BEGIN;
UPDATE products SET price = 36.00
WHERE product_id = 'P9'
RETURNING product_id, price;
-- P9 | 36.00
-- Keep this transaction open; do not COMMIT.A third connection commits a small technical marker synchronously after B's update has returned. Flushing through the marker also carries the earlier update's WAL forwards. This makes the contrast useful: even surviving physical history for P9 must not turn unfinished work into a committed price. The marker is drill evidence, not a shop payment or order.
Stop and restart the same instance
Stop only the identified disposable instance in immediate mode, then restart it using the same data directory. That is what this drill did through pg_ctl stop -m immediate with an explicit data directory. Immediate mode aborts the server processes without a clean shutdown, so the next start needs crash recovery. Fast shutdown is a clean procedure: it aborts active transactions and completes a normal shutdown. Substituting it would change the test.
This is deliberately a process-stop drill. The operating system, its caches and the backing storage remain present. It does not cut power, discard a virtual machine's cache or lose a volume. A passing result cannot establish any of those stronger failure promises.
Observed on the disposable PostgreSQL 18.6 instance. The acknowledged price survived; the unfinished price did not become committed. SQL checks also found pending order 103, zero payments and stock 10/0/4. Server recovery logs explain the path between the two outside observations.
Read the recovery evidence
The startup log's redo starts at identifies where replay begins. redo done at identifies the last replayed record's position and reports replay timing. Those two LSNs locate the scanned span; their difference is not the exact sum of record payload bytes. Recovery can encounter an incomplete tail at the end of available WAL; an end-of-log message needs the surrounding successful recovery and readiness evidence to be interpreted correctly.
After replay, PostgreSQL can still have end-of-recovery checkpoint work before it reports readiness. Preserve the complete sequence, then query the recovered products and order. P9's update can be represented in replayed pages while remaining invisible because its transaction never committed. Correctness is the visible committed result, not the absence of every attempted byte from the files.
In this restart, the log reported automatic recovery, redo from 0/1C558E0, the last replayed record at 0/1C5BEB8, and an end-of-recovery checkpoint before readiness. The rounded redo duration was 0.00 seconds; it cannot establish a useful recovery rate.
database system was not properly shut down; automatic recovery in progressThe immediate stop requires recovery, rather than a normal clean start.redo starts at 0/1C558E0This matches the redo point recorded by the completed checkpoint before the price updates.invalid record length at 0/1C5BEE0: expected at least 24, got 0This run reached the available log's end here. Read the next messages and verify the data; this line alone does not establish corruption or success.redo done at 0/1C5BEB8 … elapsed: 0.00 sThe last replayed record begins here. The reported duration rounds to zero at this resolution; it is not a measured replay-capacity result.checkpoint starting: end-of-recovery immediate waitThe completion line then reported 8 shared buffers written and total 0.009 s. Startup work continued after redo.database system is ready to accept connectionsNow a fresh guarded SQL connection checked P7, P9 and the unchanged order facts in Figure 3.
An abridged transcript of the same PostgreSQL 18.6 restart, not an illustrative log. The earlier checkpoint record was at 0/1C55938 and its redo point at 0/1C558E0. The complete client and server transcripts were retained outside the disposable instance.
Fresh reads after restart found P7 at its acknowledged 22.00 and P9 at 35.00, rather than the uncommitted 36.00. Order 103 remained pending with agreed value 29.00 and no payment; stock remained 10/0/4. The technical flush marker also survived. Those observed results establish the acknowledged-versus-unfinished distinction on surviving storage. Neither the rounded replay duration nor the whole test harness's runtime measures useful recovery capacity.
Compare statistics only within their valid reset boundary. PostgreSQL resets cumulative statistics after an unclean shutdown. Subtracting a pre-crash total from a post-restart total would create a meaningless interval, even though the data itself recovered correctly.
Choosing a recovery budget
Checkpoint settings trade steady writing against restart work. Choose them against representative updates and repeated owned restart drills, recording the generated history, checkpoint state, storage and recovered outcome each time. A tiny price test establishes the transaction distinction; it does not measure the recovery cost of a busy shop.
Keep three durations separate: failure detection and restart initiation, replay and startup work before readiness, and useful service after caches warm. WAL bytes divided by one observed replay rate estimates only part of that work under the measured conditions. A different record mix, colder storage or concurrent activity can change it. Neither a five-minute checkpoint interval nor one quick recovery promises a five-minute or quick outage.
Finally, choose the recovery mechanism from what was lost. Restart uses the surviving local history. It cannot replace lost storage, and it should faithfully retain a separately committed mistaken price of 2.20. Correct the business value where appropriate, or use another recoverable history and reconcile valid later work. Restoring PostgreSQL to a recovery target follows that wider operation.