Skip to content

PostgreSQL logical replication in depth

Operate PostgreSQL logical replication beyond the basics — publication filters, conflict handling, replication slots, and the failure modes you only see in production.

PostgreSQL logical replication ships row changes for selected tables from a publisher to one or more subscribers using the WAL as the source of truth. It enables selective sync, cross-major-version upgrades, and zero-downtime moves between hosts — but it also has sharp edges around replication slots, DDL, and conflict handling that physical replication doesn’t. This article is the operator-level walkthrough: what’s actually on the wire, what fails first, and how we keep it healthy in long-running engagements.

How to verify

Start at the publisher and confirm the protocol is running:

psql -c "SHOW wal_level;"               # must be 'logical'
psql -c "SELECT * FROM pg_publication;"
psql -c "SELECT slot_name, plugin, active, restart_lsn,
                pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn))
         FROM pg_replication_slots;"
psql -c "SELECT * FROM pg_stat_replication;"

On the subscriber:

psql -c "SELECT * FROM pg_subscription;"
psql -c "SELECT subname, received_lsn, latest_end_lsn,
                latest_end_time FROM pg_stat_subscription;"

If restart_lsn is moving backwards-from-the-head — meaning the gap between current WAL position and restart_lsn is growing — the slot is holding WAL the publisher cannot recycle. That is the first failure mode to watch.

What’s happening

Logical replication uses the same WAL stream as physical replication but with a decoding plugin (pgoutput for native, wal2json and others for CDC pipelines). When you create a PUBLICATION, you tell Postgres which tables and which operations (INSERT, UPDATE, DELETE, TRUNCATE) to publish. When a SUBSCRIPTION connects, Postgres creates a replication slot on the publisher and starts streaming logical changes — row-level, schema-aware, in commit order.

The subscriber applies changes via background worker processes (logical replication worker). Each subscription gets one apply worker per table during initial sync (configurable, parallel since PG 16), then one apply worker for streaming. Conflicts (a unique-key collision, a missing row to UPDATE) stop the worker and require manual resolution — ALTER SUBSCRIPTION ... SKIP (lsn = ...) or fixing the offending row by hand.

The slot is the dangerous part. It anchors WAL retention on the publisher: if a subscriber is down or far behind, WAL files pile up until the disk fills. Set max_slot_wal_keep_size (PG 13+) to cap the damage — once a slot exceeds that, Postgres invalidates it and the subscriber must be reseeded.

The procedure

  1. Prepare the publisher. Set wal_level = logical, max_replication_slots, max_wal_senders high enough for every subscription plus headroom (we use 20/20 as a baseline), and max_slot_wal_keep_size = '32GB' (or whatever your retention budget allows). Restart.

  2. Create the publication with explicit table list and row filters (PG 15+):

    CREATE PUBLICATION pub_app FOR TABLE
      accounts,
      orders WHERE (region = 'us-east'),
      events WITH (publish_via_partition_root = true);

    publish_via_partition_root makes a partitioned table replicate as the parent — useful when the subscriber’s layout differs.

  3. Replica identity matters. For UPDATE and DELETE, the publisher needs to identify the old row. The default REPLICA IDENTITY is the primary key; tables without one need REPLICA IDENTITY FULL (sends every column, expensive) or REPLICA IDENTITY USING INDEX <unique-idx>. Verify with \d+ <table> — if it says “Replica Identity: nothing”, deletes will fail.

  4. Create the subscriber side:

    CREATE SUBSCRIPTION sub_app
      CONNECTION 'host=pub.internal port=5432 dbname=app user=replicator password=...'
      PUBLICATION pub_app
      WITH (copy_data = true, create_slot = true, slot_name = 'sub_app',
            streaming = 'parallel', binary = true);

    streaming = 'parallel' (PG 16) lets large transactions stream before commit; binary = true skips text conversion when versions match.

  5. Monitor lag, not just connection state. Lag in bytes (pg_wal_lsn_diff) is the metric — connected subscribers can still fall hours behind under write spikes. Alert on a 5-minute moving average of WAL lag past your threshold, and on slot growth past 5 GB.

  6. DDL is not replicated. Schema changes must be applied to publisher first, subscriber afterwards (for additive changes like new columns) or simultaneously via an orchestration step. The pattern is: add column on both with the same default, deploy app, then drop the default on the publisher. Reverse for removals.

Common pitfalls

  • A subscriber that disconnects for hours holds the slot — WAL piles up on the publisher’s pg_wal. Always set max_slot_wal_keep_size and alert on slot age.
  • Initial copy is single-transaction per table; a 500 GB table will hold a transaction for hours. Use copy_data = false plus an external dump/restore for large tables, then ALTER SUBSCRIPTION ... REFRESH PUBLICATION.
  • Sequences are not replicated — SERIAL and IDENTITY columns drift. Restore them at cutover or use external coordination.
  • TRUNCATE replicates by default and cascades to subscriber children; the publication option WITH (publish = 'insert, update, delete') disables it.
  • A unique-key conflict stops the apply worker; pg_stat_subscription_stats (PG 15+) tracks apply errors so you can alert before the lag explodes.

For larger CDC pipelines that ship JSON to warehouses, see wal2json CDC pipelines and logical replication with selective table sync.

In the engagements we run, logical replication is how we do online Postgres major upgrades, how we feed read-only reporting copies, and how we move databases between cloud regions without a downtime window. We monitor slot lag, slot age, and apply errors as first-class signals; we use parallel streaming on PG 16 and max_slot_wal_keep_size everywhere. For the operating model behind a cross-region Postgres footprint, see multi-region environments.