Replication Basics
PostgreSQL supports two main replication models: Physical (Streaming) Replication for high availability and read scaling, and Logical Replication for selective table-level replication and zero-downtime upgrades.
Physical (Streaming) vs Logical Replication#
| Feature | Streaming (Physical) | Logical |
|---|---|---|
| Scope | Entire cluster (byte-for-byte WAL copy) | Selected tables (publications & subscriptions) |
| Standby writes | Read-only | Writable |
| Cross-major version | No (same major version & arch) | Yes |
| DDL replication | Automatic | Manual (DML only) |
wal_level required | replica (default) | logical |
Monitoring streaming replication#
On the primary, check connected standbys and replication lag:
SELECT
client_addr,
application_name,
state,
sync_state,
pg_wal_lsn_diff(pg_current_wal_lsn(), sent_lsn) AS send_lag_bytes,
pg_wal_lsn_diff(sent_lsn, replay_lsn) AS replay_lag_bytes,
replay_lag
FROM pg_stat_replication;
On a standby, verify recovery mode and replay delay:
SELECT
pg_is_in_recovery(),
pg_last_wal_receive_lsn(),
pg_last_wal_replay_lsn(),
now() - pg_last_xact_replay_timestamp() AS replay_delay;Replication slots#
Replication slots ensure the primary retains WAL segments until a standby (or logical subscriber) has consumed them:
SELECT
slot_name,
slot_type,
active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
Watch inactive slots (
active = false)! An abandoned slot holds WAL indefinitely and can fill uppg_wal/and crash the primary. Setmax_slot_wal_keep_sizeinpostgresql.confas a safety cap, or drop unused slots withSELECT pg_drop_replication_slot('slot_name');.
Quick logical replication setup#
On the publisher (wal_level = logical):
CREATE PUBLICATION my_pub FOR TABLE orders, customers;
On the subscriber:
CREATE SUBSCRIPTION my_sub
CONNECTION 'host=primary.example.com port=5432 dbname=mydb user=replicator'
PUBLICATION my_pub;