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 for | Go to |
|---|---|
| The whole topic in three tables | Everything in one minute |
| Why a log, and the trade-off it makes | Why durability needs a log |
| ARIES, repeating history, where PostgreSQL differs | Where it comes from |
| Which failure each mechanism survives | The failure model |
The write-ahead rule, LSN, segments, wal_level | Write-ahead rule, WAL records, LSN, segments |
fsync, fdatasync, O_DIRECT, O_DSYNC, wal_sync_method | Flushing to stable storage |
synchronous_commit and what each level can lose | Commit levels |
commit_delay, commit_siblings | Group commit |
Torn pages, full_page_writes, doublewrite | Torn pages |
checkpoint_timeout, max_wal_size, checkpoint storms | Checkpoints |
| Background writer, WAL writer | Background writer and WAL writer |
Recycling, archive_mode, archive_command | WAL retention and archiving |
| What happens on restart, step by step (recovery timeline) | Crash recovery |
| Analysis/redo/undo, CLRs | ARIES in detail |
| Data checksums, CRC-32C | Checksums |
fsyncgate 2018, data_sync_retry | fsyncgate |
| Disk write caches, battery-backed controllers, cloud disks (EBS, Persistent Disk) | The layers below |
InnoDB redo, doublewrite, sync_binlog, 2PC with the binlog | InnoDB |
| SQLite, Redis, MongoDB, Kafka, SQL Server, Oracle, CockroachDB | Per-engine behaviour |
| Every knob, every tool, every error code | Mechanics |
Slow commits, checkpoint spikes, full pg_wal, lost acks, a database that will not start | Solving the classic problems |
| Which setting for which data | Choosing durability settings |
| Replicas, microservices, multi-region | In architecture |
kill -9, commit latency, pg_waldump | Lab |
| Wrong beliefs, a cheat sheet, every term | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The mechanisms. Every row is unpacked below.
| Mechanism | In plain words | What it protects against | PostgreSQL knob (default) |
|---|---|---|---|
| Write-ahead rule | Log the change, flush the log, only then may the page reach disk | Losing a committed change; half-applied changes | Always on |
| WAL flush at commit | The commit waits until its log record is on stable media | Losing an acknowledged commit | synchronous_commit (on) |
| Group commit | One flush covers many commits | Flush cost dominating throughput | commit_delay (0), commit_siblings (5) |
| Full-page writes | First change to a page after a checkpoint logs the whole page | Torn pages after power loss | full_page_writes (on) |
| Checkpoint | Flush all dirty pages, mark a redo start point | Unbounded recovery time and WAL growth | checkpoint_timeout (5min), max_wal_size (1GB) |
| Crash recovery (REDO) | Replay the log forward from the last checkpoint | Changes that were only in memory | Automatic, restart_after_crash (on) |
| Checksums | Detect pages and records that are garbage | Silent media corruption | Data checksums on by default since PostgreSQL 18; WAL CRC-32C always |
| Archiving | Copy finished WAL segments elsewhere | Losing the disk, needing PITR | archive_mode (off), archive_command |
| Synchronous replica | Another machine has the WAL before you ack | Losing the whole server | synchronous_standby_names + synchronous_commit |
What an acknowledged commit can lose, per product and setting.
| Product and setting | Ack after | A crash can lose | Can it corrupt? |
|---|---|---|---|
PostgreSQL synchronous_commit = on (default) | Local WAL flush | Nothing acknowledged | No |
PostgreSQL synchronous_commit = off | Nothing | Up to 3 × wal_writer_delay (600 ms by default) | No: lost commits look like clean aborts |
PostgreSQL fsync = off | Nothing is ever flushed | Anything | Yes, "arbitrarily bad corruption" |
MySQL InnoDB innodb_flush_log_at_trx_commit = 1 (default) | Redo flush | Nothing acknowledged | No |
InnoDB innodb_flush_log_at_trx_commit = 2 / 0 | Write to OS / nothing | About 1 s (innodb_flush_log_at_timeout) | No |
SQLite WAL mode, PRAGMA synchronous = NORMAL | WAL append, no sync | Last transactions on power loss | No |
Redis appendfsync everysec (default AOF policy) | Append to AOF buffer | About 1 s of writes | No |
MongoDB WiredTiger, write concern j: true | Journal flush | Nothing acknowledged | No |
Kafka acks=all, default flush settings | In-sync replicas have it in page cache | Only if all in-sync replicas fail together | No |
| SQL Server delayed durability | Log buffer | Unflushed log tail | No |
Oracle COMMIT WRITE NOWAIT | Nothing | Unwritten redo | No |
The three things to do.
| Situation | Do this |
|---|---|
| Money, stock, anything an external party was told about | Keep 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 machine | Durability 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 commit | One sequential append and one flush per commit (or per group of commits) |
| Commit latency grows with the number of pages touched | Commit latency is roughly one WAL flush |
| A crash mid-flush leaves some pages new and some old, no way to tell | The log says exactly which changes committed |
| No point-in-time recovery, no physical replication | The same log feeds archiving, PITR, standbys and logical decoding |
| Nothing extra to manage | You 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
- "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_buffersfor minutes until a checkpoint. That is the whole point of the design. - "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.
- "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.
| Failure | What is lost from memory | What brings data back | What does NOT help |
|---|---|---|---|
One backend process crashes (kill -9 a backend, segfault) | Shared memory is considered unsafe; PostgreSQL resets all processes | Crash 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_buffers | Crash recovery; the OS page cache still holds written-but-unflushed data | |
| OS crash or kernel panic | Process memory and the OS page cache | Only what was flushed (fsync) | synchronous_commit = off commits not yet flushed are gone |
| Power loss | Page cache and any volatile drive/controller cache | Flushed data, if the drive honoured the flush; full-page images for torn pages | A write-back cache without a battery |
| Disk dies | The whole volume | A replica, or base backup + archived WAL | Anything on the same disk, including local WAL |
| Data center / zone lost | All local copies | A replica or archive in another zone/region | Same-zone replicas |
Operator error (DROP TABLE, bad migration) | Nothing; the mistake is durably committed | PITR to before the mistake | Replicas (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.
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 writtenReal 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.
| Product | Name of the log | Write-ahead rule enforced by |
|---|---|---|
| PostgreSQL | WAL (pg_wal/) | Buffer manager checks page LSN against flushed WAL before writing |
| MySQL InnoDB | Redo log (#innodb_redo/) | Flushes redo up to the page LSN before flushing the page |
| SQLite | Rollback journal or WAL file | Journal synced before the database file is changed (rollback mode), or WAL appended (WAL mode) |
| SQL Server | Transaction log (.ldf) | Log records hardened before the dirty page is written |
| Oracle | Online redo log | LGWR writes redo before DBWn writes the block |
| MongoDB WiredTiger | Journal | Journal 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).
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'); 000000010000000000000001Real 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.
| Concept | PostgreSQL | MySQL InnoDB |
|---|---|---|
| Position | LSN, byte offset, pg_lsn | LSN, ever-increasing, Innodb_redo_log_current_lsn |
| Files | 16 MB segments in pg_wal/, recycled | 32 files #ib_redoN sized innodb_redo_log_capacity/32 |
| Content level | wal_level = minimal / replica / logical | Redo is physical-logical; row images for replication go to the separate binary log |
| Integrity | CRC-32C per record | Checksums per redo block |
Fix / how to use it:
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".
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 ackReal 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.
| Product | Knob | Default | Note |
|---|---|---|---|
| PostgreSQL | wal_sync_method | fdatasync on Linux/FreeBSD | Test with pg_test_fsync |
| PostgreSQL | fsync | on | off only for throwaway clusters |
| MySQL InnoDB | innodb_flush_method | O_DIRECT if supported (Unix), else fsync | innodb_use_fdatasync swaps fsync() for fdatasync() |
| MySQL InnoDB | O_DIRECT_NO_FSYNC | not default | Skips fsync() after writes; unsafe if redo and data are on different devices without battery-backed cache |
| SQLite | PRAGMA synchronous | FULL for rollback journal | PRAGMA fullfsync on macOS |
| Redis | appendfsync | everysec |
Fix / how to use it:
# 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 5SHOW fsync; -- must be on
SHOW wal_sync_method; -- fdatasync on Linuxsynchronous_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:
| Value | Waits for | Survives PG crash | Survives OS crash on standby | Standby reads see it |
|---|---|---|---|---|
off | nothing; WAL writer flushes within 3 × wal_writer_delay | Not the last few commits | — | — |
local | local WAL flush | Yes (locally) | — | — |
remote_write | local flush + standby wrote to its OS | Yes | No | No |
on (default) | local flush + standby flushed (if synchronous_standby_names set) | Yes | Yes | No |
remote_apply | local flush + standby replayed it | Yes | Yes | Yes |
"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
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 flushReal 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".
| Product | Per-transaction relaxation | Server-wide relaxation |
|---|---|---|
| PostgreSQL | SET LOCAL synchronous_commit = off | ALTER SYSTEM SET synchronous_commit = off |
| MySQL InnoDB | none (variable is global) | innodb_flush_log_at_trx_commit = 0/2 |
| SQL Server | COMMIT TRANSACTION WITH (DELAYED_DURABILITY = ON) when database is ALLOWED | ALTER DATABASE ... SET DELAYED_DURABILITY = FORCED |
| Oracle | COMMIT WRITE NOWAIT (with BATCH or IMMEDIATE) | COMMIT_WAIT/COMMIT_LOGGING parameters |
| MongoDB | write concern j: false / w: 1 | default write concern |
Fix / how to use it:
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.
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 ackReal 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.
| Product | Group commit |
|---|---|
| PostgreSQL | Implicit; tunable with commit_delay, commit_siblings |
| MySQL | Binary log group commit (flush, sync, commit stages); binlog_group_commit_sync_delay |
| Redis | appendfsync always still does "a single write and a single fsync" per event-loop batch |
| Kafka | Batching on the producer (linger.ms, batch.size) |
| SQLite | No: 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.
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 consistentReal 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.
| Product | Torn-page protection | Knob |
|---|---|---|
| PostgreSQL | Full-page images in WAL | full_page_writes (on) |
| MySQL InnoDB | Doublewrite buffer | innodb_doublewrite (ON, DETECT_AND_RECOVER, DETECT_ONLY, OFF) |
| SQLite | Rollback journal holds original pages; WAL holds whole new pages | journal_mode |
| ZFS / copy-on-write file systems | Never overwrite in place | — |
Fix / how to use it:
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.
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.
| Product | Checkpoint style | Main knobs |
|---|---|---|
| PostgreSQL | Periodic full (spread) checkpoint | checkpoint_timeout, max_wal_size, checkpoint_completion_target |
| MySQL InnoDB | Fuzzy checkpoint, continuous flushing of oldest dirty pages | innodb_redo_log_capacity, innodb_io_capacity, innodb_max_dirty_pages_pct |
| SQLite WAL mode | Copy WAL pages back into the database file | wal_autocheckpoint (about 1000 pages) |
| MongoDB WiredTiger | Periodic checkpoint plus journal for changes since it | Journal storage.journal.commitIntervalMs |
Fix / how to use it:
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.
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 aheadReal 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.
| Process | PostgreSQL | InnoDB equivalent |
|---|---|---|
| Page cleaner | background writer | page cleaner threads (innodb_page_cleaners) |
| Log flusher | WAL writer | log writer / log flusher threads |
| Checkpointer | checkpointer | page 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.
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 recycledReal 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".
| Retainer | Where to see it | Fix |
|---|---|---|
| Failing archiver | pg_stat_archiver.failed_count, last_failed_wal | Fix the command; never delete from pg_wal by hand |
| Replication slot | pg_replication_slots (restart_lsn, wal_status) | Drop unused slots; set max_slot_wal_keep_size |
wal_keep_size | SHOW wal_keep_size | Lower it or use slots |
| WAL summarization | summarize_wal, wal_summary_keep_time | Expected while incremental backups need it |
Fix / how to use it:
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 = 60Crash 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.
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 connectionsReal 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.
| Step | PostgreSQL | MySQL InnoDB |
|---|---|---|
| Find start point | pg_control → checkpoint → redo LSN | Checkpoint LSN in redo file header |
| Redo | Forward replay, page-LSN check, FPIs | Tablespace discovery, then redo application "before accepting any connections" |
| Torn pages | Full-page images | Doublewrite buffer |
| Losers (uncommitted) | Invisible via MVCC; no undo pass | Rolled 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 start | pg_resetwal (last resort) | innodb_force_recovery 1..6 |
Fix / how to use it:
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.
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 undoNextReal 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.
| Engine | Passes | Undo |
|---|---|---|
| ARIES (DB2 lineage) | Analysis, redo, undo | CLRs |
| SQL Server | Analysis, redo, undo | Log-based |
| MySQL InnoDB | Redo, then rollback of incomplete transactions | Undo logs |
| PostgreSQL | Redo only | None 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.
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, silentlyReal 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.
| Product | Page checksums | Log checksums |
|---|---|---|
| PostgreSQL | data_checksums (default on since 18) | CRC-32C per WAL record |
| MySQL InnoDB | innodb_checksum_algorithm (crc32) | Redo block checksums |
| SQL Server, Oracle | Page/block checksums (product-specific settings) | Log block checks |
Fix / how to use it:
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
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 recycledReal 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.
| Product | Behaviour 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) |
| SQLite | Returns 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.
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 pagesReal 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.
| Storage | Flush honest? | Notes |
|---|---|---|
| Enterprise SSD/NVMe with power-loss protection | Yes | Capacitors drain cache to flash |
| Consumer SSD / SATA disk with write cache on | Often not | Disable write cache or test with diskchecker.pl |
| RAID with BBU write-back cache | Yes, while the battery is healthy | Monitor the battery; file-system write barriers can negate the BBU benefit |
| Amazon EBS, Google Persistent Disk | Provider-managed; durability published per volume type | Network latency per flush: group commit helps |
| ZFS | Yes; issues its own cache flushes | Allows 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.
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 commitReal scenario: a payment platform runs synchronous_standby_names = 'ANY 1 (s1, s2)' across two zones; a node loss costs no acknowledged payment.
| Product | Durable-on-another-node setting |
|---|---|
| PostgreSQL | synchronous_standby_names + synchronous_commit = on/remote_apply |
| MySQL | Semi-synchronous replication, Group Replication |
| MongoDB | write concern w: "majority" (implies j: true when writeConcernMajorityJournalDefault is true) |
| Kafka | acks=all + min.insync.replicas (e.g. RF 3, min ISR 2) |
| CockroachDB | Raft 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."
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 onlineReal 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.
| Variable | Meaning |
|---|---|
innodb_redo_log_capacity | Total redo size (supersedes innodb_log_file_size × innodb_log_files_in_group) |
Innodb_redo_log_checkpoint_lsn / _current_lsn / _flushed_to_disk_lsn | Positions to compute checkpoint age and flush lag |
innodb_log_buffer_size | In-memory log buffer |
performance_schema.innodb_redo_log_files | START_LSN/END_LSN per file |
Fix / how to use it:
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."
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 lostReal scenario: a replica used only for analytics runs 2 to keep up with the primary; a primary that takes payments must run 1.
| Setting | Write at commit | Flush at commit |
|---|---|---|
1 | yes | yes |
2 | yes | no (once per innodb_flush_log_at_timeout) |
0 | no | no |
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.
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 redoReal 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 writes | InnoDB doublewrite | |
|---|---|---|
| Where the good copy lives | In the WAL | In doublewrite files |
| When it costs | First change after each checkpoint | Every page flush |
| Effect on WAL/redo size | Larger WAL | No 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".
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 committedReal 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 pair | Primary after OS crash | Replicas / PITR |
|---|---|---|
sync_binlog=1, innodb_flush_log_at_trx_commit=1 | Nothing acknowledged lost | Consistent with primary |
sync_binlog=0, =1 | InnoDB intact | Binlog 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
| Product | Log | Commit default | Relax | Torn pages | Recovery |
|---|---|---|---|---|---|
| PostgreSQL | WAL, 16 MB segments | Flush at commit | synchronous_commit = off per transaction | Full-page writes | Redo only |
| MySQL InnoDB | Redo log + binlog | Flush redo and binlog at commit | innodb_flush_log_at_trx_commit, sync_binlog | Doublewrite | Redo, rollback, binlog 2PC resolution |
| SQLite | Rollback journal or WAL | synchronous = FULL | NORMAL in WAL mode | Journal / WAL pages | Roll back hot journal or replay WAL |
| SQL Server | Transaction log | Fully durable | Delayed durability (DISABLED / ALLOWED / FORCED) | Page checksums | Analysis, redo, undo |
| Oracle | Online redo logs | COMMIT WRITE WAIT | COMMIT WRITE NOWAIT, BATCH | Block checksums | Roll forward, roll back |
| MongoDB (WiredTiger) | Journal + checkpoints | Journal flushed every 100 ms (storage.journal.commitIntervalMs), or at once with j: true | j: false | Checkpoint + journal | Last checkpoint + journal |
| Redis | AOF / RDB | AOF everysec (if enabled) | appendfsync no, RDB only | Not applicable | Load RDB, replay AOF |
| Kafka | Partition log segments | Page cache, no fsync | acks=1/0 | Not applicable | Truncate to high watermark, re-sync from leader |
| CockroachDB | Raft log per range | Quorum of replicas | Not offered for writes | Storage engine | Raft log replay per range |
Mechanics
Every PostgreSQL knob on one page Must-know
| Parameter | Default | Effect | Changing it |
|---|---|---|---|
wal_level | replica | WAL content: minimal, replica, logical | Restart |
fsync | on | Any flush at all | Never off in production |
synchronous_commit | on | What a commit waits for | Any time, per transaction |
wal_sync_method | fdatasync (Linux) | How WAL is flushed | Reload |
full_page_writes | on | Torn-page protection | Reload; keep on |
wal_log_hints | off | FPIs for hint-bit changes | Restart |
wal_compression | off | Compress FPIs (pglz, lz4, zstd) | Superuser, any time |
wal_buffers | -1 (1/32 of shared_buffers) | Shared memory for unwritten WAL | Restart |
wal_writer_delay / wal_writer_flush_after | 200ms / 1MB | WAL writer cadence; async-commit loss window | Reload |
commit_delay / commit_siblings | 0 / 5 | Group commit wait | Superuser |
checkpoint_timeout | 5min | Max time between checkpoints | Reload |
max_wal_size / min_wal_size | 1GB / 80MB | Checkpoint trigger / recycling floor | Reload |
checkpoint_completion_target | 0.9 | Spread of checkpoint writes | Reload |
checkpoint_flush_after | 256kB (Linux) | Gradual writeback during checkpoints | Reload |
checkpoint_warning | 30s | Log when size-triggered checkpoints are too close | Reload |
bgwriter_delay / bgwriter_lru_maxpages / bgwriter_lru_multiplier | 200ms / 100 / 2.0 | Background writer pacing | Reload |
wal_recycle / wal_init_zero | on / on | Reuse/zero-fill segments | Reload |
wal_keep_size | 0 | WAL kept for standbys without slots | Reload |
archive_mode / archive_command / archive_library / archive_timeout | off / empty / empty / 0 | WAL archiving | archive_mode needs restart |
data_sync_retry | off | PANIC on flush failure | Restart |
restart_after_crash | on | Automatic crash recovery after a backend dies | Reload |
recovery_init_sync_method | fsync | Sync data dir before recovery (syncfs on Linux) | Reload |
recovery_prefetch | try | Prefetch blocks during replay | Reload |
data_checksums | on (initdb default since 18) | Page checksums | pg_checksums offline |
Tools Important
| Tool | What it does | Danger |
|---|---|---|
pg_waldump | Decodes 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_controldata | Prints pg_control: state, latest checkpoint, redo location, timeline | None |
pg_test_fsync | Times each wal_sync_method; suggests commit_delay | None |
pg_checksums | Enable/disable/verify data checksums offline | Must run on a stopped cluster, every node |
pg_resetwal | Clears WAL and resets pg_control | Last resort: "the database might contain inconsistent data due to partially-committed transactions" |
pg_archivecleanup | Removes archived WAL older than a restartpoint | Only for archives no other server needs |
diskchecker.pl | Tests whether a disk really persists flushed writes across power loss | Needs 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 / message | Product | Meaning | Action |
|---|---|---|---|
57P03 cannot_connect_now ("the database system is starting up" / "in recovery mode") | PostgreSQL | Recovery in progress | Retry with backoff; do not fail health checks too fast |
57P02 crash_shutdown | PostgreSQL | Another backend crashed; all sessions reset | Retry the transaction; outcome of an in-flight COMMIT is unknown |
57P01 admin_shutdown | PostgreSQL | Fast/immediate shutdown | Retry against the new primary |
XX001 data_corrupted ("invalid page in block") | PostgreSQL | Checksum or page header failure | Restore the relation from replica/backup |
XX002 index_corrupted | PostgreSQL | Corrupt index | REINDEX |
58030 io_error | PostgreSQL | I/O error | Hardware incident |
53100 disk_full | PostgreSQL | Out of space (often pg_wal) | Free space elsewhere; fix archiver/slots |
PANIC: could not fsync file | PostgreSQL | Flush failed; deliberate crash (data_sync_retry = off) | Investigate storage; recovery replays WAL |
LOG: checkpoints are occurring too frequently | PostgreSQL | checkpoint_warning tripped | Raise max_wal_size |
[MY-013598] Server was killed when Innodb Redo logging was disabled | MySQL | Crash with redo disabled | Re-initialise the instance and reload |
NotEnoughReplicas / NotEnoughReplicasAfterAppend | Kafka | ISR below min.insync.replicas with acks=all | Producer retries; fix brokers |
SQLITE_IOERR / SQLITE_FULL | SQLite | I/O failure / disk full | Surface 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).
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Batch work into fewer transactions | Insert 500 rows per COMMIT, or COPY | One flush per batch | Bigger units of retry |
| Per-transaction async commit | SET LOCAL synchronous_commit = off for low-value writes | Commit returns immediately; database stays consistent | Last ~600 ms of those writes can vanish on crash |
| Group commit tuning | commit_delay ≈ half of pg_test_fsync's 8 kB flush time | More commits per flush, durability unchanged | Adds latency at low concurrency |
| Faster WAL device | Put pg_wal on a low-latency NVMe with power-loss protection | Every commit benefits | Hardware cost |
| Asynchronous standby instead of synchronous | synchronous_standby_names = '' | Removes network round trip | Failover can lose commits |
// 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()
}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:
// 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:
// 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:
// 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
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
// 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)
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Make checkpoints time-triggered | Raise max_wal_size until num_requested ≪ num_timed | Fewer, spread checkpoints; fewer FPIs | More WAL on disk; longer recovery |
| Keep spreading | checkpoint_completion_target = 0.9 | Smooth I/O | Do not lower it |
| Smaller writeback bursts | checkpoint_flush_after, bgwriter_flush_after | Avoids end-of-checkpoint fsync stall | Can hurt when data > shared_buffers but < page cache |
| Smaller FPIs | wal_compression = lz4 | Less WAL after each checkpoint | CPU |
| InnoDB | Raise innodb_redo_log_capacity | Fewer flush stalls | Longer recovery |
-- 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();// 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
}// 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
| Cause | How to see it | Fix |
|---|---|---|
archive_command failing | pg_stat_archiver.failed_count rising, log lines | Fix the command; the archiver retries; segments then recycle |
| Inactive replication slot | pg_replication_slots.active = false, large retained bytes | SELECT pg_drop_replication_slot('name'); set max_slot_wal_keep_size |
wal_keep_size too high | SHOW wal_keep_size | Lower it |
| Long checkpoint interval at high write rate | WAL between checkpoints ≈ max_wal_size | Expected; size the disk |
Someone deleted files from pg_wal | Server will not start, "could not open file" | Restore; never delete WAL by hand |
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."
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Idempotency key | UNIQUE (idempotency_key); retry inserts the same key | Retry is safe; duplicate becomes 23505 | Needs a key from the caller |
| Ask the server | Record pg_current_xact_id() before COMMIT; on failure call pg_xact_status(xid) | Exact answer while status is retained | NULL for very old xids; prepared xacts show "in progress" |
| Upsert / natural idempotency | INSERT ... ON CONFLICT DO NOTHING | Simple | Only where the row has a natural key |
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// 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
}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
| Step | PostgreSQL | MySQL InnoDB |
|---|---|---|
| 1. Stop and copy | Copy the whole data directory (including pg_wal) before touching anything | Copy datadir and #innodb_redo |
| 2. Read the log | First PANIC/FATAL line: missing WAL segment, checksum error, could not fsync | [ERROR] lines during redo or rollback |
| 3. Storage first | Disk full? read-only remount? kernel I/O errors? | Same |
| 4. Prefer known-good copies | Promote a replica or restore base backup + WAL (PITR) | Same |
| 5. Last resort | pg_resetwal on the copy, then dump, initdb, restore, verify | innodb_force_recovery = 1, raise one step at a time, dump, rebuild |
Loading data fast without weakening production
| Technique | Product | Trade-off |
|---|---|---|
COPY in one transaction | PostgreSQL | One flush; WAL still written |
CREATE UNLOGGED TABLE | PostgreSQL | Not written to WAL, "automatically truncated after a crash or unclean shutdown", not replicated |
wal_level = minimal + create/truncate and load in one transaction | PostgreSQL | No WAL for that data; breaks PITR and standbys; restart needed |
ALTER INSTANCE DISABLE INNODB REDO_LOG | MySQL | "intended only for loading data into a new MySQL instance" |
PRAGMA synchronous = OFF during an initial build | SQLite | Fine when the build "can be repeated if a power loss occurs" |
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 / workload | Recommended setting | Extra technique | Reason |
|---|---|---|---|
| Payments, ledgers, orders, inventory | synchronous_commit = on; InnoDB 1 + sync_binlog = 1 | Synchronous standby in another zone; idempotency keys | An acknowledged loss is a business incident |
| User-generated content (posts, comments) | Defaults | Async standby is usually acceptable | Losing seconds on failover is tolerable, corruption is not |
| Events, click streams, metrics in PostgreSQL | SET LOCAL synchronous_commit = off per transaction | Batch inserts | Loss window ≤ ~600 ms, no corruption |
| Session store, caches, rate-limit counters | Redis with RDB or appendfsync everysec | Treat as rebuildable | Speed matters more than the last second |
| Staging / ETL scratch tables | UNLOGGED | Rebuild on crash | No WAL, truncated after crash |
| CI test databases | fsync = off, full_page_writes = off acceptable | Recreate per run | Data is disposable |
| Embedded/mobile app (SQLite) | WAL mode + synchronous = NORMAL (or FULL for money) | Checkpoint in background | Consistent always; durable across app crash |
| Event streaming (Kafka) | acks=all, RF 3, min.insync.replicas = 2; leave flush defaults | Replicas in different racks/zones | Replication, not fsync, is the durability |
| MongoDB orders collection | w: "majority" (journaled) | Retryable writes | Durable on a majority before ack |
| Analytics replica (MySQL) | innodb_flush_log_at_trx_commit = 2 | Rebuild from primary if lost | Replica 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).
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 idDistributed 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_fsynconce; archiving on; monitorpg_stat_checkpointerandpg_walsize. - 10×: commit rate becomes the bottleneck: batch writes, use async commit for low-value tables, move
pg_walto a dedicated low-latency device, raisemax_wal_sizeso checkpoints are time-triggered, considerwal_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.
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 BCREATE 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.
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' survivedExperiment 2: kill the whole server, not just a backend.
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.
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.
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');# 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.
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.
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
| Belief | Reality |
|---|---|
| "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
| Topic | What to remember |
|---|---|
| Write-ahead rule | Log flushed before page written; commit = commit record flushed |
| LSN | Byte offset in WAL; pg_current_wal_lsn(), pg_wal_lsn_diff() |
| Segments | 16 MB in pg_wal/, recycled after checkpoints and archiving |
synchronous_commit | off < local < remote_write < on < remote_apply; per transaction with SET LOCAL |
| Async commit loss | ≤ 3 × wal_writer_delay (600 ms default); no corruption |
fsync = off | Corruption risk; throwaway clusters only |
| Group commit | Free at concurrency; commit_delay ≈ half a flush when flushes are slow |
| Torn pages | full_page_writes = on (PostgreSQL), doublewrite (InnoDB) |
| Checkpoints | checkpoint_timeout 5min, max_wal_size 1GB, target 0.9; want num_timed ≫ num_requested |
| Recovery | pg_control → checkpoint → redo record → replay to end of valid WAL; no undo in PostgreSQL |
| ARIES | Analysis, redo (repeating history), undo with CLRs |
| fsyncgate | PANIC on flush failure (data_sync_retry = off) |
| Hardware | Test with pg_test_fsync; no volatile write-back cache without BBU/PLP |
| InnoDB | innodb_flush_log_at_trx_commit = 1, sync_binlog = 1, doublewrite on, size innodb_redo_log_capacity |
| Other engines | SQLite synchronous; Redis appendfsync; Kafka acks=all + min ISR; MongoDB j: true |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Durability | The 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 rule | WAL up to a page's LSN must be flushed before that page is written |
| WAL record | One 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 segment | A 16 MB WAL file in pg_wal/ (size set by initdb --wal-segsize) |
wal_level | How much the WAL contains: minimal, replica, logical |
effective_wal_level | PostgreSQL 19 read-only setting showing the level actually in use |
| Redo / roll-forward | Replaying log records to rebuild pages after a crash |
| Redo record / redo point | The WAL position a checkpoint guarantees everything before is on disk; replay starts there |
pg_control | Small control file holding the latest checkpoint location and cluster state |
fsync | System call (and PostgreSQL setting) that forces a file's data and metadata to stable storage |
fdatasync | Like fsync but skips non-essential metadata; PostgreSQL's Linux default |
O_DSYNC / O_SYNC | Open flags that make each write synchronous (open_datasync, open_sync) |
O_DIRECT | Open flag that bypasses the OS page cache; not a durability guarantee by itself |
O_DIRECT_NO_FSYNC | InnoDB flush method that skips fsync() after writes; risky with separate devices |
wal_sync_method | PostgreSQL choice of flush call for WAL |
fsync_writethrough | wal_sync_method value that forces write-through of the disk cache (macOS) |
synchronous_commit | What a PostgreSQL commit waits for: off, local, remote_write, on, remote_apply |
remote_apply | Commit waits until a synchronous standby has replayed it |
| Asynchronous commit | Ack before WAL flush; loses recent commits, never consistency |
| Group commit | One WAL flush shared by several concurrent commits |
commit_delay / commit_siblings | Leader wait (µs) before a flush / minimum active transactions for the wait |
| WAL writer | Process that flushes WAL every wal_writer_delay (200 ms) or wal_writer_flush_after |
wal_buffers | Shared memory for WAL not yet written |
| Torn page | Page left half old, half new by a power loss mid-write |
full_page_writes | Log 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_compression | Compress full-page images (pglz, lz4, zstd) |
wal_log_hints | Also log FPIs for hint-bit-only changes |
| Checkpoint | Flush all dirty pages and write a checkpoint record that sets the redo point |
checkpoint_timeout | Maximum time between checkpoints (default 5min) |
max_wal_size / min_wal_size | Soft WAL size that triggers a checkpoint / recycling floor |
checkpoint_completion_target | Fraction of the interval over which checkpoint writes are spread (0.9) |
| Spread checkpoint | Checkpoint whose writes are paced across the interval |
| Checkpoint storm | Size-triggered checkpoints in quick succession causing I/O and FPI bursts |
checkpoint_warning | Logs a warning when size-triggered checkpoints are closer than this |
checkpoint_flush_after | Ask the OS to write back checkpoint data in small steps |
| Restartpoint | A standby's equivalent of a checkpoint |
| Background writer | Writes dirty buffers ahead of demand (bgwriter_delay, bgwriter_lru_maxpages) |
| Checkpointer | Process that performs checkpoints |
| WAL recycling | Renaming old segments for reuse (wal_recycle) |
wal_keep_size | WAL kept for standbys regardless of slots |
| Replication slot | Server-side marker that retains WAL a consumer has not received |
archive_mode / archive_command / archive_library | Hand completed segments to an archive |
archive_timeout | Force a segment switch so idle periods still get archived |
| PITR | Point-in-time recovery from a base backup plus archived WAL |
| Crash recovery | Automatic redo from the last checkpoint at startup after an unclean stop |
restart_after_crash | Reinitialise and run recovery automatically after a backend crash |
recovery_init_sync_method | Sync the data directory before recovery (fsync or syncfs) |
recovery_prefetch | Prefetch blocks referenced by WAL during replay |
| ARIES | 1992 recovery method: WAL, page LSNs, analysis/redo/undo, CLRs |
| Repeating history | ARIES redo replays all logged updates, losers included, before undo |
| Compensation log record (CLR) | Redo-only record written for each undo step in ARIES |
| Loser transaction | A transaction with no commit record at the crash |
| Data checksums | Per-page checksum verified on read (default on since PostgreSQL 18) |
pg_checksums | Offline tool to enable, disable or verify data checksums |
| CRC-32C | Checksum protecting each WAL record |
| fsyncgate | The 2018 discovery that failed fsync() errors could be lost or retried falsely on Linux |
data_sync_retry | Off by default: PANIC on data-file flush failure |
| Write-back cache | Device/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_fsync | Times each sync method; sanity-checks the disk |
diskchecker.pl | Tests whether a disk really persists flushed writes across power loss |
| EBS / Persistent Disk | AWS and Google Cloud network block storage with published annual durability |
pg_waldump | Decodes and prints WAL records |
pg_controldata | Prints the contents of pg_control |
pg_resetwal | Last-resort tool that clears WAL and resets control data |
pg_xact_status | Reports whether a recent transaction id committed, aborted or is in progress |
| Ambiguous commit | The client cannot know whether a commit succeeded because the reply was lost |
UNLOGGED table | PostgreSQL table not written to WAL, truncated after a crash |
| InnoDB redo log | InnoDB's WAL, sized by innodb_redo_log_capacity |
innodb_redo_log_capacity | Total redo log size (default 100 MB in MySQL 8.4) |
innodb_flush_log_at_trx_commit | InnoDB commit durability: 1 (flush), 2 (write), 0 (neither) per commit |
innodb_flush_log_at_timeout | Seconds between background redo flushes for settings 0 and 2 |
innodb_flush_method | How InnoDB opens and flushes files (O_DIRECT, fsync, O_DSYNC...) |
| Doublewrite buffer | InnoDB area where pages are written and flushed before their real location |
innodb_doublewrite | ON/DETECT_AND_RECOVER, DETECT_ONLY, OFF |
| Binary log (binlog) | MySQL log of committed changes for replication and PITR |
sync_binlog | How 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_recovery | Emergency startup levels 1–6; 4+ can permanently corrupt data |
journal_mode | SQLite journaling: DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF |
PRAGMA synchronous | SQLite flush policy: OFF, NORMAL, FULL, EXTRA |
AOF / appendfsync | Redis append-only file and its fsync policy (always, everysec, no) |
| RDB | Redis point-in-time snapshot file |
log.flush.interval.messages | Kafka broker setting for forced flushes; effectively never by default |
acks=all / min.insync.replicas | Kafka producer ack level and the ISR size required for it |
j: true | MongoDB write concern option: acknowledge after the journal is flushed |
| Delayed durability | SQL Server lazy commit (DELAYED_DURABILITY) |
COMMIT WRITE NOWAIT | Oracle commit that returns before redo is written |
57P03 / XX001 | PostgreSQL SQLSTATEs for "cannot connect now" (recovery) and data corruption |
References
- PostgreSQL 19 documentation: 28.1 Reliability, 28.2 Data Checksums, 28.3 Write-Ahead Logging, 28.4 Asynchronous Commit, 28.5 WAL Configuration, 28.6 WAL Internals, 19.5 Write Ahead Log settings, 19.4 Resource Consumption (background writer), 19.14 Error Handling, Statistics views, System information functions, System administration functions, Error codes, CREATE TABLE (UNLOGGED), pg_waldump, pg_resetwal, pg_test_fsync
- PostgreSQL 17 and 18 Data Checksums pages (default changed in 18)
- C. Mohan, D. Haderle, B. Lindsay, H. Pirahesh, P. Schwarz, "ARIES: A Transaction Recovery Method Supporting Fine-Granularity Locking and Partial Rollbacks Using Write-Ahead Logging", ACM TODS 17(1), March 1992. PDF
- PostgreSQL wiki, Fsync Errors
- MySQL 8.4 Reference Manual (read via web.archive.org): Redo Log, Doublewrite Buffer, InnoDB Startup Options and System Variables, InnoDB Recovery, Forcing InnoDB Recovery, The Binary Log, Binary Logging Options and Variables
- SQLite: Write-Ahead Logging, PRAGMA statements
- Redis: Persistence
- Apache Kafka 4.1: Design, Broker configs, Producer configs
- MongoDB: Journaling
- Microsoft SQL Server: Control transaction durability
- Oracle Database 19c SQL Reference: COMMIT
- CockroachDB: Replication Layer
- AWS: Amazon EBS volume types; Google Cloud: Persistent Disk
- Go:
database/sql. Laravel 13: Database: Getting Started, Transactions; framework source: UniqueConstraintViolationException.php