SENIORCHAPTER 19

Replication: physical, logical, sync and async

Ship the WAL to another machine, measure how far behind it is, lose a commit you acknowledged, then pay to stop losing it

60 MINDATABASESUPDATED 2026-11-02
PREDICT

A primary runs with one asynchronous streaming replica. A client runs UPDATE ... ; COMMIT; and gets COMMIT back. 20 ms later the primary's host dies, and you promote the replica. Is the update on the new primary?

The write-ahead logging chapter ended with a sentence this chapter cashes in: a replica is a server in permanent recovery, replaying WAL streamed from somewhere else. Everything about replication follows from that. Lag is the distance between the WAL the primary has written and the WAL the replica has replayed. Losing a commit is promoting a replica that never received it. Synchronous replication is making COMMIT wait for a second machine’s flush. And logical replication is decoding the same WAL back into rows so a different kind of consumer can apply them.

This chapter goes through physical streaming replication in the order you meet its failure modes in production: lag and stale reads, data loss on failover, the cost of making that loss zero, the slot that fills your disk, the replica query that gets cancelled, and logical replication with the things it does not carry.

A replica is recovery that never ends

A physical standby starts as a byte-for-byte copy of the primary’s data directory, taken with pg_basebackup while the primary keeps running. The copy carries a standby.signal file and a primary_conninfo setting. On start, the server sees the signal, enters recovery, and instead of stopping at the end of local WAL it connects to the primary and asks for more.

Two processes carry the stream. On the primary, a walsender per replica reads WAL from pg_wal (or from WAL buffers) and sends it as soon as it is flushed. On the replica, the walreceiver writes what arrives into its own pg_wal, flushes it, and reports its position back. The startup process, the same one that runs crash recovery, replays the records into the data pages. With hot_standby = on (the default) the replica accepts read-only queries while it replays.

Because it replays physical page changes, a physical replica is exact: same major version, same architecture, same everything, including bloat, indexes and dead tuples. It replicates the whole cluster, every database, with no choice of tables. And it has no idea what a row is. That is its strength (nothing to configure, nothing to get out of sync) and the reason logical replication exists.

The replica reports four positions, and pg_stat_replication on the primary shows all of them:

column meaning the lag column that goes with it
sent_lsn WAL the walsender has sent —
write_lsn written to the replica’s OS, not yet flushed write_lag
flush_lsn flushed to the replica’s disk flush_lag
replay_lsn applied to the replica’s pages, visible to its queries replay_lag

The *_lag columns are time: how long ago the primary flushed WAL that the replica has only now written, flushed or replayed. They are measured from feedback messages, so they go to NULL a few seconds after the replica is fully caught up and the primary is idle. That NULL means “nothing to measure”, not “unknown”. For a byte measure, which is what alerting should use because it does not depend on traffic, subtract LSNs: pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn).

Write and flush lag are the network and the replica’s disk. Replay lag is a single process applying the WAL that a whole primary’s worth of backends generated in parallel. On a busy primary, replay is where lag builds, and the next sections show what else can stop it.

Stale reads, in the simulation

Sending reads to replicas is the first reason most teams add them, and it changes the consistency you offer without anyone deciding to. The simulation has one primary and two asynchronous replicas that apply WAL at different speeds. Client A writes and then reads; client B only reads.

Run STALE READ and watch A’s own read go to R1 before R1 has applied A’s write: read-your-writes is broken. Then B reads R2 (new value) and R1 (old value): time goes backwards for B, which breaks monotonic reads. LUCKY TIMING is the same code with faster shipping, and it passes, which is why this bug survives testing. FIX: LSN ROUTING gives each client a token, the LSN of its last write or read, and only routes it to a replica whose replayed LSN has reached the token. STICKY REPLICA fixes monotonic reads but not read-your-writes.

▶ SIMULATION
PRIMARY
LSN 100 · email old
WAL entries not on every replica: 0
t = 0 ms · routing: round-robin
CLIENT READS (value@LSN)
A: —
B: —
stale reads 0 · backwards reads 0
REPLICAS (async)
R1: LSN 100 · email old · lag 0 ms
R2: LSN 100 · email old · lag 0 ms
last eventeveryone at LSN 100, email = old
✓ read-your-writes: no client reads older than its own acked write✓ monotonic reads: no client reads older than what it already read
SCHEDULE
01[SYS]reads go to any replica (round-robin)
02[A]A: UPDATE email = new → primary
03[REPL]R2 applies the next WAL entry
04[A]A: SELECT email
05[B]B: SELECT email
06[B]B: SELECT email
07[REPL]R1 applies the next WAL entry
08[SYS]report
Start of stale read scenario. 8 steps.
// write to the primary, read from whatever the balancer picks
await primary.query("UPDATE users SET email = $1 WHERE id = $2", [email, id]);

const replica = loadBalancer.pick();          // any replica, any lag
return replica.query("SELECT email FROM users WHERE id = $1", [id]);
FIX IT NOT YET

Write route(read, clientLsn, primary, replicas). clientLsn is the highest LSN this client has written or read. Return a replica whose appliedLsn is at least clientLsn; only if none is caught up, return primary. Prefer replicas: the primary is the one node you cannot scale.

In Postgres the token is real. After a write, the application stores pg_current_wal_lsn() (or pg_current_wal_insert_lsn()) from the primary in the session or a cookie. Before reading from a replica it checks pg_last_wal_replay_lsn() >= $token there and falls back to the primary, or waits, if the replica is behind. Lag is not a number you configure away, so routing is something your application or proxy has to know about. The replication lag lesson has the general version.

Asynchronous: what a failover loses

By default replication is asynchronous. COMMIT waits for the local WAL flush and nothing else; the walsender ships the record as soon as it can. On a LAN with a healthy replica, the record arrives within a millisecond or two, and if you promote the replica after a crash you lose nothing or a handful of transactions.

That “usually” is the whole problem. The amount you lose on failover is the lag at the instant of failure, and lag is unbounded:

  • A bulk load or a big UPDATE generates WAL faster than one startup process can replay it. Lag grows to minutes.
  • A replica query holds back replay (the conflict section below). Lag grows by up to max_standby_streaming_delay, 30 s by default, per conflict.
  • A network partition stops the stream. Lag grows for as long as the partition lasts, and the primary keeps accepting writes the whole time.

The last case is the dangerous one, because it is also exactly when an HA tool decides the primary is dead and promotes a replica. Your recovery point objective under async replication is not “a few milliseconds”; it is “however far behind the replica was when we failed over”. Write that down as the RPO, and decide whether the business accepts it, before choosing async.

Two settings help without going synchronous. maximum_lag_on_failover in Patroni (or the equivalent in your HA tool) refuses to promote a replica more than N bytes behind. And alerting on replay lag in bytes catches the slow drift before the incident. Neither saves a commit that was never sent.

Synchronous: what not losing costs

synchronous_standby_names turns on synchronous replication. The primary then makes COMMIT wait for standbys as well as for its own flush. Which standbys, and for what, are two separate settings.

Which standbys:

-- the first listed standby that is connected must confirm; the second is a hot spare
ALTER SYSTEM SET synchronous_standby_names = 'FIRST 1 (replica1, replica2)';
-- any one of the listed standbys may confirm (quorum commit)
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica1, replica2)';
SELECT pg_reload_conf();

The names are each standby’s application_name, which defaults to its cluster_name. pg_stat_replication.sync_state shows the result: sync and potential with FIRST, quorum with ANY, async for anything not listed.

What COMMIT waits for is synchronous_commit, which you met on one node and which now has its full meaning:

synchronous_commit COMMIT returns when survives
off WAL is in memory; flushed within 3 × wal_writer_delay nothing guaranteed
local flushed on the primary primary crash
remote_write flushed on the primary and written (not flushed) on the standbys primary loss, unless the standby’s OS also crashes
on (default) flushed on the primary and flushed on the standbys loss of the primary and a standby crash
remote_apply flushed on both and replayed on the standbys the above, and reads on those standbys see the commit

The price is a network round trip plus the standby’s fsync on every commit. Inside one availability zone that is 0.2 to 1 ms. Between zones of one cloud region it is 1 to 3 ms. Between regions it is the speed of light: Frankfurt to Virginia is about 90 ms round trip, so a synchronous cross-region commit costs at least 90 ms and a single connection cannot exceed about eleven sequential commits per second. Throughput across many connections survives better than latency, because commits in flight at the same moment share one round trip, the same group-commit effect you saw with fsync.

The second price is availability. If no synchronous standby is connected, COMMIT waits forever. Not an error: a hang. Cancelling the wait produces this, which surprises everyone the first time:

WARNING:  canceling wait for synchronous replication due to user request
DETAIL:  The transaction has already committed locally, but might not have been replicated to the standby.

The transaction is committed on the primary and visible to other sessions. Cancelling does not roll it back, because the commit record is already flushed and the only thing left to do was wait. Your application saw an error for a write that happened. That is why one synchronous standby is a liability (its maintenance window is your outage) and the usual production shape is three nodes with ANY 1 (a, b): any one of two replicas confirms, so either can be down. Patroni’s synchronous_mode manages the list for you and, with synchronous_mode_strict: false, falls back to async when no standby is available, which trades the zero-RPO promise back for availability. Know which one you configured.

Note what synchronous replication does not give you: consistent reads on the replicas. With on, the standby has the WAL on disk but may not have replayed it, so a read there can still be stale. Only remote_apply closes that, and it adds replay time to every commit.

Replication slots, and how WAL fills a disk

A replica that disconnects for an hour needs an hour of WAL when it comes back. Without a slot, the primary removes WAL at each checkpoint once it is no longer needed for crash recovery, beyond wal_keep_size (0 by default). The replica returns, asks for a segment that is gone, and logs requested WAL segment ... has already been removed. It can never catch up by streaming; it needs a fresh base backup. That is the GitLab sequence.

A replication slot fixes this by making the primary remember each consumer’s position (restart_lsn) and keep all WAL after it. pg_basebackup -C -S name creates one when it builds the replica. The slot survives restarts and disconnections.

The failure flips. Now an abandoned slot, a replica that was deleted without dropping its slot, or a logical consumer that stopped, keeps WAL forever. pg_wal grows at the primary’s WAL rate, which on a busy server is tens of GB per hour, until the volume fills and Postgres PANICs. The cap is max_slot_wal_keep_size (default -1, unlimited). Set it to a size you can afford, and the slot is invalidated instead of the primary dying:

SELECT slot_name, slot_type, active, wal_status, safe_wal_size,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;

wal_status reads reserved (within max_wal_size), extended (beyond it, still kept), unreserved (past the cap, will be removed at the next checkpoint) and finally lost. safe_wal_size is how many more bytes can be written before the slot is lost. Alert on retained and on active = false for more than a few minutes; a slot is a promise the primary keeps on behalf of a consumer it cannot see.

Queries on a replica fight replay

A long query on a replica wants the row versions in its snapshot to stay. Meanwhile the primary vacuums and removes those versions, and the replica has to replay that removal. One of them has to give way. The startup process waits up to max_standby_streaming_delay (30 s by default) and then cancels the query:

ERROR:  canceling statement due to conflict with recovery
DETAIL:  User query might have needed to see row versions that must be removed.

You have three knobs and no free choice:

  • Raise max_standby_streaming_delay, up to -1 (wait forever). Reporting queries survive; replay stalls behind them, so lag grows by as long as the longest query. Fine for a dedicated reporting replica, terrible for a failover candidate.
  • Set hot_standby_feedback = on on the replica. It reports its oldest snapshot to the primary, and the primary’s vacuum stops removing rows the replica might need. No cancellations, and a two-hour query on the replica now pins the vacuum horizon on the primary for two hours, with the bloat the MVCC chapter showed you.
  • Keep long queries off replicas that matter for failover. A separate analytics replica with a long delay, or a logical copy, isolates the damage.

pg_stat_database_conflicts on the replica counts cancellations by cause (snapshot, lock, buffer pin, tablespace, deadlock). A sudden rise after a schema change or a vacuum tuning change is usually this.

Logical replication: rows, not pages

Logical replication decodes the WAL back into row changes (insert this tuple, update that key) and ships those. The primary needs wal_level = logical, which adds enough information to the WAL to reconstruct rows, typically a few percent more WAL. The pieces are SQL objects:

-- on the publisher
CREATE PUBLICATION inv_pub FOR TABLE inventory;
-- on the subscriber, a separate writable server with the table already created
CREATE SUBSCRIPTION inv_sub
  CONNECTION 'host=db dbname=shop user=atlas password=atlas'
  PUBLICATION inv_pub;

The subscription creates a logical slot on the publisher, copies the existing rows with COPY, then applies the stream through a built-in decoding plugin, pgoutput. Because it carries rows, it can do what physical replication cannot: replicate a subset of tables or rows (publications accept column lists and WHERE filters since Postgres 15), cross major versions (the standard near-zero-downtime upgrade path), feed a database whose other tables are written locally, and feed non-Postgres consumers such as Debezium through the same decoding interface.

It also loses what made physical replication foolproof:

  • No DDL. Schema changes are not replicated. Add a column on the publisher, write a row, and the subscriber’s apply worker errors that the target table is missing a replicated column, then retries in a loop. The publisher’s slot holds WAL the whole time.
  • No sequences in Postgres 17. At cutover you set every sequence on the new side by hand, or the first insert collides.
  • Updates and deletes need a replica identity, normally the primary key. A table without one cannot publish updates.
  • Conflicts stop the stream. A unique violation on the subscriber halts the apply worker until you fix the row or skip the transaction (ALTER SUBSCRIPTION ... SKIP (lsn = ...)). disable_on_error makes it stop cleanly instead of retrying forever.
  • Slots and failover. Until Postgres 17 a logical slot lived only on the primary, so after a failover the subscriber had nowhere to resume. Postgres 17 adds failover slots: create the subscription with failover = true, set sync_replication_slots = on on the physical standby, and list it in synchronized_standby_slots on the primary so logical consumers never get ahead of it.

A logical slot also pins catalog_xmin, so a stalled subscriber holds back vacuum of the system catalogues as well as WAL. The same monitoring query covers it.

physical streaming logical
unit WAL page changes row changes
scope whole cluster chosen tables, columns, rows
versions same major version across major versions
target read-only standby writable server, other systems
DDL, sequences yes, everything no
use for HA, read scaling, PITR base upgrades, migrations, CDC, partial copies

The lab stack

The lab adds labs/databases/replication.yaml, a compose override on top of the shop. It restarts db with wal_level=logical and an hba_file that permits replication connections, and adds replica1 (port 5442) and replica2 (port 5443), which clone the primary with pg_basebackup -X stream -R -C -S <name> on first start, so each has a slot named after itself and cluster_name set to its own name. A fourth service, subscriber (port 5444), is a plain empty Postgres for the logical step. Setting COMPOSE_FILE=compose.yaml:replication.yaml makes every docker compose command in the shell see both files.

LAB Lag, lose a commit, then pay for it ~60 MIN
YOU NEEDthe labs/databases stack from docs/LABS.md, loaded at scale 0.1 (scale 1 works and makes lag easier to see)about 2 GB of free RAM and 1 GB of disk for the replicastwo terminals in labs/databases with COMPOSE_FILE exported in both

In each terminal:

cd labs/databases
export COMPOSE_FILE=compose.yaml:replication.yaml

P> below means a psql on the primary (docker compose exec db psql -U atlas shop), R1> and R2> on the replicas (docker compose exec replica1 psql -U atlas shop, same for replica2), and S> on the subscriber.

1. Start the replicas and read the stream.

docker compose up -d
docker compose ps
docker compose logs replica1 | tail -5
P> SELECT application_name, state, sync_state, sent_lsn, replay_lsn, replay_lag FROM pg_stat_replication;
P> SELECT slot_name, slot_type, active, wal_status FROM pg_replication_slots;
R1> SELECT pg_is_in_recovery(), pg_last_wal_replay_lsn();
R1> UPDATE inventory SET on_hand = 0 WHERE product_id = 1;
db is recreated (its command changed) and comes back with the same data. The replica logs show cloning the primary, then started streaming WAL from primary at 0/... on timeline 1. On the primary, two rows with state = streaming, sync_state = async, and sent_lsn equal to replay_lsn; replay_lag is NULL because nothing is happening. Two physical slots, both active, wal_status = reserved. The replica says t for recovery, reports an LSN equal to the primary’s, and refuses the update with cannot execute UPDATE in a read-only transaction.

2. Measure lag under write load.

In terminal 2, create pgbench’s tables in the shop database and run a 60-second write load:

docker compose exec db pgbench -U atlas -i -s 10 shop
docker compose exec db pgbench -U atlas -c 8 -j 4 -T 60 -N -P 10 shop

In terminal 1, while it runs:

P> SELECT application_name,
          pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind,
          write_lag, flush_lag, replay_lag
   FROM pg_stat_replication \watch 2
behind hovers between a few kB and a few hundred kB, and the three lag columns read well under a millisecond to a few milliseconds, with replay_lag the largest. pgbench reports a few thousand tps. This is the healthy case: same host, no network distance, a replica with nothing else to do. Note the numbers; step 3 makes them grow. Stop the \watch with Ctrl-C.

3. Stop replay and read stale data.

R1> SELECT pg_wal_replay_pause();
P>  UPDATE inventory SET on_hand = 4242 WHERE product_id = 7 RETURNING pg_current_wal_lsn() AS token;
R1> SELECT on_hand, pg_last_wal_replay_lsn() FROM inventory WHERE product_id = 7;
R2> SELECT on_hand, pg_last_wal_replay_lsn() FROM inventory WHERE product_id = 7;
P>  SELECT application_name, pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn)) AS behind,
           write_lag, flush_lag, replay_lag FROM pg_stat_replication;

Now apply the token check from the simulation, with your token in place of the one below:

R1> SELECT pg_last_wal_replay_lsn() >= '0/1A2B3C4D'::pg_lsn AS caught_up;
R1> SELECT pg_wal_replay_resume();
R1> SELECT on_hand FROM inventory WHERE product_id = 7;
R1 returns the old on_hand and R2 returns 4242: two replicas, two answers, both without error. On the primary, replica1’s behind grows while its write_lag and flush_lag stay tiny, because the WAL is arriving and being flushed; only replay has stopped. caught_up is f, so a router would send this client to the primary. After resume, R1 returns 4242 within milliseconds. Paused replay is the extreme case of a replica busy replaying a large transaction or blocked by a query conflict.

4. Let a slot fill the disk, then cap it.

docker compose stop replica2
docker compose exec db pgbench -U atlas -c 8 -j 4 -T 30 -N shop > /dev/null
P> SELECT slot_name, active, wal_status, pg_size_pretty(safe_wal_size) AS safe,
          pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
   FROM pg_replication_slots;
P> ALTER SYSTEM SET max_slot_wal_keep_size = '64MB';
P> SELECT pg_reload_conf();
P> CHECKPOINT;
P> SELECT slot_name, active, wal_status FROM pg_replication_slots;
docker compose start replica2
sleep 5; docker compose logs replica2 --since 1m | grep -iE "removed|error" | head -3
With replica2 stopped, its slot is active = f and retained grows by tens to a few hundred MB in 30 seconds; safe is NULL because nothing caps it. Every one of those bytes stays in pg_wal until replica2 returns. After the cap and a checkpoint, the slot’s wal_status becomes lost (if retained was under 64 MB, run the pgbench line again and repeat the checkpoint). The restarted replica2 logs an error that it can no longer get changes from its invalidated slot, or that the requested WAL segment ... has already been removed, and can never catch up: the GitLab failure, chosen deliberately this time. The primary is safe; the replica must be rebuilt.

Rebuild it and remove the cap:

docker compose rm -sf replica2 && docker volume rm databases_replica2-data && docker compose up -d replica2
docker compose exec db psql -U atlas shop -c "ALTER SYSTEM RESET max_slot_wal_keep_size" -c "SELECT pg_reload_conf()"

5. Pay for synchronous replication.

P> ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica1, replica2)';
P> SELECT pg_reload_conf();
P> SELECT application_name, sync_state FROM pg_stat_replication;
for sc in local on remote_apply; do
  echo "synchronous_commit=$sc"
  docker compose exec -e PGOPTIONS="-c synchronous_commit=$sc" db \
    pgbench -U atlas -c 8 -j 4 -T 20 -N shop | grep -E "^tps|latency average"
done

Now take both synchronous standbys away and commit:

docker compose pause replica1 replica2
P> UPDATE inventory SET on_hand = 9999 WHERE product_id = 8;

Wait five seconds, press Ctrl-C, then:

P> SELECT on_hand FROM inventory WHERE product_id = 8;
docker compose unpause replica1 replica2
docker compose exec db psql -U atlas shop -c "ALTER SYSTEM RESET synchronous_standby_names" -c "SELECT pg_reload_conf()"
docker compose exec db pgbench -U atlas -i -I d shop     # drop pgbench's tables
Both standbys show sync_state = quorum. local matches the async numbers from step 2; on adds a fraction of a millisecond to the average latency here, and remote_apply a little more, with tps falling by roughly 10 to 40%. On a real network each step adds the round trip, so cross-zone multiply the gap by ten and cross-region by a hundred. With both standbys paused, the UPDATE hangs. Ctrl-C prints canceling wait for synchronous replication due to user request and The transaction has already committed locally, but might not have been replicated to the standby. The SELECT returns 9999: your client saw an error for a write that happened.

6. Logical replication, and the DDL it does not carry.

P> CREATE PUBLICATION inv_pub FOR TABLE inventory;
S> CREATE TABLE inventory (product_id bigint PRIMARY KEY, on_hand int NOT NULL, updated_at timestamptz NOT NULL DEFAULT now());
S> CREATE SUBSCRIPTION inv_sub CONNECTION 'host=db dbname=shop user=atlas password=atlas' PUBLICATION inv_pub;
S> SELECT count(*), sum(on_hand) FROM inventory;
P> SELECT count(*), sum(on_hand) FROM inventory;
P> SELECT slot_name, slot_type, active FROM pg_replication_slots;
P> ALTER TABLE inventory ADD COLUMN warehouse text NOT NULL DEFAULT 'BER';
P> UPDATE inventory SET on_hand = on_hand + 1 WHERE product_id = 1;
sleep 3; docker compose logs subscriber --since 1m | grep -i "missing" | head -2

Fix it on the subscriber, then clean up:

S> ALTER TABLE inventory ADD COLUMN warehouse text;
S> SELECT on_hand, warehouse FROM inventory WHERE product_id = 1;
S> DROP SUBSCRIPTION inv_sub;
P> DROP PUBLICATION inv_pub;
P> ALTER TABLE inventory DROP COLUMN warehouse;
The initial copy gives identical counts and sums on both sides (5000 rows at scale 0.1). The primary now has a third slot, inv_sub, of type logical. The subscriber is not a standby: you created its table by hand. After the ALTER on the primary, the subscriber’s log repeats an error that the logical replication target relation public.inventory is missing a replicated column, warehouse, because DDL does not travel. Adding the column on the subscriber lets the apply worker continue and the updated row arrives. DROP SUBSCRIPTION also drops the slot on the publisher; forgetting that step on a real migration leaves a slot holding WAL.

7. Lose an acknowledged commit.

Cut both replicas off the network, commit on the primary, and kill it:

docker network disconnect databases_default databases-replica1-1
docker network disconnect databases_default databases-replica2-1
docker compose exec db psql -U atlas shop -c "UPDATE inventory SET on_hand = 1111 WHERE product_id = 3 RETURNING product_id, on_hand"
docker compose kill db
docker network connect databases_default databases-replica1-1
docker network connect databases_default databases-replica2-1
docker compose exec replica1 psql -U atlas shop -c "SELECT pg_promote()" -c "SELECT pg_is_in_recovery()" \
  -c "SELECT product_id, on_hand FROM inventory WHERE product_id = 3"
The UPDATE returns 3 | 1111 and UPDATE 1: the client has its acknowledgement. After promotion, replica1 reports pg_is_in_recovery = f, and product 3 has its old value. The commit is durable, on the disk of a primary you have abandoned. If you now ran docker compose start db, you would have two writable primaries with different histories, which is where the next chapter starts.

Reset the replicas (the shop data in db is kept, including the 1111):

docker compose rm -sf replica1 replica2 subscriber
docker volume rm databases_replica1-data databases_replica2-data databases_subscriber-data
docker compose up -d
Make the replica fight replay. On R1, BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT count(*) FROM orders; SELECT pg_sleep(120);. On the primary, UPDATE orders SET status = status WHERE id <= 20000; VACUUM orders;. About 30 seconds later R1’s sleep is cancelled with canceling statement due to conflict with recovery and User query might have needed to see row versions that must be removed, and SELECT confl_snapshot FROM pg_stat_database_conflicts WHERE datname = 'shop' on R1 counts it. Now ALTER SYSTEM SET hot_standby_feedback = on; SELECT pg_reload_conf(); on R1 and repeat: the query survives, and on the primary SELECT backend_xmin FROM pg_stat_replication shows the replica’s snapshot pinning vacuum, while VACUUM VERBOSE orders reports dead row versions it cannot remove yet. You chose between cancelled queries and primary bloat; there is no third option on one replica. Finish by removing the replicas and their slots: an inactive slot left on the shop would hold WAL on its disk through every later chapter. docker compose rm -sf replica1 replica2 subscriber, then docker compose exec db psql -U atlas shop -c "SELECT pg_drop_replication_slot(slot_name) FROM pg_replication_slots" (it should return two rows, replica1 and replica2), docker volume rm databases_replica1-data databases_replica2-data databases_subscriber-data, unset COMPOSE_FILE and docker compose up -d, which recreates db with its default command (wal_level = replica, the image’s own pg_hba.conf). Do not use down -v: it would also delete the shop volume. The consistency chapter brings replica1 back from this same file.
DECIDE

The shop's payments database runs on one Postgres primary in eu-central-1 with one async replica in another availability zone. A promotion after a host failure last month lost 1.4 seconds of captured payments that the provider had already charged; finance reconciled them by hand over two days. Commit latency today is 2 ms at p50 and the checkout budget allows 10 ms. Leadership asks for 'no lost payments'. What do you change?

READING
  1. BOOK
    Designing Data-Intensive Applications, chapter 5: Replication Martin Kleppmann, 2017

    Leaders and followers, sync versus async, replication lag and the read-your-writes and monotonic-reads guarantees, in the vocabulary this chapter uses. The multi-leader and leaderless sections are background for later chapters. Read: chapter 5, sections 'Leaders and Followers' and 'Problems with Replication Lag'.

  2. DOC
    PostgreSQL 17: High Availability, Load Balancing, and Replication

    The official account of log shipping, streaming, slots, synchronous replication and hot standby conflicts. Section 26.2 on streaming replication and 26.4 on hot standby are what you will reread in an incident.

  3. DOC
    PostgreSQL 17: Replication settings

    Every knob in this chapter with its default and reload behaviour: synchronous_standby_names syntax, max_slot_wal_keep_size, hot_standby_feedback, max_standby_streaming_delay, sync_replication_slots.

  4. DOC
    PostgreSQL 17: Logical Replication

    Publications, subscriptions, row filters, conflicts and the restrictions list (DDL, sequences, large objects). Read the Restrictions and Conflicts sections before planning an upgrade with it.

  5. POST
    Postmortem of database outage of January 31 GitLab, 2017

    The incident in the Why, told by the team. Read the timeline for the replication part: lag, removed WAL, the failed resync, and how many safety nets were silently not working.

  6. PAPER
    Spanner, TrueTime and the CAP theorem Eric Brewer, 2017

    A short paper on what synchronous replication over a quorum buys and what a partition still costs, from the author of CAP. It frames the availability trade you make with synchronous_standby_names. Read: the whole paper; it is six pages.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Failover, split brain and fencing →