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#

FeatureStreaming (Physical)Logical
ScopeEntire cluster (byte-for-byte WAL copy)Selected tables (publications & subscriptions)
Standby writesRead-onlyWritable
Cross-major versionNo (same major version & arch)Yes
DDL replicationAutomaticManual (DML only)
wal_level requiredreplica (default)logical
Interactive Streaming Replication & Replication Slots
PRIMARY (READ / WRITE) STANDBY (READ-ONLY) Primary pg_wal/ + Slot LSN 0/2000100 slot: active=true · retained: 16 MB walsender ready to stream state: streaming Standby Data + Startup replayed: 0/2000000 pg_is_in_recovery() = true walreceiver connected flush_lsn: 0/2000000

pg_stat_replication / Slots

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 up pg_wal/ and crash the primary. Set max_slot_wal_keep_size in postgresql.conf as a safety cap, or drop unused slots with SELECT 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;