Replication & High Availability
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
PostgreSQL replicates by shipping its write-ahead log (WAL). Physical replication sends the raw WAL to a standby
that replays it byte for byte, producing an identical copy of the whole cluster. Logical replication decodes the WAL
into row changes that a subscriber applies, which allows partial, cross-version and writable copies. This page runs both
with two Docker containers (pg-b as the primary and pg-b2 as the standby) on PostgreSQL 18.6, using the shop
data from Getting Started. Output is trimmed where stated. For backups
and point-in-time recovery see Backup & Restore, and for the
corresponding MongoDB concepts see Replica Sets & High Availability.
How streaming replication works
Every change is first written to the WAL on the primary. A WAL sender process on the primary streams the records over a replication connection to a WAL receiver process on the standby, which writes them to its own WAL; the startup process then replays them against the standby’s data files. If the standby also allows read-only queries it is called a hot standby (the default on current versions).
The settings that matter on the primary are wal_level (replica is enough for physical replication, logical is
required for logical), max_wal_senders and max_replication_slots. The containers in this page start with
wal_level=logical, so one primary serves both types of subscriber. A standby also needs a role with the REPLICATION
attribute and a matching pg_hba.conf line. The database all in pg_hba.conf does not match replication
connections, so a dedicated replication line is required:
docker network create pgb-net
docker run -d --name pg-b --network pgb-net -e POSTGRES_PASSWORD=secret -p 54322:5432 postgres:latest \
-c wal_level=logical -c max_wal_senders=10 -c max_replication_slots=10 -c hot_standby=on
docker exec pg-b sh -c "echo 'host replication replicator all scram-sha-256' >> /var/lib/postgresql/18/docker/pg_hba.conf"
docker exec pg-b psql -U postgres -c "CREATE ROLE replicator REPLICATION LOGIN PASSWORD 'secret'" -c "select pg_reload_conf()"
After loading the seed into pg-b, pg_hba_file_rules shows the new line last, at line 129:
line_number | type | database | user_name | address | auth_method
-------------+-------+---------------+--------------+-----------+---------------
124 | local | {replication} | {all} | | trust
125 | host | {replication} | {all} | 127.0.0.1 | trust
126 | host | {replication} | {all} | ::1 | trust
129 | host | {replication} | {replicator} | all | scram-sha-256
Building a physical standby
pg_basebackup -R takes a base backup of the primary and writes the standby configuration for you: it creates an empty
standby.signal file (the marker that starts the server as a standby) and puts the connection details in
postgresql.auto.conf. With -C -S standby1 it also creates a physical replication slot named standby1 on the primary.
The standby container runs the backup as its first step, then starts PostgreSQL on the copied directory:
docker run -d --name pg-b2 --network pgb-net --user postgres -p 54323:5432 -e PGPASSWORD=secret postgres:latest \
bash -c "pg_basebackup -h pg-b -U replicator -D /var/lib/postgresql/18/docker -R -X stream -C -S standby1 -c fast -P -v \
&& chmod 700 /var/lib/postgresql/18/docker && exec postgres -D /var/lib/postgresql/18/docker"
The standby’s log shows it entering standby mode and connecting to the primary:
LOG: starting backup recovery with redo LSN 0/2000028, checkpoint LSN 0/2000080, on timeline ID 1 LOG: entering standby mode LOG: consistent recovery state reached at 0/2000120 LOG: database system is ready to accept read-only connections LOG: started streaming WAL from primary at 0/3000000 on timeline 1
and -R wrote these lines (the connection string is shortened here to its first fields):
primary_conninfo = 'user=replicator password=secret channel_binding=prefer host=''pg-b'' port=5432 sslmode=prefer ...' primary_slot_name = 'standby1'
(The file also contains a standby.signal marker in the data directory.) A real deployment replaces the plain password
with a .pgpass entry, a certificate, or sslmode=verify-full.
Checking replication
On the primary, pg_stat_replication has one row per connected standby with the WAL positions it has received
(sent/write/flush) and replayed, plus the three lag intervals:
SELECT pid, usename, application_name, client_addr, state, sent_lsn, write_lsn, flush_lsn, replay_lsn,
sync_state, write_lag, replay_lag
FROM pg_stat_replication;
-[ RECORD 1 ]----+---------------- pid | 98 usename | replicator application_name | walreceiver client_addr | 172.21.0.3 state | streaming sent_lsn | 0/3000060 write_lsn | 0/3000060 flush_lsn | 0/3000060 replay_lsn | 0/3000060 sync_state | async write_lag | 00:00:00.019868 replay_lag | 00:00:00.020226
On the standby, pg_stat_wal_receiver describes the other end of the same connection:
SELECT status, receive_start_lsn, written_lsn, flushed_lsn, latest_end_lsn, sender_host, sender_port, slot_name
FROM pg_stat_wal_receiver;
SELECT pg_is_in_recovery(), pg_last_wal_receive_lsn(), pg_last_wal_replay_lsn();
-[ RECORD 1 ]-----+---------- status | streaming receive_start_lsn | 0/3000000 written_lsn | 0/3000060 flushed_lsn | 0/3000060 latest_end_lsn | 0/3000060 sender_host | pg-b sender_port | 5432 slot_name | standby1 pg_is_in_recovery | pg_last_wal_receive_lsn | pg_last_wal_replay_lsn -------------------+-------------------------+------------------------ t | 0/3000060 | 0/3000060
Hot standby reads
A write on the primary is visible on the standby moments later, and any attempt to write on the standby is refused:
-- on pg-b (primary)
UPDATE shop.products SET stock = stock + 1 WHERE sku='A-1';
-- on pg-b2 (standby)
SELECT sku, stock FROM shop.products WHERE sku='A-1';
UPDATE shop.products SET stock=0;
SHOW transaction_read_only;
sku | stock -----+------- A-1 | 13 ERROR: cannot execute UPDATE in a read-only transaction transaction_read_only ----------------------- on
Read replicas are eventually consistent: a client that writes on the primary and immediately reads from a standby can miss its own write. Measure lag in time on the standby, or in bytes on the primary:
-- standby
SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay; -- 00:00:01.060913 (right after a small update)
-- primary
SELECT pg_wal_lsn_diff(pg_current_wal_lsn(), replay_lsn) AS replay_lag_bytes FROM pg_stat_replication; -- 0
Note that now() - pg_last_xact_replay_timestamp() grows on an idle primary because no transaction has been replayed
recently; it measures staleness, not necessarily a problem. Replay can be paused for inspection with
pg_wal_replay_pause(); pg_get_wal_replay_pause_state() then reports paused until pg_wal_replay_resume().
Long queries on a standby can conflict with replay of cleanup records from the primary. The standby cancels the query
after max_standby_streaming_delay (30 seconds by default). The alternatives are hot_standby_feedback = on (the
standby tells the primary which rows it still needs, at the price of table bloat on the primary), or running reporting
on a dedicated standby with a larger delay. recovery_min_apply_delay deliberately delays replay, a cheap safety net
against operator error.
Replication slots
Without a slot, the primary may recycle WAL that a lagging standby has not yet received, and the standby then has to be rebuilt. A replication slot makes the primary retain WAL until the slot’s consumer has confirmed it:
SELECT slot_name, slot_type, active, restart_lsn, wal_status FROM pg_replication_slots;
slot_name | slot_type | active | restart_lsn | wal_status -----------+-----------+--------+-------------+------------ standby1 | physical | t | 0/3000060 | reserved
The risk is the opposite problem: an abandoned slot retains WAL forever and can fill the disk. After stopping the standby,
the slot showed active = f and the retained amount grew as the primary kept writing:
slot_name | active | restart_lsn | wal_status | retained -----------+--------+-------------+------------+----------- standby1 | f | 0/3000540 | reserved | 248 bytes
Protect the primary by setting max_slot_wal_keep_size (the default -1 means unlimited, as shown by pg_settings),
monitor pg_replication_slots, and drop unused slots with pg_drop_replication_slot('name'). The alternative without
slots is wal_keep_size (default 0), which keeps a fixed amount of WAL, or a WAL archive for the standby to fall back
on (see Backup & Restore).
Synchronous replication
By default replication is asynchronous: the primary acknowledges a commit once its own WAL is flushed, so a crash of the
primary can lose the last few transactions that a standby had not received. Naming a synchronous standby makes the
commit wait for it. The standby is identified by its application_name, which defaults to walreceiver for a
pg_basebackup -R standby:
ALTER SYSTEM SET synchronous_standby_names = 'FIRST 1 (walreceiver)';
SELECT pg_reload_conf();
SELECT application_name, state, sync_state, sync_priority FROM pg_stat_replication;
application_name | state | sync_state | sync_priority ------------------+-----------+------------+--------------- walreceiver | streaming | sync | 1
The trade-off is visible when the standby disappears. After docker stop pg-b2, a write on the primary does not
complete; pg_stat_activity shows the session waiting on SyncRep:
pid | state | wait_event_type | wait_event | left -----+--------+-----------------+------------+------------------------------------------ 137 | active | IPC | SyncRep | UPDATE shop.products SET stock = stock +
A psql run with timeout 5 returned exit code 124 (killed). The transaction was already applied locally and held its
row locks, so other writers to the same row blocked until the standby came back (after docker start pg-b2 the wait cleared
and the update was visible). Synchronous replication therefore trades availability for durability, so production setups
use two or more candidates, FIRST 1 (a, b) or ANY 1 (a, b, c), so that one failure does not stall writers.
synchronous_commit controls how far a commit waits and can be set per transaction:
| Value | Waits until |
|---|---|
|
Nothing is flushed (risk of losing recent commits on a crash, but no corruption) |
|
Local WAL flush only |
|
Standby has written the WAL to its operating system |
|
Standby has flushed the WAL to disk |
|
Standby has applied the change, so a read on it sees the commit |
Switching synchronous_commit to local released the writes while synchronous_standby_names stayed set. Both settings
were then reset with ALTER SYSTEM RESET.
Failover and promotion
Promotion turns a standby into a primary. Either run pg_ctl promote -D <datadir> on the standby host or call the SQL
function from a superuser session:
SELECT pg_promote(wait => true, wait_seconds => 30);
SELECT pg_is_in_recovery();
pg_promote ------------ t pg_is_in_recovery ------------------- f
The log records the timeline switch, which distinguishes WAL written before and after the promotion:
LOG: invalid record length at 0/305B580: expected at least 24, got 0 LOG: redo done at 0/305B550 ... LOG: selected new timeline ID: 2 LOG: archive recovery complete LOG: database system is ready to accept connections
The promoted server accepts writes (an UPDATE of B-7 succeeded and reported stock 250 on the new primary, while the
old primary still showed 150), and its WAL files now begin with 00000002, with a 00000002.history file recording the
fork. That divergence is the danger of failover: the two servers are now independent. The old primary must be fenced
(stopped, or cut from clients) before any write goes to it, otherwise the data splits ("split brain").
To reuse the old primary as a standby, either rebuild it with pg_basebackup or use pg_rewind, which resynchronizes
the diverged data directory by copying only the changed blocks. pg_rewind requires wal_log_hints = on or data
checksums (enabled by default in PostgreSQL 18) and the old primary to have been shut down cleanly. It is described here
and was not run in this example.
Promotion is only half of failover: something has to detect the failure, choose the best standby, fence the old primary, and redirect clients. That coordination is the job of the tools described below.
Logical replication
Logical replication replicates changes to rows rather than blocks. A publication on the source declares which tables
(and optionally which columns and rows) to publish; a subscription on the target connects, copies the existing rows
and then applies new changes. The target is an ordinary writable database, which can be a different major version, hold a
subset of the tables or have extra indexes. The requirements are wal_level = logical on the publisher and a primary
key (or REPLICA IDENTITY) on each published table so updates and deletes can be located.
The demo promotes pg-b2 first (above), then uses it as the subscriber. After dropping the now-pointless physical slot
(SELECT pg_drop_replication_slot('standby1') on the old primary), create a publication on the primary:
CREATE PUBLICATION shop_pub FOR TABLE shop.customers, shop.products, shop.orders, shop.order_items;
SELECT * FROM pg_publication_tables;
pubname | schemaname | tablename | attnames | rowfilter
----------+------------+-------------+--------------------------------------------+-----------
shop_pub | shop | customers | {id,name,email,city,tier,created_at} |
shop_pub | shop | products | {sku,name,category,price,stock,tags,attrs} |
shop_pub | shop | orders | {id,customer_id,status,order_date} |
shop_pub | shop | order_items | {order_id,sku,qty,price} |
Logical replication does not copy the schema, so the subscriber needs the table definitions first. A schema-only dump provides them:
docker exec pg-b sh -c "pg_dump -U postgres -d postgres -n shop --schema-only" > shop_schema.sql
docker exec pg-b2 psql -U postgres -c "CREATE DATABASE shopcopy"
docker exec -i pg-b2 psql -U postgres -d shopcopy -q < shop_schema.sql
CREATE SUBSCRIPTION shop_sub
CONNECTION 'host=pg-b port=5432 dbname=postgres user=replicator password=secret'
PUBLICATION shop_pub;
NOTICE: created replication slot "shop_sub" on publisher CREATE SUBSCRIPTION
The first attempt did not copy any data. The subscriber’s log shows why: the replicator role could connect but had no
privilege on the tables.
ERROR: could not start initial contents copy for table "shop.customers": ERROR: permission denied for schema shop
pg_subscription_rel stayed in state d (data copy). The initial copy runs SELECT as the subscription’s role, so it needs
USAGE on the schema and SELECT on the tables:
GRANT USAGE ON SCHEMA shop TO replicator;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO replicator;
Within seconds every table reached state r (ready), and the row counts match the publisher (4 customers, 11 order lines):
srrelid | srsubstate ------------------+------------ shop.products | r shop.orders | r shop.customers | r shop.order_items | r
Changes made on the publisher now flow to the subscriber:
-- publisher
INSERT INTO shop.customers VALUES ('c-9','Margaret Hamilton','mh@example.com','Boston','pro',now());
UPDATE shop.products SET price = 299.00 WHERE sku='C-9';
DELETE FROM shop.order_items WHERE order_id=1008;
-- subscriber (shopcopy)
SELECT id, name FROM shop.customers ORDER BY id; -- 5 rows, including c-9
SELECT sku, price FROM shop.products WHERE sku='C-9'; -- 299.00
SELECT count(*) FROM shop.order_items; -- 10
The matching monitoring views are pg_replication_slots and pg_stat_replication on the publisher (the subscription
appears as a walsender with application_name = shop_sub) and pg_stat_subscription on the subscriber:
slot_name | plugin | slot_type | database | active | confirmed_flush_lsn -----------+----------+-----------+----------+--------+--------------------- shop_sub | pgoutput | logical | postgres | t | 0/3076860
Because the subscriber is writable, it can conflict with incoming changes. After inserting a row with id = 'c-10' locally on
the subscriber and then inserting a different row with the same key and e-mail on the publisher, the apply worker stops:
ERROR: conflict detected on relation "shop.customers": conflict=multiple_unique_conflicts DETAIL: Key already exists in unique index "customers_email_key", modified in transaction 833. Key (email)=(l@example.com); existing local row (c-10, Local only, ...); remote row (c-10, Different, ...).
The worker restarts and fails repeatedly until the conflict is resolved; pg_stat_subscription_stats counts the failures
(apply_error_count was 2 when sampled). Resolve it by removing or fixing the conflicting local row (here
DELETE FROM shop.customers WHERE id='c-10' on the subscriber, after which the remote row was applied), or by using
ALTER SUBSCRIPTION ... SKIP for a transaction known to be bad. Remember:
-
DDL is not replicated; apply schema changes on both sides, usually subscriber first for additions.
-
Sequences are not replicated; a failover to the subscriber needs sequence values synchronized.
-
Large objects are not replicated, and
TRUNCATEis replicated only if the publication includes it (the default). -
An unused subscription leaves a slot on the publisher; always
DROP SUBSCRIPTION(which drops the slot too, as it did here withNOTICE: dropped replication slot "shop_sub" on publisher).
Typical uses: zero-downtime major-version upgrades, feeding a reporting database with a subset of tables, consolidating several sources, and change data capture, where a tool such as Debezium reads the same logical slot (see Database Migration).
Tools for high availability
PostgreSQL provides the replication and promotion primitives but not an orchestrator. These tools add one; they are described for orientation and were not run here.
-
Patroni keeps cluster state in a distributed store (etcd, Consul or ZooKeeper) and uses it as a leader lock. It starts and stops PostgreSQL, promotes a standby when the leader’s lease expires, reconfigures the other nodes, and exposes a REST API (
/primary,/replica,/health) that load balancers use to find the leader. It is the most widely used HA stack, including in Kubernetes operators. -
repmgr manages standbys and switchover/failover with a monitoring daemon (
repmgrd) and a few commands (repmgr standby clone,repmgr standby promote,repmgr cluster show). It is lighter than Patroni and keeps its state in a PostgreSQL metadata schema. -
pg_auto_failover, cloud-managed services and Kubernetes operators (CloudNativePG, Zalando, Crunchy) package the same ideas.
Whatever the tool, test failover regularly: kill the primary, time how long writes are unavailable, and check that no acknowledged transaction was lost. With asynchronous replication the last transactions can be.
Connection pooling with PgBouncer
Every PostgreSQL connection is a separate server process using several megabytes of memory, so thousands of application connections are better multiplexed over a few dozen server connections by a pooler. PgBouncer is the standard lightweight one. Its pool mode decides when a server connection is returned to the pool:
| Mode | Behaviour |
|---|---|
|
Server connection held for the whole client session; safest, least multiplexing |
|
Held only during a transaction; best utilisation, but session state ( |
|
Returned after each statement; multi-statement transactions are not allowed |
A minimal configuration (shown as configuration and not executed here) routes writes to the primary and reads to a standby through two database aliases:
[databases]
shop = host=pg-b port=5432 dbname=postgres
shop_ro = host=pg-b2 port=5432 dbname=postgres
[pgbouncer]
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 20
Applications then connect to port 6432. Size default_pool_size against max_connections and the core count rather
than the number of clients; see Performance Tuning. In transaction mode,
use a PgBouncer version that supports protocol-level prepared statements, or disable client-side prepared statements.
Other poolers include Pgpool-II (which can also load-balance and parse queries) and PgCat.
Read replicas in practice
-
Route read-only, staleness-tolerant queries (dashboards, search pages, exports) to standbys. Keep read-your-own-writes traffic on the primary, or use
synchronous_commit = remote_applyfor the transactions that need it. -
Monitor lag in both bytes and time; alert when a standby falls behind by more than your tolerance, and on inactive slots.
-
Standbys can be cascaded: a standby with
primary_conninfopointing to another standby spares the primary the fan-out. -
Remember a replica is not a backup: a
DROP TABLEreplicates at once. Keep archived backups as in Backup & Restore.