AdvancedAdvanced PostgreSQL

Logical replication subscription setup

The query

SQL
-- On PRIMARY server:
CREATE PUBLICATION pub_employees FOR TABLE employees, departments;

-- On REPLICA server:
CREATE SUBSCRIPTION sub_employees
  CONNECTION 'host=primary_host dbname=mydb user=replication_user password=secret'
  PUBLICATION pub_employees;

-- Monitor replication lag
SELECT
  application_name,
  client_addr,
  state,
  PG_WAL_LSN_DIFF(sent_lsn, replay_lsn) AS replication_lag_bytes
FROM pg_stat_replication;
Tested against PostgreSQL 16

Note

Logical replication replicates specific tables. Physical replication copies entire WAL stream.

Tables referenced