Replication exists because every database server goes down eventually: a disk fails, a kernel panics, a data center loses power, or the server simply needs patching. With a single server, the application is down until it comes back, and if the disk is gone, the data exists only in backups until someone restores them. Replication keeps the same data on more than one server, so that when one goes down another takes over and the application carries on, ideally noticing nothing more than a few failed queries and a reconnect. That is high availability, and it comes in two broad shapes: a cluster whose members agree on every write before it counts, or one server that sends its changes to others that can be promoted when it fails.
PostgreSQL’s built-in replication is the second shape, and here is how it works, in outline. One server, the primary, takes every write and records each change in its log; it streams that log to the others, the replicas (PostgreSQL’s documentation also calls them standbys), which replay it against their own copy. When the primary fails, a replica is promoted to take its place, and tools such as Patroni automate that part: they watch the primary, pick a replica, promote it and point the application at it. Because the replicas hold the data anyway, they can also answer reads, while writes still go to one server.
The weak spot is “ideally noticing nothing”. The replicas are always a little behind, so a read sent to one right after a write can miss it: a row read from a replica the instant its insert had succeeded was missing 5,995 times out of 6,000, even with both servers on the same machine, and arrived about a millisecond later. Whatever a replica has not received when the primary dies is what a failover, the switch to a replica, loses, and measuring that is most of this post.
A quick reminder about what COMMIT promises
A transaction is a group of statements the database treats as one unit: you open it with BEGIN, and COMMIT keeps every change while ROLLBACK throws every change away. Of the four guarantees summed up as ACID, the one replication is about is durability: once COMMIT returns, the change survives a crash. PostgreSQL keeps that promise with its write-ahead log (WAL). Every change is written into the WAL before it touches the table, and COMMIT returns once the commit’s log record is flushed to disk. After a crash, PostgreSQL replays the WAL to put back anything the tables had not caught up with.
Durable here means durable on this server’s disk. If that disk or that machine is gone for good, every commit that existed only there is gone with it, and copying those commits to another machine before anyone needs them is the job replication does. How soon “before” is turns out to be a setting.
The WAL is what gets copied
The tests in this post ran in Docker on one laptop. Each server got 1 CPU and 768 MB of memory, a primary had two replicas made with pg_basebackup (the tool that copies a running server), and everything ran at the default settings except where a test says otherwise. On the same host, a round trip between two servers took 0.1 ms. To stand in for servers further apart I added network delay with tc netem; the Docker VM could not add less than about 3 ms in each direction, so the tables quote the round trip I measured (6 ms or 22 ms), not the delay I asked for.
A replica starts as a copy of the primary’s data directory and then streams the WAL. A process on the primary (the WAL sender) sends WAL records as they are written, and a process on the replica (the WAL receiver) writes them to the replica’s own WAL, where the startup process replays them, the same way crash recovery would. Because the WAL describes changes to the blocks of the data files, the result is a byte-for-byte copy of the whole server: every database, every table, every index. The copy is read-only, and it says so:
| |
The primary reports each replica in pg_stat_replication, with its position in the WAL (the lsn columns) and how far behind it is at three steps: written to the replica’s disk, flushed there, and replayed so queries can see it.
| |
The time between a commit on the primary and the moment a replica’s queries can see it is called replication lag. Here is what it did to a page that reads a row right after writing it. One connection inserted a row on the primary and, as soon as COMMIT returned, a second connection looked for it on a replica:
| Round trip between servers | Reads that missed the new row | Row visible on the replica after (median / p99) |
|---|---|---|
| Same host (0.1 ms) | 5,995 of 6,000 | 1.0 ms / 3.9 ms |
| 6 ms | 2,000 of 2,000 | 2.1 ms / 5.4 ms |
| 22 ms | 1,000 of 1,000 | 11.0 ms / 14.2 ms |
Same host: three runs of 2,000; p99 is the median of the three runs’ p99.
A millisecond of lag is invisible to a person and certain to a program, because the program’s next query arrives sooner than that. The usual fix is to send a user’s reads to the primary for a short while after they write (often called read-your-writes routing), or to route by what the page needs: the order confirmation goes to the primary, the product catalog to a replica.
Large transactions barely change that picture, which is where PostgreSQL differs from MySQL. I ran one UPDATE that changed all 1,000,000 rows of a table, three times. It took 3.1 to 4.5 s on the primary, and the replica showed the new values 0.10 to 0.16 s after COMMIT returned. The WAL streams while the transaction is still running, so the replica replays the changes alongside the primary and has almost nothing left to do at commit. (MySQL ships a transaction only once it commits, and the same test left its replica 3.4 s behind; the MySQL replication post has the details.)
Replaying a transaction before it commits sounds like it could show half-finished work, and it cannot. The replica writes the new rows into its tables as they arrive, but a query on a replica sees a transaction’s changes only “once the commit record for a transaction is replayed” (manual). If the primary rolls the transaction back, there is nothing to undo on either server: the rollback is one more WAL record, the replica replays it, and the rows that were already written stay on both as garbage until VACUUM, PostgreSQL’s cleanup process, removes them on the primary, a cleanup that is replicated too. A primary that dies partway through never sends a commit record at all, so a promoted replica treats that transaction as one that never committed. What a rolled-back million-row update does leave behind is a million discarded rows on every replica as well as on the primary. I did not run the rollback or the crash for this post; that is how PostgreSQL’s commit bookkeeping works, and the pages of the manual I checked state only the visibility rule quoted above.
DELETE without a WHERE or a dropped table is replayed as faithfully as an insert, which in the tests above took about a millisecond. Replicas protect against losing a machine; protecting against a bad statement takes backups you can restore to a point in time, which the backups post covers.What a commit waits for
The lag above comes from a choice about when COMMIT returns. In asynchronous replication, the default, the primary acknowledges a commit as soon as its own disk has it and streams the change afterwards. Synchronous replication makes the commit wait for a replica as well. You list the replicas allowed to be synchronous in synchronous_standby_names, and synchronous_commit decides how far along the replica has to be:
At on, the default once a replica is listed, the commit waits until the replica has flushed the change to its disk. At remote_apply, it waits until the replica has replayed it, “so that it has become visible to queries on the standby(s)” (documentation). A third value, remote_write, waits only until the replica has handed the change to its operating system, which survives a replica PostgreSQL crash but not a replica machine crash; I did not test it.
Only remote_apply promises that a read on the replica sees the commit. on promises that the replica has the change on disk, which protects against losing it but says nothing about whether a query can see it yet. The tests found that gap, narrowly: at on on the same host, 1 of 2,000 reads missed the new row, against none in 5,000 at remote_apply.
What the wait costs depends on distance. On the same host it barely registered: a commit went from 0.6 ms to 1.4 ms at on and 1.6 ms at remote_apply. At a 22 ms round trip, every commit paid the round trip:
| Setting, 22 ms round trip | Commit time (median / p99) | Replica reads that missed the new row | Commits per second, 16 sessions |
|---|---|---|---|
| Async | 0.6 ms / 1.5 ms | 1,000 of 1,000 | 6,550 to 8,080 |
Sync at on | 29.9 ms / 37.0 ms | 0 of 1,000 | 560 to 580 |
Sync at remote_apply | 30.1 ms / 39.8 ms | 0 of 1,000 | not measured |
Commit times: 1,000 single-row inserts from one session. Commits per second: separate runs, three of 10 seconds each, with 16 sessions inserting one row per transaction. The two columns come from different runs, so they do not multiply out exactly (16 sessions at 29.9 ms would give about 535/s).
A session that commits one row at a time can do about 33 commits a second at 30 ms each, however fast the server is, so throughput falls by more than ten times unless the application runs more sessions in parallel. That is why synchronous replicas usually sit in the same region, often in a different availability zone a millisecond or two away, while replicas in other regions stay asynchronous. synchronous_commit can also be set per transaction, so a payment can wait for the replica while a page-view counter does not.
When the primary goes away
The point of having a replica is to promote it when the primary dies (with pg_promote() or pg_ctl promote), and the question every failover raises is what the client was told succeeded that the new primary does not have.
The first test killed the primary’s container while 16 sessions were inserting rows, waited for the replica to replay everything it had received, and compared its rows with the commits the clients had seen acknowledged. With asynchronous replication, 3, 8 and 6 acknowledged commits were lost on the same host, and 0, 9 and 4 at a 22 ms round trip. With synchronous replication at on, none were lost in three runs.
The synchronous runs turned up the opposite surprise instead. Each time, the replica held 16 rows more than the clients had seen acknowledged, one per session: commits the replica had confirmed whose acknowledgement died with the primary on its way back to the client. The application saw an error for each, so a retry would write those rows twice.
A crash is the gentle case, because the primary stops writing at the same moment it stops sending. A network partition is worse, because a primary that can still reach its clients but not its replicas keeps accepting writes. That is what happened to GitHub in October 2018: a 43-second network outage, a failover to MySQL primaries on the other coast, and East Coast servers that “contained a brief period of writes that had not been replicated to the US West Coast facility.” The promoted primaries never received those writes, so GitHub had to reconcile them by hand, and the site stayed degraded for 24 hours and 11 minutes (GitHub’s analysis, October 30, 2018). Different engine, same shape.
The second test reproduced it on PostgreSQL. After 5 seconds of writes I cut the network between the primary and its replicas while leaving the clients connected, kept writing for 15 seconds, then killed the primary and counted what the replica had:
| Setting | Acknowledged commits lost (per run) | What the clients saw during the partition |
|---|---|---|
| Async | 161,406 / 165,729 / 162,403 | nothing unusual: commits kept returning in under 0.1 s |
Sync at on | 0 / 0 / 0 | no commit returned at all until the primary was killed |
Same host, 16 sessions inserting one row per transaction; the partition was applied with tc and took about 2 seconds to cover every link.
Asynchronous replication lost nearly everything written after the cut, because nothing about the commit depended on the replicas. Synchronous replication kept its promise by stopping: with its only synchronous replica unreachable, every commit waited, and from the application’s side the database was down for writes. PostgreSQL has no timeout for that wait. The usual way to soften it is to name several replicas and wait for any one of them, synchronous_standby_names = 'ANY 1 (r1, r2)', so a single slow or missing replica does not stop writes; I did not measure that setup. Whatever the setting, the failover has to promote the replica that received the most WAL (compare pg_last_wal_receive_lsn() on each), after letting it finish replaying what it received, and has to make sure the old primary cannot come back and accept writes on its own.
Replicas add reads, not writes
Every replica replays every write the primary makes and refuses writes of its own (the error near the top of this post), so adding replicas adds read capacity and no write capacity at all. A test with pgbench, PostgreSQL’s bundled load generator, shows both halves: a read-only workload of primary-key lookups, and a write workload of single-row updates and inserts. Each server had 1 CPU and 16 client connections, and each run lasted 20 seconds.
| Setup | Read-only transactions/s | Write transactions/s |
|---|---|---|
| Primary alone | 43,768 | not measured |
| Primary + 2 replicas, reads spread across all three | 138,484 (3.2×) | 7,557, all of them on the primary |
Median of three runs. The primary-alone read run was measured with another container keeping the host’s CPUs busy, because with the host idle the same test ran about 30% slower (31,000 to 32,700/s): the laptop gave the VM faster cores under load.
Reads scaled almost exactly with the number of servers, because a primary-key lookup on one copy is as cheap as on any other. Writes are capped by what one primary can do, however many replicas sit behind it, and each replica has to replay that same write rate to stay current. When the writes are what outgrows one server, the next step is splitting the rows themselves across several primaries, called sharding, which gets a post of its own.
What to watch
Replication slots are the one replication feature that can take the primary down. A slot is the primary’s promise to keep WAL until a named replica has received it, so a replica that was offline for an hour can carry on where it stopped instead of being rebuilt from a fresh copy. The replicas in these tests were created with slots (pg_basebackup -C -S slot1), and the promise has no limit by default: max_slot_wal_keep_size is -1. I stopped one replica and kept writing on the primary with pgbench, about 3,000 small transactions a second, checking the slots and the size of the WAL directory every 20 seconds:
| |
The WAL directory grew by 768 MB in two minutes, about 6.4 MB a second, all of it held for a replica that was not there. At that rate a 100 GB volume would fill in a little over four hours, and PostgreSQL shuts down when it can no longer write WAL.
max_slot_wal_keep_size so a slot that falls too far behind is given up: its wal_status turns unreserved once it needs more WAL than the limit allows, then lost after the next checkpoint removes that WAL, and that replica has to be rebuilt. PostgreSQL 18 also has idle_replication_slot_timeout, off by default, which invalidates a slot that has gone unused for that long. Either way, alert on any row in pg_replication_slots with active = false.| Question | Async | Sync at on | Sync at remote_apply | Source |
|---|---|---|---|---|
| Read right after a write sees it on a replica? | No (5,995 of 6,000 missed) | Almost always (1 of 2,000 missed) | Yes (0 of 5,000 missed) | measured |
| Commit time at a 22 ms round trip (median) | 0.6 ms | 29.9 ms | 30.1 ms | measured |
| Acknowledged commits lost when the primary crashed | 0 to 9 per run | 0 | not separately tested | measured |
| In a 15 s partition | about everything written after the cut | writes stop, nothing lost | as on | measured |
| More read capacity | Yes, 3.2× with 3 servers | Yes | Yes | measured |
| More write capacity | No | No | No | measured |
On the primary, pg_stat_replication holds the lag: replay_lag for how stale a replica’s reads are, flush_lsn for how much an asynchronous failover could lose, as bytes the replica has not yet flushed (pg_wal_lsn_diff(pg_current_wal_lsn(), flush_lsn)), and sync_state to confirm that the replica you think is synchronous really is. On a replica, pg_last_xact_replay_timestamp() gives the time of the last transaction it replayed, which is the number to compare against the clock when the primary is quiet and the lag columns go empty.
