Skip to content

Durability, WAL & Crash Recovery ​

"WAL's central concept is that changes to data files (where tables and indexes reside) must be written only after those changes have been logged, that is, after WAL records describing the changes have been flushed to permanent storage." — PostgreSQL documentation, 28.3. Write-Ahead Logging (WAL)

Summary: A commit is durable when its log record is on stable media, not when the table changes are; everything else (checkpoints, full-page writes, checksums, replicas) exists to make that log usable after a crash. Focus: The write-ahead rule, WAL records and LSNs, fsync and its friends, synchronous_commit, group commit, torn pages, checkpoints, crash recovery and ARIES, fsyncgate, and how InnoDB, SQLite, Redis, MongoDB and Kafka make the same trade. Learning goal: Say exactly what a crash can lose under each setting, tune commit latency and checkpoints without losing data, and recover (or refuse to "fix") a database that will not start.

This page is the complete reference for the "D" in ACID: what it promises, how the write-ahead log (WAL) delivers it, every knob that trades it for speed, how a database restarts after a crash, and how the layers under the database (kernel, controller, drive, cloud volume) can quietly break it. PostgreSQL is the main engine; MySQL InnoDB, SQLite, Redis, MongoDB, Kafka, SQL Server, Oracle and CockroachDB are compared wherever they differ. Neighbours that this page does not re-teach: the four ACID properties and BEGIN/COMMIT live in ACID & Transactions; pages, tuples and the heap in Database Internals; row versions and why an uncommitted row is invisible in MVCC, VACUUM & Bloat; standbys, synchronous replication and failover in Replication, Read Replicas & Failover; base backups, WAL archiving for PITR and restore drills in Backup, PITR & Disaster Recovery; distributed two-phase commit and consensus in Distributed SQL, Consensus & 2PC.

Page map ​

If you are looking forGo to
The whole topic in three tablesEverything in one minute
Why a log, and the trade-off it makesWhy durability needs a log
ARIES, repeating history, where PostgreSQL differsWhere it comes from
Which failure each mechanism survivesThe failure model
The write-ahead rule, LSN, segments, wal_levelWrite-ahead rule, WAL records, LSN, segments
fsync, fdatasync, O_DIRECT, O_DSYNC, wal_sync_methodFlushing to stable storage
synchronous_commit and what each level can loseCommit levels
commit_delay, commit_siblingsGroup commit
Torn pages, full_page_writes, doublewriteTorn pages
checkpoint_timeout, max_wal_size, checkpoint stormsCheckpoints
Background writer, WAL writerBackground writer and WAL writer
Recycling, archive_mode, archive_commandWAL retention and archiving
What happens on restart, step by step (recovery timeline)Crash recovery
Analysis/redo/undo, CLRsARIES in detail
Data checksums, CRC-32CChecksums
fsyncgate 2018, data_sync_retryfsyncgate
Disk write caches, battery-backed controllers, cloud disks (EBS, Persistent Disk)The layers below
InnoDB redo, doublewrite, sync_binlog, 2PC with the binlogInnoDB
SQLite, Redis, MongoDB, Kafka, SQL Server, Oracle, CockroachDBPer-engine behaviour
Every knob, every tool, every error codeMechanics
Slow commits, checkpoint spikes, full pg_wal, lost acks, a database that will not startSolving the classic problems
Which setting for which dataChoosing durability settings
Replicas, microservices, multi-regionIn architecture
kill -9, commit latency, pg_waldumpLab
Wrong beliefs, a cheat sheet, every termMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The mechanisms. Every row is unpacked below.

MechanismIn plain wordsWhat it protects againstPostgreSQL knob (default)
Write-ahead ruleLog the change, flush the log, only then may the page reach diskLosing a committed change; half-applied changesAlways on
WAL flush at commitThe commit waits until its log record is on stable mediaLosing an acknowledged commitsynchronous_commit (on)
Group commitOne flush covers many commitsFlush cost dominating throughputcommit_delay (0), commit_siblings (5)
Full-page writesFirst change to a page after a checkpoint logs the whole pageTorn pages after power lossfull_page_writes (on)
CheckpointFlush all dirty pages, mark a redo start pointUnbounded recovery time and WAL growthcheckpoint_timeout (5min), max_wal_size (1GB)
Crash recovery (REDO)Replay the log forward from the last checkpointChanges that were only in memoryAutomatic, restart_after_crash (on)
ChecksumsDetect pages and records that are garbageSilent media corruptionData checksums on by default since PostgreSQL 18; WAL CRC-32C always
ArchivingCopy finished WAL segments elsewhereLosing the disk, needing PITRarchive_mode (off), archive_command
Synchronous replicaAnother machine has the WAL before you ackLosing the whole serversynchronous_standby_names + synchronous_commit

What an acknowledged commit can lose, per product and setting.

Product and settingAck afterA crash can loseCan it corrupt?
PostgreSQL synchronous_commit = on (default)Local WAL flushNothing acknowledgedNo
PostgreSQL synchronous_commit = offNothingUp to 3 × wal_writer_delay (600 ms by default)No: lost commits look like clean aborts
PostgreSQL fsync = offNothing is ever flushedAnythingYes, "arbitrarily bad corruption"
MySQL InnoDB innodb_flush_log_at_trx_commit = 1 (default)Redo flushNothing acknowledgedNo
InnoDB innodb_flush_log_at_trx_commit = 2 / 0Write to OS / nothingAbout 1 s (innodb_flush_log_at_timeout)No
SQLite WAL mode, PRAGMA synchronous = NORMALWAL append, no syncLast transactions on power lossNo
Redis appendfsync everysec (default AOF policy)Append to AOF bufferAbout 1 s of writesNo
MongoDB WiredTiger, write concern j: trueJournal flushNothing acknowledgedNo
Kafka acks=all, default flush settingsIn-sync replicas have it in page cacheOnly if all in-sync replicas fail togetherNo
SQL Server delayed durabilityLog bufferUnflushed log tailNo
Oracle COMMIT WRITE NOWAITNothingUnwritten redoNo

The three things to do.

SituationDo this
Money, stock, anything an external party was told aboutKeep the defaults: synchronous_commit = on, innodb_flush_log_at_trx_commit = 1, sync_binlog = 1, and verify the disk honours flushes (pg_test_fsync)
High-volume, low-value writes (events, telemetry, audit-adjacent logs)Relax per transaction (SET LOCAL synchronous_commit = off), never server-wide fsync = off
Surviving the loss of a machineDurability on one disk is not enough: add a synchronous standby or archived WAL, see Replication and Backup & PITR

Why durability needs a log ​

A database keeps hot pages in memory and writes them back later, because writing every changed 8 kB page to its home on disk at every commit would mean dozens of random writes per transaction. But memory dies with the process. The write-ahead log solves both problems at once: at commit, the database appends a small description of the change to a sequential file and flushes only that file. The changed pages stay in memory. If the machine dies, the log is replayed and the pages are rebuilt. PostgreSQL's chapter states the payoff: "only the WAL file needs to be flushed to disk to guarantee that a transaction is committed, rather than every data file changed by the transaction", and because "the WAL file is written sequentially", syncing it costs much less than flushing data pages.

Flush data pages at commit (no log, "force")Write-ahead log ("no-force")
Random writes to every touched page, every commitOne sequential append and one flush per commit (or per group of commits)
Commit latency grows with the number of pages touchedCommit latency is roughly one WAL flush
A crash mid-flush leaves some pages new and some old, no way to tellThe log says exactly which changes committed
No point-in-time recovery, no physical replicationThe same log feeds archiving, PITR, standbys and logical decoding
Nothing extra to manageYou now manage checkpoints, WAL volume, recycling and archiving

The analogy we reuse on this page: a restaurant kitchen. The cook writes every order on a ticket and pins it on the rail before touching food. The tickets are the WAL; the plates are the data pages. If the power goes out mid-service, the manager does not inspect every half-made plate: she walks the rail and re-makes whatever the tickets say (REDO). Clearing the rail of tickets whose plates have all been served is a checkpoint. A waiter who says "your order is in" before the ticket is pinned is asynchronous commit: usually fine, and at worst the last few orders vanish, but the kitchen is never left in a mangled state. A cook who skips tickets entirely is fsync = off.

Three common misunderstandings, up front ​

  1. "COMMIT returned, so the row is in the table file." No. The commit record is in the WAL; the table page may sit dirty in shared_buffers for minutes until a checkpoint. That is the whole point of the design.
  2. "Checkpoints make commits durable." No. The WAL flush does. Checkpoints bound how much WAL must be replayed after a crash and let old WAL be recycled.
  3. "A successful fsync() means the bytes are on the platter." Only if every layer below tells the truth: kernel, RAID controller, drive cache, cloud volume. PostgreSQL's own manual warns that for SSDs "many of these do not honor cache flush commands by default", and fsyncgate (2018) showed the kernel could report success after losing data.

Where it comes from ​

Write-ahead logging predates relational databases, but the version every engine is measured against is Mohan, Haderle, Lindsay, Pirahesh and Schwarz, "ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging" (ACM TODS, March 1992). It fixed the vocabulary: log sequence number (LSN) on every page, the WAL protocol, "repeating history" during redo, and compensation log records for undo. The abstract:

"We introduce the paradigm of repeating history to redo all missing updates before performing the rollbacks of the loser transactions during restart after a system failure. ARIES uses a log sequence number in each page to correlate the state of a page with respect to logged updates of that page." — Mohan et al., ARIES, ACM TODS 17(1), 1992

The paper's definition of the WAL protocol is the rule this whole page rests on: the log records for a change "must already be on stable storage before the changed data is allowed to replace the previous version of that data on nonvolatile storage."

PostgreSQL is not ARIES. PostgreSQL's manual calls WAL "a standard method for ensuring data integrity" and points to transaction-processing textbooks; it does not claim to implement ARIES. The visible difference: PostgreSQL's recovery is redo-only. An uncommitted transaction's row versions are replayed like everything else but stay invisible, because MVCC sees no commit record for their transaction id; there is no undo pass. InnoDB and SQL Server are closer to ARIES: they redo, then roll back losers using undo information. Treat ARIES as the conceptual ancestor and the vocabulary, not as a description of PostgreSQL's code.

Two later events shaped today's defaults. fsyncgate (2018) showed that on Linux a failed fsync() could be followed by a successful one that lied; PostgreSQL now panics instead of retrying (details). And checksums by default: PostgreSQL 17's manual still says "By default, data pages are not protected by checksums"; PostgreSQL 18's says "By default, data pages are protected by checksums".

The failure model ​

PostgreSQL's reliability chapter states the target: committed data should be "stored in a nonvolatile area that is safe from power loss, operating system failure, and hardware failure (except failure of the nonvolatile area itself, of course)". Every mechanism on this page answers one row of this table.

FailureWhat is lost from memoryWhat brings data backWhat does NOT help
One backend process crashes (kill -9 a backend, segfault)Shared memory is considered unsafe; PostgreSQL resets all processesCrash recovery from WAL (automatic with restart_after_crash = on)Nothing else needed
Database server process killed (docker kill, OOM killer on the postmaster)Everything in shared_buffersCrash recovery; the OS page cache still holds written-but-unflushed data
OS crash or kernel panicProcess memory and the OS page cacheOnly what was flushed (fsync)synchronous_commit = off commits not yet flushed are gone
Power lossPage cache and any volatile drive/controller cacheFlushed data, if the drive honoured the flush; full-page images for torn pagesA write-back cache without a battery
Disk diesThe whole volumeA replica, or base backup + archived WALAnything on the same disk, including local WAL
Data center / zone lostAll local copiesA replica or archive in another zone/regionSame-zone replicas
Operator error (DROP TABLE, bad migration)Nothing; the mistake is durably committedPITR to before the mistakeReplicas (they replay the mistake too)

The mechanisms, one by one ​

Each block: plain words, the usual wrong belief, a precise definition, a timeline, real scenarios, what each product does, and the fix or usage in SQL (Go and Laravel versions are in Solving the classic problems).

The write-ahead rule Must-know ​

In plain words: write down what you are about to change, make sure the note is safe, and only then let the changed page reach disk.

Common misunderstanding: "WAL means every change is written twice, so it must be slower." The WAL write is sequential and small, and it replaces the random page writes a commit would otherwise need. The page is still written once, later, often after absorbing many changes.

Definition: for every data page, the WAL up to that page's LSN must be flushed before the page may be written to the data file; and a transaction counts as committed only when its commit record is flushed. The first half protects atomicity across a crash (no orphan page changes without a log record to explain or undo them), the second half is durability.

The picture below follows one commit through every layer: the backend changes a page in shared_buffers and inserts a WAL record, the WAL is written and flushed at COMMIT, the client is acknowledged, and only later do the background writer and checkpointer write the data pages.

Write path: log first, pages later1. ClientINSERT ... ; COMMIT2. Backend (shared memory)change page + insert WAL recordWAL bufferswal_buffersshared_buffersdirty page (LSN)3. write() at COMMITkernel page cache: pg_wal/0000...4. fsync / fdatasync / O_DSYNC(wal_sync_method)device / controller cachesafe only if flushed or battery-backedstable media: WAL is durable5. ack "COMMIT"after flush (synchronous_commit=on)before flush when off: WAL writerflushes within 3 x wal_writer_delay6. Later, in backgroundbackground writer (bgwriter_delay)checkpointer (spread writes)7. Checkpointwrite all dirty pages, fsyncdata files, write checkpointrecord, update pg_control,recycle old WAL segmentsRule: a data page may reach diskonly after the WAL up to its LSNis flushed (write-ahead rule).
text
     Backend                         WAL (pg_wal)              Data file (base/...)
1    UPDATE accounts ... id=7
2    page 42 changed in shared_buffers, page LSN := 0/3000148
3                                    record @0/3000100 (buffer)
4    COMMIT
5                                    commit record @0/3000160
6                                    write + fdatasync up to 0/3000190
7    "COMMIT" sent to client
8    ... minutes later: bgwriter/checkpointer wants to write page 42
9                                    flushed LSN >= 0/3000148?  yes
10                                                             page 42 written

Real scenario: a bulk UPDATE touches 2 million rows; commit takes milliseconds because only WAL is flushed, but the next checkpoint writes gigabytes. A server crashes one second after a payment commit; the payment row is not in the table file, yet after restart it is there, rebuilt from WAL.

ProductName of the logWrite-ahead rule enforced by
PostgreSQLWAL (pg_wal/)Buffer manager checks page LSN against flushed WAL before writing
MySQL InnoDBRedo log (#innodb_redo/)Flushes redo up to the page LSN before flushing the page
SQLiteRollback journal or WAL fileJournal synced before the database file is changed (rollback mode), or WAL appended (WAL mode)
SQL ServerTransaction log (.ldf)Log records hardened before the dirty page is written
OracleOnline redo logLGWR writes redo before DBWn writes the block
MongoDB WiredTigerJournalJournal records plus periodic checkpoints

Fix / how to use it: nothing to switch on; what you control is when the WAL flush happens (synchronous_commit, below) and whether the flush is honest (fsync, wal_sync_method, the hardware).

WAL records, LSN, segments and wal_level Must-know ​

In plain words: the WAL is one endless numbered byte stream cut into 16 MB files; the LSN is your position in that stream.

Common misunderstanding: "The WAL contains SQL statements." It contains physical, per-page change records from resource managers (heap, B-tree, transaction, XLOG...), plus full-page images. Logical decoding needs extra information (wal_level = logical) to turn them back into row changes.

Definition: PostgreSQL's manual: "The insert position is described by a Log Sequence Number (LSN) that is a byte offset into the WAL, increasing monotonically with each new record." LSNs are type pg_lsn and print as two hex halves (0/3000148); the difference of two LSNs is a byte count (pg_wal_lsn_diff). WAL is stored "as a set of segment files, normally each 16 MB in size" (changeable with initdb --wal-segsize), divided into 8 kB pages, named like 000000010000000000000001 (timeline, then log and segment number). Each record is protected by a CRC-32C. Three LSNs matter: insert (pg_current_wal_insert_lsn(), reserved in WAL buffers), write (pg_current_wal_lsn(), handed to the kernel) and flush (pg_current_wal_flush_lsn(), "the last location known to be written to durable storage").

wal_level decides how much goes in: minimal (only crash recovery; enables skipping WAL for tables created or truncated in the same transaction, controlled by wal_skip_threshold), replica (default; archiving and physical standbys), logical (adds what logical decoding needs). "Each level includes the information logged at all lower levels." PostgreSQL 19 also raises the effective level to logical automatically while a logical replication slot exists (effective_wal_level).

text
     Session                                              WAL position
1    SELECT pg_current_wal_lsn();                          0/1A2B3C8
2    BEGIN; INSERT INTO t VALUES (1); COMMIT;
3    SELECT pg_current_wal_lsn();                          0/1A2B470
4    SELECT pg_wal_lsn_diff('0/1A2B470','0/1A2B3C8');      168   -- bytes for one insert + commit
5    SELECT pg_walfile_name('0/1A2B470');                  000000010000000000000001

Real scenario: measuring WAL generated per business transaction to size disks and network for replicas; computing replication lag in bytes; finding which segment a PITR target lives in; noticing that an UPDATE of one column in a wide row produces a full-page image right after each checkpoint.

ConceptPostgreSQLMySQL InnoDB
PositionLSN, byte offset, pg_lsnLSN, ever-increasing, Innodb_redo_log_current_lsn
Files16 MB segments in pg_wal/, recycled32 files #ib_redoN sized innodb_redo_log_capacity/32
Content levelwal_level = minimal / replica / logicalRedo is physical-logical; row images for replication go to the separate binary log
IntegrityCRC-32C per recordChecksums per redo block

Fix / how to use it:

sql
SHOW wal_level;                                    -- replica
SELECT pg_current_wal_lsn(), pg_current_wal_flush_lsn(), pg_walfile_name(pg_current_wal_lsn());
SELECT wal_records, wal_fpi, wal_bytes, wal_buffers_full FROM pg_stat_wal;  -- wal_fpi_bytes: PostgreSQL 19+

Flushing to stable storage: fsync, fdatasync, O_DIRECT, O_DSYNC and wal_sync_method Must-know ​

In plain words: write() only hands bytes to the kernel's page cache; a flush call is what pushes them through to the device and asks the device to make them permanent.

Common misunderstanding: "O_DIRECT means my writes are durable." O_DIRECT bypasses the OS page cache, nothing more. The device's own volatile cache still needs a flush, which is why InnoDB with innodb_flush_method = O_DIRECT still calls fsync() and why O_DIRECT_NO_FSYNC comes with a warning.

Definition: fsync(fd) flushes a file's data and metadata; fdatasync(fd) flushes data and only the metadata needed to read it back (cheaper, no mtime update); opening with O_SYNC/O_DSYNC makes each write() itself synchronous; O_DIRECT skips the page cache (alignment rules apply). PostgreSQL's wal_sync_method chooses among open_datasync (O_DSYNC), fdatasync (default on Linux and FreeBSD), fsync, fsync_writethrough (forces write-through of the disk cache; the macOS answer) and open_sync. The manual: "All the options should be the same in terms of reliability, with the exception of fsync_writethrough". The server-wide fsync parameter turns all of it off and "can result in unrecoverable data corruption in the event of a power failure or system crash".

text
     PostgreSQL backend           Linux kernel                  SSD
1    write(wal_fd, 8kB)           copy into page cache          -
2    (COMMIT not yet safe)        page dirty in RAM             -
3    fdatasync(wal_fd)            submit bio, then FLUSH/FUA     lands in volatile cache
4                                                                cache flushed to NAND
5                                 return 0                       -
6    commit is durable; send ack

Real scenario: pg_test_fsync reports flush times on a consumer SSD that are implausibly fast for that drive class: a sign the drive acknowledges flushes from its volatile cache; verify with diskchecker.pl before trusting it, because a power cut would lose acknowledged commits. A macOS laptop's PostgreSQL loses data on power loss until wal_sync_method = fsync_writethrough. A benchmark sets fsync = off and someone copies the config to production.

ProductKnobDefaultNote
PostgreSQLwal_sync_methodfdatasync on Linux/FreeBSDTest with pg_test_fsync
PostgreSQLfsynconoff only for throwaway clusters
MySQL InnoDBinnodb_flush_methodO_DIRECT if supported (Unix), else fsyncinnodb_use_fdatasync swaps fsync() for fdatasync()
MySQL InnoDBO_DIRECT_NO_FSYNCnot defaultSkips fsync() after writes; unsafe if redo and data are on different devices without battery-backed cache
SQLitePRAGMA synchronousFULL for rollback journalPRAGMA fullfsync on macOS
Redisappendfsynceverysec

Fix / how to use it:

bash
# Run on the volume that will hold pg_wal; compare methods and sanity-check the numbers
pg_test_fsync -f /var/lib/postgresql/pg_wal_test -s 5
sql
SHOW fsync;             -- must be on
SHOW wal_sync_method;   -- fdatasync on Linux

synchronous_commit: what a commit waits for Must-know ​

In plain words: one setting decides how far the commit record must travel (my RAM, my disk, a standby's OS, a standby's disk, a standby's tables) before the client hears "COMMIT".

Common misunderstanding: "synchronous_commit = off can corrupt my database." It cannot. The docs: "The risk that is taken by using asynchronous commit is of data loss, not data corruption." Corruption comes from fsync = off or full_page_writes = off.

Definition:

ValueWaits forSurvives PG crashSurvives OS crash on standbyStandby reads see it
offnothing; WAL writer flushes within 3 × wal_writer_delayNot the last few commits——
locallocal WAL flushYes (locally)——
remote_writelocal flush + standby wrote to its OSYesNoNo
on (default)local flush + standby flushed (if synchronous_standby_names set)YesYesNo
remote_applylocal flush + standby replayed itYesYesYes

"If synchronous_standby_names is empty, the only meaningful settings are on and off" The level is read "when transaction commit begins", so it can be set per transaction with SET LOCAL. "Certain utility commands, for instance DROP TABLE, are forced to commit synchronously", as is PREPARE TRANSACTION. Transactions replay in commit order, so "if transaction B made changes relying on the effects of a previous transaction A, it is not possible for A's effects to be lost while B's effects are preserved."

"The risk that is taken by using asynchronous commit is of data loss, not data corruption." — PostgreSQL documentation, 28.4. Asynchronous Commit

text
     Session A (synchronous_commit=off)        WAL writer                Disk
1    INSERT INTO events ...; COMMIT;
2    client sees COMMIT at t=0 ms
3                                              sleeps (wal_writer_delay=200ms)
4    -- OS crash at t=150 ms --
5    after restart: the event row is gone; the database is consistent
     -- with synchronous_commit=on, step 2 would wait for one WAL flush

Real scenario: the docs' own examples: "a bank would certainly not use asynchronous commit for a transaction recording an ATM's dispensing of cash", but event logging needs no such guarantee. Typical asynchronous candidates: click streams, metrics, session touches, cache tables. A pg_ctl stop -m immediate is "equivalent to a server crash, and will therefore cause loss of any unflushed asynchronous commits".

ProductPer-transaction relaxationServer-wide relaxation
PostgreSQLSET LOCAL synchronous_commit = offALTER SYSTEM SET synchronous_commit = off
MySQL InnoDBnone (variable is global)innodb_flush_log_at_trx_commit = 0/2
SQL ServerCOMMIT TRANSACTION WITH (DELAYED_DURABILITY = ON) when database is ALLOWEDALTER DATABASE ... SET DELAYED_DURABILITY = FORCED
OracleCOMMIT WRITE NOWAIT (with BATCH or IMMEDIATE)COMMIT_WAIT/COMMIT_LOGGING parameters
MongoDBwrite concern j: false / w: 1default write concern

Fix / how to use it:

sql
BEGIN;
SET LOCAL synchronous_commit = off;      -- this transaction only
INSERT INTO page_views (user_id, path) VALUES (42, '/pricing');
COMMIT;
-- equivalent, parameterisable from drivers: SELECT set_config('synchronous_commit', 'off', true);

Group commit: commit_delay and commit_siblings Important ​

In plain words: if ten sessions commit at the same moment, one flush can make all ten durable.

Common misunderstanding: "commit_delay is a kind of asynchronous commit." It is not: it is still synchronous, the docs say it "is ignored during an asynchronous commit". It only makes a flush leader wait a little so more commits ride along.

Definition: with the default commit_delay = 0, PostgreSQL already groups commits that arrive while the previous flush is running (the docs' "gangway effect" at high client counts). Setting commit_delay (microseconds) makes the group commit leader sleep before flushing, but only if at least commit_siblings (default 5) other transactions are active. The manual's starting point: half of the single 8 kB flush time reported by pg_test_fsync. Too high a value adds latency and can reduce throughput.

text
     S1            S2            S3            Leader flush
1    COMMIT                                    S1 becomes leader, sleeps commit_delay
2                  COMMIT                      S2 queues behind leader
3                                COMMIT        S3 queues behind leader
4                                              one fdatasync covers S1..S3
5    ack           ack           ack

Real scenario: an ingestion API on network storage where one flush costs 2 ms; 200 concurrent clients; raising commit_delay to 1000 µs lifts commits per second without touching durability. On a local NVMe with 50 µs flushes it does nothing useful.

ProductGroup commit
PostgreSQLImplicit; tunable with commit_delay, commit_siblings
MySQLBinary log group commit (flush, sync, commit stages); binlog_group_commit_sync_delay
Redisappendfsync always still does "a single write and a single fsync" per event-loop batch
KafkaBatching on the producer (linger.ms, batch.size)
SQLiteNo: one writer at a time; batch in one transaction instead

Fix / how to use it: measure first (pg_test_fsync), then ALTER SYSTEM SET commit_delay = 500; ALTER SYSTEM SET commit_siblings = 5; SELECT pg_reload_conf(); and compare throughput with pgbench -c 64.

Torn pages and full_page_writes Important ​

In plain words: a page is 16 disk sectors; if power fails halfway through writing it, the page on disk is half new, half old, and a "change this row" log record cannot repair that.

Common misunderstanding: "A battery-backed controller makes full_page_writes unnecessary." The manual: BBU controllers "do not prevent partial page writes unless they guarantee that data is written to the BBU as full (8kB) pages."

Definition: with full_page_writes = on (default) PostgreSQL "writes the entire content of each disk page to WAL during the first modification of that page after a checkpoint". Because replay always starts at a checkpoint, one full-page image (FPI) per page per checkpoint cycle is enough: recovery restores the image, then applies later deltas. Turning it off is safe only on storage that cannot tear writes (the docs name ZFS). wal_compression (off by default; pglz, lz4, zstd) compresses FPIs; wal_log_hints also logs FPIs for hint-bit-only changes, and is implied when data checksums are on.

Torn page: 8 kB page = 16 x 512-byte sectors; power fails mid-writeon disksectors 1-9: new versionsectors 10-16: old version (power lost)checksum failsRow-level redo alone cannot fix it"insert tuple at offset 3" assumes a sane page;the header and line pointers may be from twodifferent versions of the page.full_page_writes = on (PostgreSQL default)first change of each page after a checkpointlogs the whole 8 kB image (FPI) in the WAL;later changes log only the delta.checkpointchange 1 + FPI 8 kBchange 2 deltachange 3 deltatorn writeRecovery1. overwrite the torn page with the FPI from change 12. replay change 2 and change 3 deltas on top3. page is consistent again; data checksum verifiescost: more WAL right after every checkpointInnoDB: doublewrite bufferwrite pages to doublewrite filesfirst (one fsync), then in place;recovery copies the good pageback, then applies redo
text
     Checkpoint at LSN 0/5000000
1    UPDATE row on page 88 -> WAL: FPI of page 88 (8 kB) + change     @0/5000100
2    UPDATE row on page 88 -> WAL: delta only                          @0/5002100
3    checkpointer writes page 88: sectors 1..9 written, power lost
4    restart: redo from 0/5000000
5    record @0/5000100 has FPI -> page 88 overwritten with the image
6    record @0/5002100 applied on top -> page 88 consistent

Real scenario: WAL volume doubles right after every checkpoint (FPIs); pg_stat_wal.wal_fpi explains it. Shortening checkpoint_timeout to "recover faster" multiplies FPIs and makes the server slower. A team turns off full_page_writes on ext4 for speed and gets "invalid page in block" after a power cut.

ProductTorn-page protectionKnob
PostgreSQLFull-page images in WALfull_page_writes (on)
MySQL InnoDBDoublewrite bufferinnodb_doublewrite (ON, DETECT_AND_RECOVER, DETECT_ONLY, OFF)
SQLiteRollback journal holds original pages; WAL holds whole new pagesjournal_mode
ZFS / copy-on-write file systemsNever overwrite in place—

Fix / how to use it:

sql
SHOW full_page_writes;                                 -- on
ALTER SYSTEM SET wal_compression = 'lz4';              -- smaller FPIs, needs a build with lz4
SELECT pg_reload_conf();
SELECT wal_fpi, pg_size_pretty(wal_bytes) AS total FROM pg_stat_wal;

Checkpoints: checkpoint_timeout, max_wal_size, spread checkpoints and checkpoint storms Must-know ​

In plain words: every so often the database writes all dirty pages to their files and writes down "everything before here is already on disk", so a restart only has to replay WAL from that point.

Common misunderstanding: "Checkpoint more often to be safer." More frequent checkpoints do not make commits more durable; they shorten recovery but cost more page writes and more full-page images.

Definition: "At checkpoint time, all dirty data pages are flushed to disk and a special checkpoint record is written to the WAL file." The checkpointer starts one every checkpoint_timeout (default 5min, range 30s to 1 day) "or if max_wal_size is about to be exceeded, whichever comes first" (default 1 GB, a soft limit). Writes are spread: checkpoint_completion_target (default 0.9) paces them to finish at 90% of the interval; checkpoint_flush_after (256kB on Linux) pushes them to the device gradually so the final fsync does not stall. If size-triggered checkpoints come closer than checkpoint_warning (30s), the log says to raise max_wal_size. After a checkpoint, WAL before the redo record can be recycled. You can force one with CHECKPOINT. On a standby the equivalent is a restartpoint.

A checkpoint storm is the pathological loop: max_wal_size too small for the write rate → checkpoints triggered by size every few seconds (num_requested ≫ num_timed) → each one floods the disk with page writes → every page touched afterwards emits an FPI → WAL grows faster → the next checkpoint comes even sooner. Latency spikes line up with checkpoint starts.

text
     t        WAL since last ckpt     Event
1    00:00    0                        checkpoint starts (timed), redo point = LSN A
2    00:00-04:30                       dirty pages written at a paced rate (target 0.9)
3    04:30    ~700 MB                  checkpoint done: fsync data files, checkpoint record, pg_control
4    05:00                             next timed checkpoint, redo point = LSN B
     -- storm variant, max_wal_size = 256MB, bulk load writing 50 MB/s:
5    00:05    256 MB                   requested checkpoint #1
6    00:10    256 MB                   requested checkpoint #2  -> log: "checkpoints are occurring too frequently"

Real scenario: p99 latency spikes every 5 minutes on a busy OLTP server (checkpoint end fsync); a nightly COPY that fills the log with "checkpoints are occurring too frequently" warnings; recovery after a crash taking 20 minutes because max_wal_size was set to 100 GB and checkpoint_timeout to 1 hour.

ProductCheckpoint styleMain knobs
PostgreSQLPeriodic full (spread) checkpointcheckpoint_timeout, max_wal_size, checkpoint_completion_target
MySQL InnoDBFuzzy checkpoint, continuous flushing of oldest dirty pagesinnodb_redo_log_capacity, innodb_io_capacity, innodb_max_dirty_pages_pct
SQLite WAL modeCopy WAL pages back into the database filewal_autocheckpoint (about 1000 pages)
MongoDB WiredTigerPeriodic checkpoint plus journal for changes since itJournal storage.journal.commitIntervalMs

Fix / how to use it:

sql
SELECT num_timed, num_requested, write_time, sync_time, buffers_written
FROM pg_stat_checkpointer;                      -- PostgreSQL 17+; pg_stat_bgwriter before 17
ALTER SYSTEM SET max_wal_size = '16GB';         -- size so that checkpoints are time-triggered
ALTER SYSTEM SET checkpoint_timeout = '15min';  -- longer interval, fewer FPIs, longer recovery
SELECT pg_reload_conf();

Background writer and WAL writer Good to know ​

In plain words: two helper processes: one trickles dirty table pages out so backends find clean buffers, the other flushes WAL for asynchronous commits.

Common misunderstanding: "The background writer is what makes data durable." It writes pages that are already protected by WAL; its job is latency (backends not writing pages themselves), not durability.

Definition: the background writer wakes every bgwriter_delay (200 ms), writes up to bgwriter_lru_maxpages (100) dirty buffers based on recent demand × bgwriter_lru_multiplier (2.0), and nudges the kernel with bgwriter_flush_after (512kB on Linux). Its counters are buffers_clean and maxwritten_clean in pg_stat_bgwriter. The WAL writer flushes WAL every wal_writer_delay (200 ms) or after wal_writer_flush_after (1MB), which bounds the loss window of synchronous_commit = off. wal_buffers (default 1/32 of shared_buffers, 64kB to 16MB) holds WAL not yet written; pg_stat_wal.wal_buffers_full counts forced writes when it is too small.

text
     Backend                  Buffer pool                     Background writer
1    needs a free buffer      clock sweep finds dirty page
2    writes it itself (slow)  -- without bgwriter
3                                                             every 200 ms: write ~2x recent demand
4    finds a clean buffer     -- with bgwriter keeping ahead

Real scenario: pg_stat_io shows many writes with backend_type = 'client backend': backends are doing the background writer's job; raise bgwriter_lru_maxpages. wal_buffers_full climbing during bulk loads: raise wal_buffers.

ProcessPostgreSQLInnoDB equivalent
Page cleanerbackground writerpage cleaner threads (innodb_page_cleaners)
Log flusherWAL writerlog writer / log flusher threads
Checkpointercheckpointerpage cleaners + checkpoint LSN advance

Fix / how to use it: SELECT backend_type, context, writes, fsyncs FROM pg_stat_io WHERE writes > 0 ORDER BY writes DESC;

WAL retention, recycling and archiving Important ​

In plain words: old WAL files are renamed and reused once no checkpoint, archive or replica needs them; if any of those three falls behind, pg_wal grows until the disk is full.

Common misunderstanding: "max_wal_size caps the size of pg_wal." It is a soft limit for checkpoint pacing. A failing archive_command, a stale replication slot or a high wal_keep_size all keep WAL past it.

Definition: below max_wal_size, PostgreSQL recycles ("renamed to become future segments") enough segments for the next cycle, never fewer than min_wal_size (80 MB). wal_recycle = on renames instead of creating; wal_init_zero = on zero-fills new files (both worth turning off on copy-on-write file systems). With archive_mode = on (requires wal_level ≥ replica), each completed segment is handed to archive_command (%p path, %f file name; must return zero only on success) or archive_library, and "old segments cannot be removed or recycled until they are archived". archive_timeout forces a segment switch so a quiet server still archives every minute or so. Archived WAL is the raw material for PITR.

text
     t      archive_command           pg_wal size     Consequence
1    09:00  ok                        1.1 GB          normal recycling
2    09:05  fails (bucket creds expired)  1.3 GB      segments wait, logged as failed
3    12:00  still failing             40 GB           disk alert
4    12:40  still failing             disk full       PANIC while writing WAL; server stops
5    fix creds -> archiver catches up -> segments recycled

Real scenario: an abandoned logical replication slot from a CDC tool holds WAL for weeks; archiving to object storage breaks after a credential rotation; archive_command = '/bin/true' "effectively disables archiving, but also breaks the chain of WAL files needed for archive recovery".

RetainerWhere to see itFix
Failing archiverpg_stat_archiver.failed_count, last_failed_walFix the command; never delete from pg_wal by hand
Replication slotpg_replication_slots (restart_lsn, wal_status)Drop unused slots; set max_slot_wal_keep_size
wal_keep_sizeSHOW wal_keep_sizeLower it or use slots
WAL summarizationsummarize_wal, wal_summary_keep_timeExpected while incremental backups need it

Fix / how to use it:

sql
SELECT archived_count, failed_count, last_failed_wal, last_failed_time FROM pg_stat_archiver;
SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;
-- postgresql.conf (restart for archive_mode):
-- archive_mode = on
-- archive_command = 'test ! -f /mnt/archive/%f && cp %p /mnt/archive/%f'
-- archive_timeout = 60

Crash recovery, step by step Must-know ​

In plain words: on restart after a crash, the database finds the last checkpoint and replays the log forward until the log ends; only then does it accept connections.

Common misunderstanding: "Recovery has to read the whole WAL." It reads only from the last checkpoint's redo record onward, which is why checkpoint settings are also your recovery-time budget.

Definition (PostgreSQL): the manual: "at the start of recovery, the server first reads pg_control and then the checkpoint record; then it performs the REDO operation by scanning forward from the WAL location indicated in the checkpoint record." Before replay, recovery_init_sync_method (fsync by default, syncfs on Linux) syncs the data directory so replay builds on durable files. Each record is applied unless the page's LSN shows it is already there; full-page images replace torn pages; recovery_prefetch (try) reads ahead the blocks the WAL will need. Replay stops at the first record whose CRC-32C fails or that is incomplete: the torn tail of the log. Then an end-of-recovery checkpoint is written and connections are accepted; until then clients get 57P03 cannot_connect_now ("the database system is starting up" / "in recovery mode"). Uncommitted transactions need no undo pass (see the timeline diagram). With restart_after_crash = on, the crash of any backend makes the postmaster terminate the others and run this procedure; clients see 57P02 crash_shutdown.

Crash recovery: redo from the last checkpoint's redo recordWAL / LSNredo recordredo_lsncheckpoint recordcheckpoint_lsnT1 COMMITT2 COMMITT3 no commitcrash1. Read pg_controlfind latest checkpoint,then its redo record2. REDO: replay every record forwardskip if page LSN already newer; restore fullpage images; stop at first bad CRC-32C3. End of recoverycheckpoint, then acceptconnections (57P03 before)replayed rangePostgreSQL: no undo passT3's row versions are replayed but carry an xidwith no commit record, so MVCC treats them asaborted; VACUUM removes them later.ARIES / InnoDB: analysis, redo, undorepeat history (redo all, losers too), then rollback T3 using undo logs; ARIES logs each undostep as a compensation log record (CLR).
text
     Server log (illustrative, abridged; wording varies by version)
1    LOG:  server process (PID 812) was terminated by signal 9: Killed
2    LOG:  terminating any other active server processes
3    LOG:  all server processes terminated; reinitializing
4    LOG:  database system was interrupted; last known up at ...
5    LOG:  database system was not properly shut down; automatic recovery in progress
6    LOG:  redo starts at 0/1A2B3C8
7    LOG:  redo done at 0/1F00010 ...
8    LOG:  checkpoint starting: end-of-recovery immediate wait
9    LOG:  database system is ready to accept connections

Real scenario: OOM killer hits one backend and every connection drops for a few seconds; a Kubernetes liveness probe kills a recovering pod because recovery takes longer than the probe allows, and recovery restarts from scratch each time; a standby promoted after the primary died replays to the end of received WAL and starts a new timeline.

StepPostgreSQLMySQL InnoDB
Find start pointpg_control → checkpoint → redo LSNCheckpoint LSN in redo file header
RedoForward replay, page-LSN check, FPIsTablespace discovery, then redo application "before accepting any connections"
Torn pagesFull-page imagesDoublewrite buffer
Losers (uncommitted)Invisible via MVCC; no undo passRolled back from undo logs, can take "three or four times" as long as they ran
Binlog consistency—Prepared transactions completed or rolled back against the binlog
Emergency startpg_resetwal (last resort)innodb_force_recovery 1..6

Fix / how to use it:

sql
SELECT checkpoint_lsn, redo_lsn, redo_wal_file, timeline_id, checkpoint_time
FROM pg_control_checkpoint();
SELECT pg_is_in_recovery();

ARIES in detail: analysis, redo, undo and CLRs Good to know ​

In plain words: ARIES restarts in three passes: figure out what was going on, redo everything exactly as it happened, then roll back the transactions that never committed, logging each rollback step so a crash during recovery is also safe.

Common misunderstanding: "Redo only replays committed transactions." ARIES deliberately replays the losers too ("repeating history"), so pages reach the exact pre-crash state; only then are losers undone using normal rollback logic.

Definition: analysis starts at the last checkpoint and rebuilds the dirty page table and the transaction table, which give the redo start point (the smallest recovery LSN of any dirty page). Redo scans forward, applying a record only if the page LSN is older. Undo walks each loser backwards and writes a compensation log record (CLR) for every step undone; CLRs are redo-only and point to the next record to undo, so repeated crashes during recovery never undo the same change twice. The paper also uses the LSN to avoid undoing an effect that never reached the page.

text
     Log:  [ckpt] T1:upd p1  T2:upd p2  T1:commit  T2:upd p3  ---crash---
1    Analysis: T1 committed, T2 is a loser; dirty pages p1, p2, p3
2    Redo:     apply p1, p2, p3 updates (T2's too) if page LSN is older
3    Undo T2:  revert p3, write CLR(p3, undoNext -> p2 update)
4              revert p2, write CLR(p2, undoNext -> none); write T2 end
5    crash during step 4? next restart redoes the CLRs and continues from undoNext

Real scenario: this is why a crash in the middle of a long InnoDB DELETE makes the restart slow: InnoDB redoes, then has to roll the delete back. It is also why PostgreSQL restarts quickly after the same crash: there is nothing to undo, VACUUM cleans the aborted versions later.

EnginePassesUndo
ARIES (DB2 lineage)Analysis, redo, undoCLRs
SQL ServerAnalysis, redo, undoLog-based
MySQL InnoDBRedo, then rollback of incomplete transactionsUndo logs
PostgreSQLRedo onlyNone needed (MVCC + commit log)

Fix / how to use it: nothing to configure; know it to predict restart time (PostgreSQL: proportional to WAL since checkpoint; InnoDB: plus rollback of big open transactions).

Checksums: data checksums and WAL CRC-32C Important ​

In plain words: a checksum on every page and every WAL record lets the database notice that the disk returned garbage instead of silently using it.

Common misunderstanding: "Checksums repair corruption." They only detect it. Repair comes from a replica, a backup, or full-page images in WAL.

Definition: "Each individual record in a WAL file is protected by a CRC-32C (32-bit) check", verified during crash recovery, archive recovery and replication. Data checksums cover data pages only (not pg_xact, temporary files, or RAM; the manual assumes ECC memory). They are on by default since PostgreSQL 18, "enabled or disabled at the full cluster level", toggled offline with pg_checksums, visible via SHOW data_checksums. A failure raises XX001 data_corrupted ("invalid page in block ..."); ignore_checksum_failure bypasses the check while salvaging. With checksums on, hint-bit changes are WAL-logged (like wal_log_hints), which adds some WAL.

text
     Reader                         Page 1234 of orders
1    SELECT ... (needs page 1234)   read from disk
2                                   computed checksum != stored checksum
3    ERROR:  invalid page in block 1234 of relation base/16384/16397   (XX001)
4    -- without checksums: the row is read as garbage or a wrong value, silently

Real scenario: a SAN firmware bug flips bits; checksums turn silent wrong answers into loud errors that point at one block; you restore that table from a replica. pg_checksums --check on a stopped copy before an upgrade.

ProductPage checksumsLog checksums
PostgreSQLdata_checksums (default on since 18)CRC-32C per WAL record
MySQL InnoDBinnodb_checksum_algorithm (crc32)Redo block checksums
SQL Server, OraclePage/block checksums (product-specific settings)Log block checks

Fix / how to use it:

sql
SHOW data_checksums;                       -- on
SELECT datname, checksum_failures, checksum_last_failure FROM pg_stat_database WHERE checksum_failures > 0;

fsyncgate (2018) and data_sync_retry Must-know ​

In plain words: PostgreSQL used to retry a failed fsync(); on Linux the retry could succeed even though the data had been thrown away. Now PostgreSQL crashes on purpose and recovers from WAL.

Common misunderstanding: "An I/O error that the database retried successfully is harmless." On Linux before 4.13, the PostgreSQL wiki records, "buffers are marked clean after errors, so retrying fsync() can falsely report success and the modified buffer can be thrown away at any time due to memory pressure."

Definition: PostgreSQL's checkpointer assumed "that a successful call to fsync() means that all data for a file is on disk". The wiki's "Fsync Errors" page (the "fsyncgate 2018" thread) shows that, depending on kernel version, write-back errors could be lost, reported only to file descriptors opened before the error, or reported once. The fix: data_sync_retry = off (default) makes PostgreSQL "raise a PANIC-level error on failure to flush modified data files", so the server restarts and replays WAL instead of trusting the page cache. The change was backpatched to 9.4 and later; the wiki notes "Similar changes were made in InnoDB/MySQL, WiredTiger/MongoDB".

"As of this PostgreSQL 12 commit, PostgreSQL will now PANIC on fsync() failure." — PostgreSQL wiki, Fsync Errors

text
     Checkpointer                 Kernel                          Disk
1    write(page 7)                page cached, dirty
2                                 background writeback -> EIO     bad sector / thin pool full
3                                 page marked CLEAN, error noted
4    fsync() -> EIO               (error reported once)
5    old: retry fsync() -> 0      new data is gone; checkpoint "succeeds"; WAL recycled -> data lost forever
6    new: PANIC, restart, redo from last good checkpoint using WAL that was never recycled

Real scenario: a thin-provisioned volume runs out of space and writes fail with EIO; NFS or a network block device blips; with the old behaviour these turned into silent loss.

ProductBehaviour on flush failure
PostgreSQL 12+ (and backpatched)PANIC, crash recovery from WAL (data_sync_retry = off)
MySQL InnoDB, MongoDB WiredTiger"Similar changes were made" after fsyncgate, per the PostgreSQL wiki (vendor details not covered here)
SQLiteReturns SQLITE_IOERR to the application

Fix / how to use it: leave data_sync_retry = off; alert on PANIC in logs; treat storage errors as hardware incidents. Kernel ≥ 4.13 is better at reporting, not a reason to retry.

The layers below: drive caches, battery-backed controllers and cloud disks Important ​

In plain words: the database can only ask for a flush; whether the bytes really survive a power cut is decided by the OS, the controller and the drive, and on cloud volumes by the provider's replicated storage.

Common misunderstanding: "My cloud volume is replicated, so a crash cannot lose acknowledged data." Volume replication protects against a disk failing; it does not help if the database acknowledged before flushing (synchronous_commit = off, innodb_flush_log_at_trx_commit = 2) or if the instance and its volume are lost together with an unreplicated WAL.

Definition: PostgreSQL's reliability chapter names three caches: the OS buffer cache (defeated by fsync), the disk controller cache ("Better controller cards have battery-backup units (BBUs)") and the drive cache ("Consumer-grade IDE and SATA drives are particularly likely to have write-back caches that will not survive a power failure. Many solid-state drives (SSD) also have volatile write-back caches."). Tools: hdparm -I / hdparm -W 0, sdparm --get=WCE, pg_test_fsync, diskchecker.pl. MySQL's manual says the same: "Many operating systems and some disk hardware fool the flush-to-disk operation." Cloud block storage publishes durability as an annual failure rate: Amazon EBS gp3 and gp2 "99.8% - 99.9% durability (0.1% - 0.2% annual failure rate)", io2 Block Express "99.999% durability (0.001% annual failure rate)"; Google Persistent Disk ranges from "Better than 99.99%" (zonal standard) to "Better than 99.9999%" (regional SSD), and regional PD replicates across two zones. These numbers are about losing the volume, not about your commit protocol.

text
     Layer                         Honest flush               Lying flush
1    PostgreSQL fdatasync(pg_wal)  waits                       waits
2    kernel                        sends FLUSH to device       sends FLUSH to device
3    drive cache                   writes to media, then OK    says OK, keeps data in DRAM
4    power cut                     commit survives             commit lost; maybe torn pages

Real scenario: a fast pg_test_fsync result proves nothing on its own: a datacenter NVMe with power-loss protection is fast and honest, a consumer SSD can be fast because it lies, and only a power-pull test (diskchecker.pl) tells them apart. A network volume pays a network round trip per flush and benefits most from group commit.

StorageFlush honest?Notes
Enterprise SSD/NVMe with power-loss protectionYesCapacitors drain cache to flash
Consumer SSD / SATA disk with write cache onOften notDisable write cache or test with diskchecker.pl
RAID with BBU write-back cacheYes, while the battery is healthyMonitor the battery; file-system write barriers can negate the BBU benefit
Amazon EBS, Google Persistent DiskProvider-managed; durability published per volume typeNetwork latency per flush: group commit helps
ZFSYes; issues its own cache flushesAllows full_page_writes = off

Fix / how to use it: run pg_test_fsync on new hardware; disable volatile write caches you cannot trust; on macOS use wal_sync_method = fsync_writethrough; never use fsync = off because "high quality hardware alone is not a sufficient justification".

Replication as durability Important ​

In plain words: a single server's WAL survives a crash, not the loss of the server; for that, the WAL must be on another machine before you say "committed".

Common misunderstanding: "An asynchronous replica means no data loss on failover." Asynchronous replication loses whatever the primary had not yet shipped.

Definition: PostgreSQL with synchronous_standby_names set and synchronous_commit = on waits until a synchronous standby has flushed the commit record; "This ensures the transaction will not be lost unless both the primary and all synchronous standbys suffer corruption of their database storage." MySQL semi-synchronous replication, MongoDB w: "majority", Kafka acks=all with min.insync.replicas, and CockroachDB's Raft quorum ("a quorum of replicas agrees on any changes to a range before those changes are committed") are the same idea. Details and failover live in Replication, Read Replicas & Failover.

text
     Primary                       Sync standby
1    COMMIT: flush local WAL
2    send WAL                      receive, write, flush
3                                  reply flush LSN
4    ack client                    -- primary now dies: standby has the commit

Real scenario: a payment platform runs synchronous_standby_names = 'ANY 1 (s1, s2)' across two zones; a node loss costs no acknowledged payment.

ProductDurable-on-another-node setting
PostgreSQLsynchronous_standby_names + synchronous_commit = on/remote_apply
MySQLSemi-synchronous replication, Group Replication
MongoDBwrite concern w: "majority" (implies j: true when writeConcernMajorityJournalDefault is true)
Kafkaacks=all + min.insync.replicas (e.g. RF 3, min ISR 2)
CockroachDBRaft quorum per range (3 replicas minimum)

Fix / how to use it: ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (standby_a, standby_b)'; SELECT pg_reload_conf();

MySQL InnoDB in depth ​

InnoDB solves the same problem with different pieces: a redo log for durability, undo logs for rollback and MVCC, a doublewrite buffer for torn pages, and the binary log (binlog) for replication and PITR, kept consistent with the redo log by an internal two-phase commit.

InnoDB redo log capacity (innodb_redo_log_capacity) Important ​

In plain words: the redo log is InnoDB's WAL, a fixed amount of disk that must hold every change not yet flushed to the data files.

Common misunderstanding: "A small redo log saves disk and is otherwise harmless." When the redo log fills, InnoDB must flush dirty pages aggressively before accepting more writes: the InnoDB form of a checkpoint storm.

Definition: "The redo log is a disk-based data structure used during crash recovery to correct data written by incomplete transactions." Its size is innodb_redo_log_capacity (default 104857600 bytes = 100 MB in MySQL 8.4, dynamic, maximum 512 GB), spread over 32 #ib_redoN files in #innodb_redo/ (spares carry _tmp). "Redo log data is appended as data modifications occur, and the oldest data is truncated as the checkpoint progresses." --innodb-dedicated-server sizes it automatically. ALTER INSTANCE DISABLE INNODB REDO_LOG exists for loading a new instance only; a crash while disabled leaves "[ERROR] [MY-013598] [InnoDB] Server was killed when Innodb Redo logging was disabled. Data files could be corrupt."

text
     Redo capacity 100 MB, write rate 20 MB/s
1    t=0    checkpoint LSN = A, current LSN = A
2    t=4s   current - checkpoint = 80 MB  -> page cleaners flush harder
3    t=5s   log nearly full               -> user threads wait for flushing (stall)
4    SET GLOBAL innodb_redo_log_capacity = 8589934592;   -- 8 GB, resizes online

Real scenario: periodic write stalls on a MySQL 8.4 server left at the 100 MB default; Innodb_redo_log_current_lsn - Innodb_redo_log_checkpoint_lsn close to capacity during peaks.

VariableMeaning
innodb_redo_log_capacityTotal redo size (supersedes innodb_log_file_size × innodb_log_files_in_group)
Innodb_redo_log_checkpoint_lsn / _current_lsn / _flushed_to_disk_lsnPositions to compute checkpoint age and flush lag
innodb_log_buffer_sizeIn-memory log buffer
performance_schema.innodb_redo_log_filesSTART_LSN/END_LSN per file

Fix / how to use it:

sql
SHOW GLOBAL STATUS WHERE Variable_name IN
  ('Innodb_redo_log_current_lsn','Innodb_redo_log_checkpoint_lsn','Innodb_redo_log_capacity_resized');
SET GLOBAL innodb_redo_log_capacity = 8589934592;

innodb_flush_log_at_trx_commit Must-know ​

In plain words: InnoDB's version of synchronous_commit, but server-wide.

Common misunderstanding: "2 is safe because it still writes at every commit." It writes to the OS at every commit but flushes once per second, so a mysqld crash keeps the data while an OS crash or power loss can lose about a second.

Definition: "The default setting of 1 is required for full ACID compliance. Logs are written and flushed to disk at each transaction commit. With a setting of 0, logs are written and flushed to disk once per second. ... With a setting of 2, logs are written after each transaction commit and flushed to disk once per second." The interval is innodb_flush_log_at_timeout (1 to 2700 s, default 1), "not 100% guaranteed". "InnoDB crash recovery works regardless of the innodb_flush_log_at_trx_commit setting. Transactions are either applied entirely or erased entirely."

text
     Setting   mysqld crash        OS crash / power loss
1    1         nothing lost        nothing lost (if the disk is honest)
2    2         nothing lost        up to ~1 s lost
3    0         up to ~1 s lost     up to ~1 s lost

Real scenario: a replica used only for analytics runs 2 to keep up with the primary; a primary that takes payments must run 1.

SettingWrite at commitFlush at commit
1yesyes
2yesno (once per innodb_flush_log_at_timeout)
0nono

Fix / how to use it: SET GLOBAL innodb_flush_log_at_trx_commit = 1; (Scope: Global; no per-session form.)

The doublewrite buffer Important ​

In plain words: before writing pages to their real place, InnoDB writes them to a scratch area and flushes it; if a page tears, the good copy is in the scratch area.

Common misunderstanding: "Doublewrite doubles the I/O." The manual: it "does not require twice as much I/O overhead or twice as many I/O operations", because the scratch writes go "in a large sequential chunk, with a single fsync()".

Definition: "The doublewrite buffer is a storage area where InnoDB writes pages flushed from the buffer pool before writing the pages to their proper positions in the InnoDB data files." innodb_doublewrite is ON (= DETECT_AND_RECOVER), DETECT_ONLY (metadata only, detects but does not fix torn pages) or OFF; innodb_doublewrite_dir places the files. Disabling is suggested only "when performing benchmarks". This is InnoDB's answer to torn pages; PostgreSQL's is full-page writes.

text
     Page cleaner                    Doublewrite files        Tablespace .ibd
1    batch of 64 dirty pages ->      sequential write + fsync
2                                                             write pages in place
3    power lost during step 2: page 900 torn in .ibd
4    recovery: checksum of page 900 fails -> copy from doublewrite -> apply redo

Real scenario: benchmarks that turn doublewrite off show higher throughput that production cannot have; atomic-write devices (the manual mentions Fusion-io) let InnoDB disable it safely.

PostgreSQL full-page writesInnoDB doublewrite
Where the good copy livesIn the WALIn doublewrite files
When it costsFirst change after each checkpointEvery page flush
Effect on WAL/redo sizeLarger WALNo effect on redo

Fix / how to use it: SHOW VARIABLES LIKE 'innodb_doublewrite%'; keep ON.

Binlog durability: sync_binlog and two-phase commit with InnoDB Must-know ​

In plain words: MySQL writes each commit to two logs (InnoDB redo and the binlog that replicas and PITR read); an internal two-phase commit makes sure both agree after a crash.

Common misunderstanding: "innodb_flush_log_at_trx_commit = 1 is enough." Without sync_binlog = 1 the binlog can lose transactions InnoDB kept, so replicas and PITR diverge from the primary.

Definition: with sync_binlog = 1 (default) the binlog is synced "before transactions are committed"; 0 leaves it to the OS; N syncs after N commit groups. On commit, InnoDB prepares the transaction (redo flushed with a prepare record and xid), the binlog is written and synced, then InnoDB commits. The manual: at restart, the server "scans the latest binary log file to collect transaction xid values and calculate the last valid position", then has InnoDB complete the prepared transactions that reached the binlog and truncates the binlog to that last valid position. "In MySQL 8.4, InnoDB support for two-phase commit in XA transactions is always enabled." The documented safe pair: "sync_binlog=1" and "innodb_flush_log_at_trx_commit=1".

text
     Step                                   Crash here means
1    InnoDB PREPARE (redo flushed, xid 77)  xid 77 not in binlog -> rolled back at restart
2    binlog write + fsync (sync_binlog=1)   xid 77 in binlog, prepared -> committed at restart
3    InnoDB COMMIT                          already committed

Real scenario: a primary with sync_binlog = 0 loses power; on restart InnoDB has rows that the binlog never recorded; a replica rebuilt from the binlog is missing them, and a PITR restore misses them too.

Setting pairPrimary after OS crashReplicas / PITR
sync_binlog=1, innodb_flush_log_at_trx_commit=1Nothing acknowledged lostConsistent with primary
sync_binlog=0, =1InnoDB intactBinlog may miss commits

Fix / how to use it: SET GLOBAL sync_binlog = 1; SET GLOBAL innodb_flush_log_at_trx_commit = 1; For multi-database atomicity across services, see Distributed SQL, Consensus & 2PC; this internal 2PC is between two logs of one server.

Per-engine behaviour ​

SQLite journal modes and PRAGMA synchronous Important ​

SQLite offers journal_mode = DELETE (default), TRUNCATE, PERSIST, MEMORY, WAL, OFF. In rollback modes the journal holds original pages and "the delete operation is the action that causes the transaction to commit". In WAL mode new pages are appended to the -wal file and copied back by a checkpoint, by default when the WAL reaches "about 1000 pages". PRAGMA synchronous: EXTRA (3) also syncs the directory after deleting the journal; FULL (2), "the default synchronous mode for a rollback journal", is "atomic, consistent, isolated, and durable (ACID) in WAL mode"; NORMAL (1) in WAL mode "is always consistent" but "does lose durability. A transaction committed in WAL mode with synchronous=NORMAL might roll back following a power loss or system crash"; OFF (0) can corrupt on OS crash or power loss. "Transactions are durable across application crashes regardless of the synchronous setting or journal mode." Details: SQLite in Depth.

Redis AOF and RDB Important ​

Redis is an in-memory store with two persistence options. RDB writes point-in-time snapshots by forking ("you should be prepared to lose the latest minutes of data"). AOF appends every write command, with appendfsync always ("Very very slow, very safe"), everysec (default: "you may lose 1 second of data if there is a disaster") or no (the kernel decides; "Normally Linux will flush data every 30 seconds"). Both can be combined; AOF rewrites start from an RDB preamble. Replication to a replica is asynchronous by default, so failover can lose acknowledged writes regardless of appendfsync. See Redis.

Kafka: replication instead of fsync Good to know ​

Kafka writes to the page cache and does not flush per message: "All data is immediately written to a persistent log on the filesystem without necessarily flushing to disk." log.flush.interval.messages defaults to 9223372036854775807 and log.flush.interval.ms is unset, so the broker leaves flushing to the OS. Durability comes from replication: the design document says Kafka does not "require the use of fsync on every write for our consistency guarantees as this can reduce performance by two to three orders of magnitude", and a crashed replica must fully re-sync before rejoining the ISR. Producers choose acks=0, acks=1 ("the record will be lost" if the leader fails before followers copy it) or acks=all ("the strongest available guarantee"), combined with min.insync.replicas (typical: replication factor 3, min ISR 2). The difference from a database: Kafka trades the single-node flush for several replicas in different failure domains holding the record in RAM.

What each product really does ​

ProductLogCommit defaultRelaxTorn pagesRecovery
PostgreSQLWAL, 16 MB segmentsFlush at commitsynchronous_commit = off per transactionFull-page writesRedo only
MySQL InnoDBRedo log + binlogFlush redo and binlog at commitinnodb_flush_log_at_trx_commit, sync_binlogDoublewriteRedo, rollback, binlog 2PC resolution
SQLiteRollback journal or WALsynchronous = FULLNORMAL in WAL modeJournal / WAL pagesRoll back hot journal or replay WAL
SQL ServerTransaction logFully durableDelayed durability (DISABLED / ALLOWED / FORCED)Page checksumsAnalysis, redo, undo
OracleOnline redo logsCOMMIT WRITE WAITCOMMIT WRITE NOWAIT, BATCHBlock checksumsRoll forward, roll back
MongoDB (WiredTiger)Journal + checkpointsJournal flushed every 100 ms (storage.journal.commitIntervalMs), or at once with j: truej: falseCheckpoint + journalLast checkpoint + journal
RedisAOF / RDBAOF everysec (if enabled)appendfsync no, RDB onlyNot applicableLoad RDB, replay AOF
KafkaPartition log segmentsPage cache, no fsyncacks=1/0Not applicableTruncate to high watermark, re-sync from leader
CockroachDBRaft log per rangeQuorum of replicasNot offered for writesStorage engineRaft log replay per range

Mechanics ​

Every PostgreSQL knob on one page Must-know ​

ParameterDefaultEffectChanging it
wal_levelreplicaWAL content: minimal, replica, logicalRestart
fsynconAny flush at allNever off in production
synchronous_commitonWhat a commit waits forAny time, per transaction
wal_sync_methodfdatasync (Linux)How WAL is flushedReload
full_page_writesonTorn-page protectionReload; keep on
wal_log_hintsoffFPIs for hint-bit changesRestart
wal_compressionoffCompress FPIs (pglz, lz4, zstd)Superuser, any time
wal_buffers-1 (1/32 of shared_buffers)Shared memory for unwritten WALRestart
wal_writer_delay / wal_writer_flush_after200ms / 1MBWAL writer cadence; async-commit loss windowReload
commit_delay / commit_siblings0 / 5Group commit waitSuperuser
checkpoint_timeout5minMax time between checkpointsReload
max_wal_size / min_wal_size1GB / 80MBCheckpoint trigger / recycling floorReload
checkpoint_completion_target0.9Spread of checkpoint writesReload
checkpoint_flush_after256kB (Linux)Gradual writeback during checkpointsReload
checkpoint_warning30sLog when size-triggered checkpoints are too closeReload
bgwriter_delay / bgwriter_lru_maxpages / bgwriter_lru_multiplier200ms / 100 / 2.0Background writer pacingReload
wal_recycle / wal_init_zeroon / onReuse/zero-fill segmentsReload
wal_keep_size0WAL kept for standbys without slotsReload
archive_mode / archive_command / archive_library / archive_timeoutoff / empty / empty / 0WAL archivingarchive_mode needs restart
data_sync_retryoffPANIC on flush failureRestart
restart_after_crashonAutomatic crash recovery after a backend diesReload
recovery_init_sync_methodfsyncSync data dir before recovery (syncfs on Linux)Reload
recovery_prefetchtryPrefetch blocks during replayReload
data_checksumson (initdb default since 18)Page checksumspg_checksums offline

Tools Important ​

ToolWhat it doesDanger
pg_waldumpDecodes WAL records: -s/-e LSN range, -x xid, -r resource manager, -w only FPIs, -z stats, -f follow"Can give wrong results when the server is running"; read-only
pg_controldataPrints pg_control: state, latest checkpoint, redo location, timelineNone
pg_test_fsyncTimes each wal_sync_method; suggests commit_delayNone
pg_checksumsEnable/disable/verify data checksums offlineMust run on a stopped cluster, every node
pg_resetwalClears WAL and resets pg_controlLast resort: "the database might contain inconsistent data due to partially-committed transactions"
pg_archivecleanupRemoves archived WAL older than a restartpointOnly for archives no other server needs
diskchecker.plTests whether a disk really persists flushed writes across power lossNeeds a second machine and a power pull

pg_resetwal is not a repair tool. Its manual: "It should be used only as a last resort, when the server will not start due to such corruption", and afterwards "You should immediately dump your data, run initdb, and restore." With -f and guessed values "the recovered database must be treated with even more suspicion than usual". Using it to "free disk space" in a full pg_wal throws away committed transactions. InnoDB's equivalent warning: "Values of 4 or greater can permanently corrupt data files" for innodb_force_recovery.

Error codes and log lines you will meet Must-know ​

Code / messageProductMeaningAction
57P03 cannot_connect_now ("the database system is starting up" / "in recovery mode")PostgreSQLRecovery in progressRetry with backoff; do not fail health checks too fast
57P02 crash_shutdownPostgreSQLAnother backend crashed; all sessions resetRetry the transaction; outcome of an in-flight COMMIT is unknown
57P01 admin_shutdownPostgreSQLFast/immediate shutdownRetry against the new primary
XX001 data_corrupted ("invalid page in block")PostgreSQLChecksum or page header failureRestore the relation from replica/backup
XX002 index_corruptedPostgreSQLCorrupt indexREINDEX
58030 io_errorPostgreSQLI/O errorHardware incident
53100 disk_fullPostgreSQLOut of space (often pg_wal)Free space elsewhere; fix archiver/slots
PANIC: could not fsync filePostgreSQLFlush failed; deliberate crash (data_sync_retry = off)Investigate storage; recovery replays WAL
LOG: checkpoints are occurring too frequentlyPostgreSQLcheckpoint_warning trippedRaise max_wal_size
[MY-013598] Server was killed when Innodb Redo logging was disabledMySQLCrash with redo disabledRe-initialise the instance and reload
NotEnoughReplicas / NotEnoughReplicasAfterAppendKafkaISR below min.insync.replicas with acks=allProducer retries; fix brokers
SQLITE_IOERR / SQLITE_FULLSQLiteI/O failure / disk fullSurface to the application

Solving the classic problems ​

Commit latency is too high ​

Two traps before any tuning. With a connection pool (database/sql, PgBouncer, Laravel's persistent connections), a bare SET synchronous_commit = off sticks to whichever pooled connection ran it, so a later payment on that connection silently commits asynchronously; use SET LOCAL (or set_config(..., true)) inside the transaction. And SET LOCAL outside a transaction block does nothing except log a warning, so it must run after BEGIN (inside BeginTx or DB::transaction).

SolutionHowAdvantageCost / limitation
Batch work into fewer transactionsInsert 500 rows per COMMIT, or COPYOne flush per batchBigger units of retry
Per-transaction async commitSET LOCAL synchronous_commit = off for low-value writesCommit returns immediately; database stays consistentLast ~600 ms of those writes can vanish on crash
Group commit tuningcommit_delay ≈ half of pg_test_fsync's 8 kB flush timeMore commits per flush, durability unchangedAdds latency at low concurrency
Faster WAL devicePut pg_wal on a low-latency NVMe with power-loss protectionEvery commit benefitsHardware cost
Asynchronous standby instead of synchronoussynchronous_standby_names = ''Removes network round tripFailover can lose commits
go
// One transaction per batch: one WAL flush for 500 rows instead of 500.
func InsertEvents(ctx context.Context, db *sql.DB, events []Event) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()
	// Low-value rows: allow the WAL writer to flush them (loss window ~3 x wal_writer_delay).
	if _, err := tx.ExecContext(ctx, `SELECT set_config('synchronous_commit', 'off', true)`); err != nil {
		return err
	}
	stmt, err := tx.PrepareContext(ctx, `INSERT INTO events (kind, payload) VALUES ($1, $2)`)
	if err != nil {
		return err
	}
	defer stmt.Close()
	for _, e := range events {
		if _, err := stmt.ExecContext(ctx, e.Kind, e.Payload); err != nil {
			return err
		}
	}
	return tx.Commit()
}
php
use Illuminate\Support\Facades\DB;

// Analytics events: one transaction, relaxed durability, scoped by SET LOCAL.
DB::transaction(function () use ($events) {
    DB::statement('SET LOCAL synchronous_commit = off');
    foreach (array_chunk($events, 500) as $chunk) {
        DB::table('events')->insert($chunk);   // multi-row INSERT
    }
});

The measurement helper used in the lab, with set_config(..., true) as a parameterised SET LOCAL:

go
// Package latency measures what a commit costs under each
// synchronous_commit level, using only database/sql.
package latency

import (
	"context"
	"database/sql"
	"fmt"
	"sort"
	"time"
)

// allowed keeps the level out of string-built SQL; set_config takes it as a
// bind parameter anyway, but an allowlist gives a clear error for typos.
var allowed = map[string]bool{
	"off": true, "local": true, "remote_write": true, "on": true, "remote_apply": true,
}

// Result is the distribution of n single-row commits.
type Result struct {
	Level    string
	P50, P99 time.Duration
}

// Measure runs n tiny transactions at the given level and returns p50/p99.
// set_config(name, value, true) is the function form of SET LOCAL: it lasts
// until the end of the transaction, so the pooled connection is left clean.
func Measure(ctx context.Context, db *sql.DB, level string, n int) (Result, error) {
	if !allowed[level] {
		return Result{}, fmt.Errorf("unknown synchronous_commit level %q", level)
	}
	samples := make([]time.Duration, 0, n)
	for i := 0; i < n; i++ {
		start := time.Now()
		tx, err := db.BeginTx(ctx, nil)
		if err != nil {
			return Result{}, err
		}
		if _, err := tx.ExecContext(ctx,
			`SELECT set_config('synchronous_commit', $1, true)`, level); err != nil {
			_ = tx.Rollback()
			return Result{}, err
		}
		if _, err := tx.ExecContext(ctx,
			`INSERT INTO commit_probe (note) VALUES ($1)`, level); err != nil {
			_ = tx.Rollback()
			return Result{}, err
		}
		if err := tx.Commit(); err != nil {
			return Result{}, err
		}
		samples = append(samples, time.Since(start))
	}
	if len(samples) == 0 {
		return Result{Level: level}, nil
	}
	sort.Slice(samples, func(a, b int) bool { return samples[a] < samples[b] })
	return Result{
		Level: level,
		P50:   samples[len(samples)/2],
		P99:   samples[(len(samples)*99)/100],
	}, nil
}

Before: relaxing durability for the whole database, payments included:

go
// Package before turns off synchronous commit for the whole database to make
// every write faster. It is bad design, not broken code.
package before

import (
	"context"
	"database/sql"
	"fmt"
)

// TuneForSpeed makes every future session commit without waiting for the WAL
// flush. ALTER DATABASE ... SET is the persistent, "global" form of
// SET synchronous_commit = off (a plain SET only touches one pooled connection).
//
// What is lost: after an OS or Postgres crash, up to about three times
// wal_writer_delay of acknowledged commits can vanish. That window now
// includes payments, not only the log-like writes we wanted to speed up.
func TuneForSpeed(ctx context.Context, db *sql.DB, dbName string) error {
	stmt := fmt.Sprintf("ALTER DATABASE %q SET synchronous_commit = off", dbName)
	_, err := db.ExecContext(ctx, stmt)
	return err
}

// RecordPayment returns nil to the caller, who then tells the customer "paid".
// With the setting above the row may not survive a crash a few ms later.
func RecordPayment(ctx context.Context, db *sql.DB, orderID string, cents int64) error {
	_, err := db.ExecContext(ctx,
		`INSERT INTO payments (order_id, amount_cents) VALUES ($1, $2)`, orderID, cents)
	return err
}

After: default durability for payments, per-transaction relaxation for audit rows, and checkpoint monitoring:

go
// Package after keeps the server default (synchronous_commit = on) and
// relaxes durability per transaction, only for writes we can afford to lose.
package after

import (
	"context"
	"database/sql"
)

// RecordPayment uses the default: when it returns nil, the commit record is
// flushed to local WAL (and to standbys, if synchronous_standby_names is set).
func RecordPayment(ctx context.Context, db *sql.DB, orderID string, cents int64) error {
	_, err := db.ExecContext(ctx,
		`INSERT INTO payments (order_id, amount_cents) VALUES ($1, $2)`, orderID, cents)
	return err
}

// RecordAudit trades a small loss window for latency. SET LOCAL lasts until
// the end of this transaction only, so a pooled connection is never left in
// asynchronous mode.
func RecordAudit(ctx context.Context, db *sql.DB, actor, action string) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback() // no-op after a successful Commit

	if _, err := tx.ExecContext(ctx, `SET LOCAL synchronous_commit = off`); err != nil {
		return err
	}
	if _, err := tx.ExecContext(ctx,
		`INSERT INTO audit_log (actor, action) VALUES ($1, $2)`, actor, action); err != nil {
		return err
	}
	return tx.Commit()
}

// CheckpointStats is what to graph or alert on.
type CheckpointStats struct {
	Timed     int64   // checkpoints started by checkpoint_timeout
	Requested int64   // checkpoints forced early, e.g. by max_wal_size
	WriteMS   float64 // time spent writing buffers during checkpoints
	SyncMS    float64 // time spent in fsync during checkpoints
	WALLSN    string  // pg_current_wal_lsn(), sample twice to get bytes/s
}

// ReadCheckpointStats reads pg_stat_checkpointer (PostgreSQL 17+; older
// servers keep these counters in pg_stat_bgwriter) and the current WAL position.
// A high Requested/Timed ratio means max_wal_size is too small for the write rate.
func ReadCheckpointStats(ctx context.Context, db *sql.DB) (CheckpointStats, error) {
	var s CheckpointStats
	err := db.QueryRowContext(ctx, `
		SELECT c.num_timed, c.num_requested, c.write_time, c.sync_time,
		       pg_current_wal_lsn()::text
		FROM pg_stat_checkpointer c`).
		Scan(&s.Timed, &s.Requested, &s.WriteMS, &s.SyncMS, &s.WALLSN)
	return s, err
}

The Laravel pair: one transaction that pays full durability for click-stream noise, then a split that keeps the order strict and relaxes only the events, plus an Artisan command for checkpoint stats.

php
<?php

namespace App\Jobs;

use App\Models\AnalyticsEvent;
use App\Models\Order;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;

// The order and its analytics events share ONE transaction, so both pay for
// one synchronous WAL flush and both are equally durable. The commit latency
// of every order includes writing click-stream noise we could afford to lose.
final class PlaceOrderAndTrack implements ShouldQueue
{
    public function __construct(private array $payload, private array $events) {}

    public function handle(): void
    {
        DB::transaction(function () {
            $order = Order::create($this->payload);

            foreach ($this->events as $event) {
                AnalyticsEvent::create($event + ['order_id' => $order->id]);
            }
        }); // synchronous_commit = on: waits for the WAL flush for everything above
    }
}
php
<?php

// app/Services/OrderPlacer.php
namespace App\Services;

use App\Models\AnalyticsEvent;
use App\Models\Order;
use Illuminate\Support\Facades\DB;

final class OrderPlacer
{
    public function place(array $payload, array $events): Order
    {
        // Default durability: the order is safe once this returns.
        $order = DB::transaction(fn () => Order::create($payload));

        // Separate transaction, relaxed durability. SET LOCAL ends with the
        // transaction, so the pooled connection is not left in async mode.
        // A crash may lose the last few events, never corrupt the database.
        DB::transaction(function () use ($events, $order) {
            DB::statement('SET LOCAL synchronous_commit = off');

            foreach ($events as $event) {
                AnalyticsEvent::create($event + ['order_id' => $order->id]);
            }
        });

        return $order;
    }
}

// app/Console/Commands/CheckpointStats.php
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class CheckpointStats extends Command
{
    protected $signature = 'db:checkpoint-stats';

    protected $description = 'Report checkpoint counters and the current WAL position (PostgreSQL 17+)';

    public function handle(): int
    {
        $row = DB::select(
            'SELECT num_timed, num_requested, write_time, sync_time, buffers_written,
                    pg_current_wal_lsn()::text AS wal_lsn
             FROM pg_stat_checkpointer'
        )[0];

        $this->table(
            ['timed', 'requested', 'write ms', 'sync ms', 'buffers', 'wal lsn'],
            [[$row->num_timed, $row->num_requested, $row->write_time,
              $row->sync_time, $row->buffers_written, $row->wal_lsn]]
        );

        if ($row->num_requested > $row->num_timed) {
            $this->warn('More requested than timed checkpoints: consider raising max_wal_size.');
        }

        return self::SUCCESS;
    }
}

Latency spikes at checkpoints (checkpoint storms) ​

SolutionHowAdvantageCost / limitation
Make checkpoints time-triggeredRaise max_wal_size until num_requested ≪ num_timedFewer, spread checkpoints; fewer FPIsMore WAL on disk; longer recovery
Keep spreadingcheckpoint_completion_target = 0.9Smooth I/ODo not lower it
Smaller writeback burstscheckpoint_flush_after, bgwriter_flush_afterAvoids end-of-checkpoint fsync stallCan hurt when data > shared_buffers but < page cache
Smaller FPIswal_compression = lz4Less WAL after each checkpointCPU
InnoDBRaise innodb_redo_log_capacityFewer flush stallsLonger recovery
sql
-- Are checkpoints requested by WAL volume rather than by time?
SELECT num_timed, num_requested,
       round(100.0 * num_requested / nullif(num_timed + num_requested, 0), 1) AS pct_requested,
       round(write_time / 1000) AS write_s, round(sync_time / 1000) AS sync_s
FROM pg_stat_checkpointer;
-- WAL per hour, to size max_wal_size (sample twice, an hour apart)
SELECT pg_current_wal_lsn();
go
// WALRate samples the WAL position twice; size max_wal_size to hold at
// least one checkpoint_timeout worth of WAL at peak.
func WALRate(ctx context.Context, db *sql.DB, every time.Duration) (bytesPerSec float64, err error) {
	var first string
	if err = db.QueryRowContext(ctx, `SELECT pg_current_wal_lsn()::text`).Scan(&first); err != nil {
		return 0, err
	}
	select {
	case <-time.After(every):
	case <-ctx.Done():
		return 0, ctx.Err()
	}
	var diff float64
	err = db.QueryRowContext(ctx,
		`SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), $1::pg_lsn)::float8`, first).Scan(&diff)
	return diff / every.Seconds(), err
}
php
// app/Console/Commands/WalRate.php (handle method)
$first = DB::selectOne('SELECT pg_current_wal_lsn()::text AS lsn')->lsn;
sleep(60);
$bytes = DB::selectOne(
    'SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), ?::pg_lsn) AS b', [$first]
)->b;
$this->info(sprintf('WAL rate: %.1f MB/min', $bytes / 1048576));

pg_wal is filling the disk ​

CauseHow to see itFix
archive_command failingpg_stat_archiver.failed_count rising, log linesFix the command; the archiver retries; segments then recycle
Inactive replication slotpg_replication_slots.active = false, large retained bytesSELECT pg_drop_replication_slot('name'); set max_slot_wal_keep_size
wal_keep_size too highSHOW wal_keep_sizeLower it
Long checkpoint interval at high write rateWAL between checkpoints ≈ max_wal_sizeExpected; size the disk
Someone deleted files from pg_walServer will not start, "could not open file"Restore; never delete WAL by hand
sql
SELECT pg_size_pretty(sum(size)) AS pg_wal_size FROM pg_ls_waldir();

The wrong fix is pg_resetwal or rm pg_wal/*: both discard WAL that recovery and replicas need.

The connection died during COMMIT (ambiguous commit) ​

When the network or server fails between sending COMMIT and receiving the reply, the client cannot know whether the commit is durable. Oracle's manual describes the same case for COMMIT WRITE WAIT: "A crash occurring after a successful write to the log can prevent the success message from returning to the client. In this case the client cannot tell whether or not the transaction committed."

SolutionHowAdvantageCost / limitation
Idempotency keyUNIQUE (idempotency_key); retry inserts the same keyRetry is safe; duplicate becomes 23505Needs a key from the caller
Ask the serverRecord pg_current_xact_id() before COMMIT; on failure call pg_xact_status(xid)Exact answer while status is retainedNULL for very old xids; prepared xacts show "in progress"
Upsert / natural idempotencyINSERT ... ON CONFLICT DO NOTHINGSimpleOnly where the row has a natural key
text
     Client                          Server
1    BEGIN; INSERT order key=K
2    SELECT pg_current_xact_id()  -> 9001
3    COMMIT -->                      commit record flushed
4    <-- connection reset (no reply)
5    new connection: SELECT pg_xact_status('9001')  -> committed
6    do NOT retry the insert; report success
go
// Package ambiguous handles the one commit outcome nobody tests: the
// connection drops while COMMIT is in flight, so the client cannot know
// whether the transaction is durable.
package ambiguous

import (
	"context"
	"database/sql"
	"errors"
)

// ErrUnknown means the server may or may not have committed.
var ErrUnknown = errors.New("commit outcome unknown")

// Status is what pg_xact_status reports for a recent transaction.
type Status string

// PlaceOrder records the transaction id before COMMIT. If Commit fails with
// anything but a clean server error, the caller can ask a fresh connection
// what happened instead of blindly retrying and charging twice.
func PlaceOrder(ctx context.Context, db *sql.DB, idemKey string, cents int64) (xid string, err error) {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return "", err
	}
	defer func() {
		if err != nil {
			_ = tx.Rollback()
		}
	}()

	// pg_current_xact_id() assigns a 64-bit xid (xid8) to this transaction.
	if err = tx.QueryRowContext(ctx, `SELECT pg_current_xact_id()::text`).Scan(&xid); err != nil {
		return "", err
	}
	// The idempotency key is UNIQUE: a retry after a lost ack hits 23505
	// instead of inserting a second order.
	if _, err = tx.ExecContext(ctx,
		`INSERT INTO orders (idempotency_key, amount_cents) VALUES ($1, $2)`,
		idemKey, cents); err != nil {
		return "", err
	}
	if err = tx.Commit(); err != nil {
		return xid, errors.Join(ErrUnknown, err)
	}
	return xid, nil
}

// Resolve asks the server, on a new connection, whether xid committed.
// The result is "committed", "aborted", "in progress", or NULL when the
// status is too old to be retained.
func Resolve(ctx context.Context, db *sql.DB, xid string) (Status, error) {
	var s sql.NullString
	err := db.QueryRowContext(ctx, `SELECT pg_xact_status($1::xid8)`, xid).Scan(&s)
	if err != nil {
		return "", err
	}
	if !s.Valid {
		return "", errors.New("status no longer retained; check by idempotency key")
	}
	return Status(s.String), nil
}
php
use Illuminate\Database\UniqueConstraintViolationException;
use Illuminate\Support\Facades\DB;

// Retry-safe order creation: the idempotency key turns a lost ack into a no-op.
try {
    DB::transaction(fn () => DB::table('orders')->insert([
        'idempotency_key' => $key,
        'amount_cents'    => $cents,
    ]));
} catch (UniqueConstraintViolationException) {
    // A previous call committed even though its reply was lost. The retry
    // itself comes from the caller (HTTP client, queue job); attempts: on
    // DB::transaction only re-runs deadlocks, not a dropped connection.
}

The server will not start after a crash ​

StepPostgreSQLMySQL InnoDB
1. Stop and copyCopy the whole data directory (including pg_wal) before touching anythingCopy datadir and #innodb_redo
2. Read the logFirst PANIC/FATAL line: missing WAL segment, checksum error, could not fsync[ERROR] lines during redo or rollback
3. Storage firstDisk full? read-only remount? kernel I/O errors?Same
4. Prefer known-good copiesPromote a replica or restore base backup + WAL (PITR)Same
5. Last resortpg_resetwal on the copy, then dump, initdb, restore, verifyinnodb_force_recovery = 1, raise one step at a time, dump, rebuild

Loading data fast without weakening production ​

TechniqueProductTrade-off
COPY in one transactionPostgreSQLOne flush; WAL still written
CREATE UNLOGGED TABLEPostgreSQLNot written to WAL, "automatically truncated after a crash or unclean shutdown", not replicated
wal_level = minimal + create/truncate and load in one transactionPostgreSQLNo WAL for that data; breaks PITR and standbys; restart needed
ALTER INSTANCE DISABLE INNODB REDO_LOGMySQL"intended only for loading data into a new MySQL instance"
PRAGMA synchronous = OFF during an initial buildSQLiteFine when the build "can be repeated if a power loss occurs"
sql
CREATE UNLOGGED TABLE staging_events (LIKE events INCLUDING ALL);
COPY staging_events FROM '/data/events.csv' WITH (FORMAT csv);
INSERT INTO events SELECT * FROM staging_events;   -- logged, durable copy
DROP TABLE staging_events;

Choosing durability settings ​

Data / workloadRecommended settingExtra techniqueReason
Payments, ledgers, orders, inventorysynchronous_commit = on; InnoDB 1 + sync_binlog = 1Synchronous standby in another zone; idempotency keysAn acknowledged loss is a business incident
User-generated content (posts, comments)DefaultsAsync standby is usually acceptableLosing seconds on failover is tolerable, corruption is not
Events, click streams, metrics in PostgreSQLSET LOCAL synchronous_commit = off per transactionBatch insertsLoss window ≤ ~600 ms, no corruption
Session store, caches, rate-limit countersRedis with RDB or appendfsync everysecTreat as rebuildableSpeed matters more than the last second
Staging / ETL scratch tablesUNLOGGEDRebuild on crashNo WAL, truncated after crash
CI test databasesfsync = off, full_page_writes = off acceptableRecreate per runData is disposable
Embedded/mobile app (SQLite)WAL mode + synchronous = NORMAL (or FULL for money)Checkpoint in backgroundConsistent always; durable across app crash
Event streaming (Kafka)acks=all, RF 3, min.insync.replicas = 2; leave flush defaultsReplicas in different racks/zonesReplication, not fsync, is the durability
MongoDB orders collectionw: "majority" (journaled)Retryable writesDurable on a majority before ack
Analytics replica (MySQL)innodb_flush_log_at_trx_commit = 2Rebuild from primary if lostReplica can be reseeded

In architecture: from a single process to a distributed system ​

Durability is decided per write class, and every hop between systems is a place where a "committed" thing can still vanish.

Monolith: one process, one database ​

One Laravel or Go application, one PostgreSQL. Everything on this page applies directly. The simplest correct setup: defaults (synchronous_commit = on, fsync = on, full_page_writes = on, checksums on), pg_wal on honest storage, archiving on, and per-transaction SET LOCAL synchronous_commit = off for the one or two tables of telemetry. Example: an online shop's orders and payments commit synchronously; page_views is inserted in batches with async commit. When the shop's single VM dies, the volume (EBS/PD) is reattached to a new VM and crash recovery replays WAL; RPO for orders is zero, for page views a fraction of a second.

Modular monolith and multiple databases ​

Modules own schemas or separate databases. Two traps: a module that sets ALTER DATABASE ... SET synchronous_commit = off for its own speed changes durability for every module in that database; and a business action spanning two databases is two commits, so a crash between them leaves one done. Example: billing (PostgreSQL) and search_index (a second database) are updated in one request; the crash window between the two commits is closed with an outbox row written in the billing transaction and processed afterwards, not by trusting two COMMITs in sequence.

Microservices: durable handoffs, not durable calls ​

Each service's database is durable on its own; nothing makes the pair durable. The classic failure is dual write: commit to the database, then publish to a broker; a crash between the two loses the event. The fix is the transactional outbox: the event row commits in the same WAL flush as the business row, and a relay publishes it (or CDC reads it from the WAL itself, see Change Data Capture). The broker hop has its own durability: Kafka acks=all with min.insync.replicas = 2, RabbitMQ quorum queues with publisher confirms. Consumers must be idempotent because the ambiguous-commit problem exists on every hop (idempotent consumers).

text
     Order service (PostgreSQL)              Relay                     Kafka (RF=3, min ISR 2)
1    BEGIN; INSERT order; INSERT outbox; COMMIT  -- one WAL flush, both durable
2                                            read outbox row
3                                            produce acks=all  ----->  leader + 1 follower have it
4                                            mark outbox row sent
5    crash between 3 and 4 -> relay re-sends -> consumer dedups by event id

Distributed data: replicas, caches, distributed SQL and multi-region ​

A local WAL flush survives a crash of this machine. Surviving the loss of the machine needs the WAL somewhere else before the ack: a synchronous standby (synchronous_commit = on or remote_apply), or a consensus system that only commits on a quorum (CockroachDB, Spanner, etcd). Asynchronous replicas trade an RPO of "replication lag" for lower latency; caches in front (Redis) are not durable stores at all unless you accept their AOF/RDB window. In multi-region setups the speed of light dominates: a synchronous commit across regions costs a round trip (tens of milliseconds), so teams keep synchronous replication inside a region and asynchronous across regions, accepting a non-zero RPO for region loss. Kafka, CockroachDB and MongoDB with w: "majority" all replace "one disk flushed" with "a quorum has it". See Replication, Eventual Consistency and Distributed SQL.

Scaling path: 1×, 10×, 100× ​

  • 1×: defaults; check pg_test_fsync once; archiving on; monitor pg_stat_checkpointer and pg_wal size.
  • 10×: commit rate becomes the bottleneck: batch writes, use async commit for low-value tables, move pg_wal to a dedicated low-latency device, raise max_wal_size so checkpoints are time-triggered, consider wal_compression, add a synchronous standby in another zone and watch its latency.
  • 100×: a single WAL stream is the ceiling of a single primary. Split write load by domain (separate clusters), shard (Partitioning & Sharding), or move to a system that spreads the log (distributed SQL with per-range Raft logs, Kafka partitions). Recovery time and WAL volume per hour become capacity-planning inputs, not afterthoughts.

Lab ​

Docker was not available when this page was written, so every output below is illustrative: the shape is right, the exact numbers, LSNs and log wording will differ on your machine and version. The image is postgres:18 (data checksums on by default; pg_stat_checkpointer exists since 17). Use a unique container name and port so the lab does not collide with anything else you run.

Setup.

bash
docker run -d --name dcr-lab -e POSTGRES_PASSWORD=lab -p 55432:5432 postgres:18
docker exec -it dcr-lab psql -U postgres          # terminal A
docker exec -it dcr-lab psql -U postgres          # terminal B
sql
CREATE TABLE accounts (id int PRIMARY KEY, balance bigint NOT NULL);
INSERT INTO accounts SELECT g, 1000 FROM generate_series(1, 100000) g;
CREATE TABLE commit_probe (id bigserial PRIMARY KEY, note text, at timestamptz DEFAULT now());
SHOW data_checksums;    -- on
CHECKPOINT;

Experiment 1: kill -9 a backend mid-transaction and watch recovery. In the official image the postmaster is PID 1 in the container, which a signal from inside the container will not kill; killing a backend is enough, because PostgreSQL then resets every process and runs crash recovery.

text
     A                                                    B / shell
1    BEGIN;
2    UPDATE accounts SET balance = balance - 100 WHERE id = 1;
3    SELECT pg_backend_pid();             -- e.g. 812
4                                                         B: INSERT INTO commit_probe(note) VALUES ('committed before crash');
5                                                         docker exec dcr-lab bash -c 'kill -9 812'
6    -- A: server closed the connection unexpectedly
7                                                         docker logs dcr-lab --tail 20
     -- illustrative: "terminated by signal 9", "automatic recovery in progress",
     --               "redo starts at ...", "redo done at ...", "ready to accept connections"
8    reconnect: SELECT balance FROM accounts WHERE id = 1;     -- 1000: uncommitted update gone
9               SELECT note FROM commit_probe;                  -- 'committed before crash' survived

Experiment 2: kill the whole server, not just a backend.

bash
docker exec dcr-lab psql -U postgres -c "INSERT INTO commit_probe(note) VALUES ('before docker kill')"
docker kill -s KILL dcr-lab && docker start dcr-lab
docker logs dcr-lab --tail 15        # "not properly shut down; automatic recovery in progress"
docker exec dcr-lab psql -U postgres -c "SELECT note FROM commit_probe ORDER BY id DESC LIMIT 1"
# illustrative:  before docker kill
docker exec -u postgres dcr-lab sh -c 'pg_controldata "$PGDATA" | grep -E "cluster state|REDO location|checkpoint location"'

Experiment 3: commit latency with synchronous_commit on vs off. pgbench ships in the image. Each transaction is one single-row insert.

bash
docker exec dcr-lab sh -c 'echo "INSERT INTO commit_probe(note) VALUES (:client_id);" > /tmp/ins.sql'
docker exec -e PGOPTIONS='-c synchronous_commit=on'  dcr-lab pgbench -U postgres -n -f /tmp/ins.sql -c 1 -T 15 postgres
docker exec -e PGOPTIONS='-c synchronous_commit=off' dcr-lab pgbench -U postgres -n -f /tmp/ins.sql -c 1 -T 15 postgres
docker exec -e PGOPTIONS='-c synchronous_commit=on'  dcr-lab pgbench -U postgres -n -f /tmp/ins.sql -c 32 -T 15 postgres
# illustrative shape: with 1 client, "off" shows a much lower average latency than "on";
# with 32 clients the gap narrows because group commit shares each flush.

The Go equivalent is latency.Measure(ctx, db, "on", 1000) vs "off" from the snippet above. On Docker Desktop for macOS the virtual disk may not pass flushes through to the host the way a Linux server does, so absolute numbers are not representative; compare relative values only, and repeat on the real server with pg_test_fsync.

Experiment 4: pg_waldump one transaction.

sql
SELECT pg_current_wal_lsn() AS start_lsn \gset
BEGIN;
SELECT pg_current_xact_id();                                    -- e.g. 760
UPDATE accounts SET balance = balance + 1 WHERE id = 2;
INSERT INTO commit_probe(note) VALUES ('dump me');
COMMIT;
SELECT pg_current_wal_lsn() AS end_lsn \gset
\echo :start_lsn :end_lsn
SELECT pg_walfile_name(:'start_lsn');
bash
# replace the LSNs and xid with the values printed above
docker exec -u postgres dcr-lab sh -c 'pg_waldump -p "$PGDATA/pg_wal" -s 0/1A2B3C8 -e 0/1A2B6F0 -x 760'
# illustrative, abridged:
# rmgr: Heap   len (rec/tot): 72/72,   tx: 760, lsn: 0/1A2B3C8, desc: HOT_UPDATE ... blkref #0: rel 1663/5/16385 blk 0
# rmgr: Heap   len (rec/tot): 54/8166, tx: 760, lsn: 0/1A2B410, desc: INSERT ... blkref #0: rel 1663/5/16391 blk 0 FPW
# rmgr: Btree  len (rec/tot): 64/64,   tx: 760, lsn: 0/1A2D3F8, desc: INSERT_LEAF ...
# rmgr: Transaction len (rec/tot): 34/34, tx: 760, lsn: 0/1A2D440, desc: COMMIT 2026-11-25 ...

Read it: one record per page change, the FPW marker on the first change of a page since the last checkpoint (rec 54 bytes, total 8166 bytes), and the COMMIT record whose flush made the transaction durable. Run pg_waldump ... -z for per-resource-manager totals and -w to list only full-page images.

Experiment 5: full-page images after a checkpoint.

sql
SELECT pg_stat_reset_shared('wal');
CHECKPOINT;
UPDATE accounts SET balance = balance + 1 WHERE id % 100 = 0;   -- touches ~1000 rows across many pages
SELECT wal_records, wal_fpi, pg_size_pretty(wal_bytes) FROM pg_stat_wal;
UPDATE accounts SET balance = balance + 1 WHERE id % 100 = 0;   -- same pages again, no checkpoint in between
SELECT wal_records, wal_fpi, pg_size_pretty(wal_bytes) FROM pg_stat_wal;
-- illustrative: the first UPDATE adds hundreds of FPIs and megabytes of WAL;
-- the second adds about as many records but almost no new FPIs, so far less WAL.

Experiment 6: provoke requested checkpoints.

sql
ALTER SYSTEM SET max_wal_size = '64MB'; SELECT pg_reload_conf();
SELECT num_timed, num_requested FROM pg_stat_checkpointer;
INSERT INTO commit_probe(note) SELECT repeat('x', 500) FROM generate_series(1, 400000);
SELECT num_timed, num_requested FROM pg_stat_checkpointer;   -- num_requested went up
-- docker logs: "checkpoints are occurring too frequently ... Consider increasing max_wal_size"
ALTER SYSTEM RESET max_wal_size; SELECT pg_reload_conf();

Cleanup: docker rm -f dcr-lab.

Common misconceptions ​

BeliefReality
"COMMIT means the table file on disk has my row."The WAL has the commit record; the table page is written later by the checkpointer or background writer.
"synchronous_commit = off risks corruption."It risks losing the last few hundred milliseconds of commits, never consistency. fsync = off risks corruption.
"Checkpoint more often for safety."Durability comes from the WAL flush. More checkpoints mean more I/O and more full-page images; only recovery time shrinks.
"O_DIRECT makes writes durable."It only bypasses the OS page cache; the device cache still needs a flush.
"A successful fsync retry after an error is fine."On Linux the retry could succeed after the data was dropped (fsyncgate); PostgreSQL now PANICs.
"max_wal_size limits pg_wal."It is a soft limit; failed archiving, slots and wal_keep_size hold WAL beyond it.
"pg_resetwal repairs a broken database."It discards WAL; the result "might contain inconsistent data"; dump and rebuild afterwards.
"Checksums fix corrupted pages."They detect; repair comes from replicas, backups or FPIs.
"Cloud volumes are replicated, so async commit is safe."Volume replication protects the disk, not an ack sent before the flush.
"innodb_flush_log_at_trx_commit = 2 loses nothing if MySQL crashes."Correct for a mysqld crash; an OS crash or power loss can lose about a second.
"sync_binlog = 0 only affects replication."It also makes PITR and replicas diverge from what InnoDB kept.
"Kafka is not durable because it does not fsync."It is durable through replication: acks=all + min.insync.replicas across failure domains.
"Redis AOF everysec loses at most one second, so replicas are safe too."Replication is asynchronous; failover can lose more.

Cheat sheet ​

TopicWhat to remember
Write-ahead ruleLog flushed before page written; commit = commit record flushed
LSNByte offset in WAL; pg_current_wal_lsn(), pg_wal_lsn_diff()
Segments16 MB in pg_wal/, recycled after checkpoints and archiving
synchronous_commitoff < local < remote_write < on < remote_apply; per transaction with SET LOCAL
Async commit loss≤ 3 × wal_writer_delay (600 ms default); no corruption
fsync = offCorruption risk; throwaway clusters only
Group commitFree at concurrency; commit_delay ≈ half a flush when flushes are slow
Torn pagesfull_page_writes = on (PostgreSQL), doublewrite (InnoDB)
Checkpointscheckpoint_timeout 5min, max_wal_size 1GB, target 0.9; want num_timed ≫ num_requested
Recoverypg_control → checkpoint → redo record → replay to end of valid WAL; no undo in PostgreSQL
ARIESAnalysis, redo (repeating history), undo with CLRs
fsyncgatePANIC on flush failure (data_sync_retry = off)
HardwareTest with pg_test_fsync; no volatile write-back cache without BBU/PLP
InnoDBinnodb_flush_log_at_trx_commit = 1, sync_binlog = 1, doublewrite on, size innodb_redo_log_capacity
Other enginesSQLite synchronous; Redis appendfsync; Kafka acks=all + min ISR; MongoDB j: true

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — A client receives "COMMIT" and the server loses power one millisecond later. Under PostgreSQL defaults, is the transaction there after restart, and where was it at the moment of the crash? Must-know ​

Answer

Answer: Yes, if the storage honours flushes. With synchronous_commit = on the commit record was flushed to the WAL before the reply; the table pages were probably still only in shared_buffers. Recovery replays the WAL from the last checkpoint's redo record and rebuilds them. See write-ahead rule.

2 — What exactly can synchronous_commit = off lose, and why can it not corrupt the database? Important ​

Answer

Answer: Commits not yet flushed by the WAL writer, at most about 3 × wal_writer_delay. Replay is in commit order up to the last flushed record, so the result equals "those transactions aborted cleanly"; no later transaction survives without an earlier one it depended on. See commit levels.

3 — Why does WAL volume jump right after every checkpoint? Important ​

Answer

Answer: With full_page_writes = on, the first change to each page after a checkpoint logs the whole 8 kB page image to protect against torn pages. Later changes log only deltas. See torn pages.

4 — pg_stat_checkpointer shows num_requested = 900 and num_timed = 40. What is happening and what do you change? Important ​

Answer

Answer: Checkpoints are being forced by WAL volume (max_wal_size too small): a checkpoint storm pattern. Raise max_wal_size until most checkpoints are timed; keep checkpoint_completion_target at 0.9. See checkpoints.

5 — Why does PostgreSQL's crash recovery have no undo pass, while InnoDB's does? Good to know ​

Answer

Answer: PostgreSQL's MVCC keeps uncommitted row versions invisible because their transaction has no commit record; VACUUM removes them later. InnoDB updates rows in place and keeps old versions in undo logs, so it must roll back incomplete transactions after redo, as ARIES does. See crash recovery and ARIES.

6 — What did fsyncgate teach, and what does data_sync_retry = off do? Good to know ​

Answer

Answer: A failed fsync() on Linux could mark pages clean and drop them, so a retry reported success for lost data. PostgreSQL now raises PANIC on a data-file flush failure and recovers from WAL instead of retrying. See fsyncgate.

7 — pg_wal has grown to 200 GB and the disk is nearly full. Name three likely causes and the one thing you must not do. Must-know ​

Answer

Answer: A failing archive_command, an inactive replication slot, a large wal_keep_size. Do not delete files from pg_wal or run pg_resetwal; fix the retainer and let PostgreSQL recycle. See pg_wal is filling the disk.

8 — In MySQL, why do you need both innodb_flush_log_at_trx_commit = 1 and sync_binlog = 1? Important ​

Answer

Answer: The first makes InnoDB's redo durable at commit; the second makes the binlog durable before commit. The internal two-phase commit then resolves prepared transactions against the binlog at restart, so the primary, replicas and PITR agree. See binlog 2PC.

9 — Your connection dropped while COMMIT was in flight. How do you find out whether the order exists without risking a double charge? Must-know ​

Answer

Answer: Use an idempotency key with a unique constraint so a retry cannot duplicate it, and/or record pg_current_xact_id() before COMMIT and ask pg_xact_status(xid) on a new connection. See ambiguous commit.

10 — Why is a replicated cloud volume (EBS, Persistent Disk) not a reason to set synchronous_commit = off or innodb_flush_log_at_trx_commit = 2? Important ​

Answer

Answer: Volume durability numbers describe the chance of losing the volume. Async commit acknowledges before the WAL reaches the volume at all, so a crash loses the unflushed tail no matter how well the volume is replicated. See the layers below.

11 — How does Kafka achieve durability without flushing every message, and which producer and topic settings make it hold? Important ​

Answer

Answer: By replicating each record to the in-sync replicas before acknowledging; acks=all with min.insync.replicas (for example RF 3, min ISR 2) makes a write survive any single broker loss. A crashed replica re-syncs before rejoining. See Kafka.

Glossary ​

TermMeaning
DurabilityThe ACID promise that a committed transaction survives crashes (within a stated failure model)
Write-ahead logging (WAL)Log a change and flush the log before the changed page may reach disk
Write-ahead ruleWAL up to a page's LSN must be flushed before that page is written
WAL recordOne logged change from a resource manager (heap, B-tree, transaction...)
LSN (Log Sequence Number)Byte position in the WAL; type pg_lsn in PostgreSQL
WAL segmentA 16 MB WAL file in pg_wal/ (size set by initdb --wal-segsize)
wal_levelHow much the WAL contains: minimal, replica, logical
effective_wal_levelPostgreSQL 19 read-only setting showing the level actually in use
Redo / roll-forwardReplaying log records to rebuild pages after a crash
Redo record / redo pointThe WAL position a checkpoint guarantees everything before is on disk; replay starts there
pg_controlSmall control file holding the latest checkpoint location and cluster state
fsyncSystem call (and PostgreSQL setting) that forces a file's data and metadata to stable storage
fdatasyncLike fsync but skips non-essential metadata; PostgreSQL's Linux default
O_DSYNC / O_SYNCOpen flags that make each write synchronous (open_datasync, open_sync)
O_DIRECTOpen flag that bypasses the OS page cache; not a durability guarantee by itself
O_DIRECT_NO_FSYNCInnoDB flush method that skips fsync() after writes; risky with separate devices
wal_sync_methodPostgreSQL choice of flush call for WAL
fsync_writethroughwal_sync_method value that forces write-through of the disk cache (macOS)
synchronous_commitWhat a PostgreSQL commit waits for: off, local, remote_write, on, remote_apply
remote_applyCommit waits until a synchronous standby has replayed it
Asynchronous commitAck before WAL flush; loses recent commits, never consistency
Group commitOne WAL flush shared by several concurrent commits
commit_delay / commit_siblingsLeader wait (µs) before a flush / minimum active transactions for the wait
WAL writerProcess that flushes WAL every wal_writer_delay (200 ms) or wal_writer_flush_after
wal_buffersShared memory for WAL not yet written
Torn pagePage left half old, half new by a power loss mid-write
full_page_writesLog the whole page image on its first change after a checkpoint
Full-page image (FPI)The 8 kB page copy carried in WAL (wal_fpi in pg_stat_wal)
wal_compressionCompress full-page images (pglz, lz4, zstd)
wal_log_hintsAlso log FPIs for hint-bit-only changes
CheckpointFlush all dirty pages and write a checkpoint record that sets the redo point
checkpoint_timeoutMaximum time between checkpoints (default 5min)
max_wal_size / min_wal_sizeSoft WAL size that triggers a checkpoint / recycling floor
checkpoint_completion_targetFraction of the interval over which checkpoint writes are spread (0.9)
Spread checkpointCheckpoint whose writes are paced across the interval
Checkpoint stormSize-triggered checkpoints in quick succession causing I/O and FPI bursts
checkpoint_warningLogs a warning when size-triggered checkpoints are closer than this
checkpoint_flush_afterAsk the OS to write back checkpoint data in small steps
RestartpointA standby's equivalent of a checkpoint
Background writerWrites dirty buffers ahead of demand (bgwriter_delay, bgwriter_lru_maxpages)
CheckpointerProcess that performs checkpoints
WAL recyclingRenaming old segments for reuse (wal_recycle)
wal_keep_sizeWAL kept for standbys regardless of slots
Replication slotServer-side marker that retains WAL a consumer has not received
archive_mode / archive_command / archive_libraryHand completed segments to an archive
archive_timeoutForce a segment switch so idle periods still get archived
PITRPoint-in-time recovery from a base backup plus archived WAL
Crash recoveryAutomatic redo from the last checkpoint at startup after an unclean stop
restart_after_crashReinitialise and run recovery automatically after a backend crash
recovery_init_sync_methodSync the data directory before recovery (fsync or syncfs)
recovery_prefetchPrefetch blocks referenced by WAL during replay
ARIES1992 recovery method: WAL, page LSNs, analysis/redo/undo, CLRs
Repeating historyARIES redo replays all logged updates, losers included, before undo
Compensation log record (CLR)Redo-only record written for each undo step in ARIES
Loser transactionA transaction with no commit record at the crash
Data checksumsPer-page checksum verified on read (default on since PostgreSQL 18)
pg_checksumsOffline tool to enable, disable or verify data checksums
CRC-32CChecksum protecting each WAL record
fsyncgateThe 2018 discovery that failed fsync() errors could be lost or retried falsely on Linux
data_sync_retryOff by default: PANIC on data-file flush failure
Write-back cacheDevice/controller cache that acknowledges before data is on media
Battery-backed cache (BBU)Controller cache kept alive by a battery so acknowledged writes survive power loss
Power-loss protection (PLP)Capacitors on enterprise SSDs that drain cache to flash on power loss
pg_test_fsyncTimes each sync method; sanity-checks the disk
diskchecker.plTests whether a disk really persists flushed writes across power loss
EBS / Persistent DiskAWS and Google Cloud network block storage with published annual durability
pg_waldumpDecodes and prints WAL records
pg_controldataPrints the contents of pg_control
pg_resetwalLast-resort tool that clears WAL and resets control data
pg_xact_statusReports whether a recent transaction id committed, aborted or is in progress
Ambiguous commitThe client cannot know whether a commit succeeded because the reply was lost
UNLOGGED tablePostgreSQL table not written to WAL, truncated after a crash
InnoDB redo logInnoDB's WAL, sized by innodb_redo_log_capacity
innodb_redo_log_capacityTotal redo log size (default 100 MB in MySQL 8.4)
innodb_flush_log_at_trx_commitInnoDB commit durability: 1 (flush), 2 (write), 0 (neither) per commit
innodb_flush_log_at_timeoutSeconds between background redo flushes for settings 0 and 2
innodb_flush_methodHow InnoDB opens and flushes files (O_DIRECT, fsync, O_DSYNC...)
Doublewrite bufferInnoDB area where pages are written and flushed before their real location
innodb_doublewriteON/DETECT_AND_RECOVER, DETECT_ONLY, OFF
Binary log (binlog)MySQL log of committed changes for replication and PITR
sync_binlogHow often the binlog is synced (1 = before every commit)
Two-phase commit (binlog/InnoDB)Prepare in InnoDB, write binlog, commit; resolves crashes consistently
innodb_force_recoveryEmergency startup levels 1–6; 4+ can permanently corrupt data
journal_modeSQLite journaling: DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF
PRAGMA synchronousSQLite flush policy: OFF, NORMAL, FULL, EXTRA
AOF / appendfsyncRedis append-only file and its fsync policy (always, everysec, no)
RDBRedis point-in-time snapshot file
log.flush.interval.messagesKafka broker setting for forced flushes; effectively never by default
acks=all / min.insync.replicasKafka producer ack level and the ISR size required for it
j: trueMongoDB write concern option: acknowledge after the journal is flushed
Delayed durabilitySQL Server lazy commit (DELAYED_DURABILITY)
COMMIT WRITE NOWAITOracle commit that returns before redo is written
57P03 / XX001PostgreSQL SQLSTATEs for "cannot connect now" (recovery) and data corruption

References ​

Built by Morteza Negahi