Skip to content

Deploying PostgreSQL logical replication for selective table sync across two clusters

Use publications and subscriptions to ship a subset of tables from one Postgres cluster to another — different versions, different filtering, no full-cluster mirroring.

You run a primary OLTP cluster for an e-commerce application. The analytics team wants a near-real-time read replica of orders, order_items, customers, and products — but explicitly not the audit-log table that doubles the cluster’s write volume, and explicitly not the session-store schema that gets vacuumed aggressively and would be useless on a reporting box. Streaming replication would ship everything or nothing. Logical replication is exactly the tool: you publish a set of tables on the source, subscribe to them on the target, and the target can be a different major version, a different machine class, or even a database with additional reporting-side tables that don’t exist on the source. This article shows the install, the gotchas (primary keys, schema drift, initial copy memory), and the verification queries that catch silent divergence before the reporting team notices.

What’s happening

Logical replication in Postgres works on a publication/subscription model. On the source, you create a publication that names the tables (and optionally the operations: insert, update, delete, truncate) that will be replicated. The source generates logical WAL records — decoded by the pgoutput plugin into row-level changes — and ships them over a replication connection. On the target, you create a subscription that connects to the source as a replication user, names the publication, and either runs an initial table copy (copy_data = true) or assumes the data already matches (copy_data = false, for cutover scenarios).

The model has properties streaming replication doesn’t:

  • Selective tables. You replicate orders and not audit_log. The source only spends WAL-decoding work on tables in the publication.
  • Cross-version. Source can be Postgres 14, target Postgres 16. Logical decoding deliberately abstracts the on-disk format.
  • Schema drift is your problem. Logical replication does not replicate DDL. If you ALTER TABLE orders ADD COLUMN foo TEXT on the source, the target subscription will error and stop replicating that table until you make the same change on the target. The shop convention: schema changes are deployed to target first, source second.
  • Every replicated table must have a primary key (or REPLICA IDENTITY FULL, which is expensive on wide tables — usually a sign you should add a primary key).
  • Initial copy is a COPY, not a pg_basebackup. Big tables can take hours and hold long-running transactions on the source. For tables over ~100 GB, consider copy_data = false and pre-seeding with pg_dump --data-only --table=....

Logical replication also doesn’t replicate sequences. If your target needs to write to the same tables (a writable replica), you need to handle sequence advancement separately. For analytics-only targets — read-only — sequences don’t matter, so the constraint mostly vanishes.

How to verify

From the source, confirm the publication exists and lists the right tables:

SELECT pubname, puballtables, pubinsert, pubupdate, pubdelete, pubtruncate
FROM pg_publication WHERE pubname = 'analytics_pub';

SELECT schemaname, tablename
FROM pg_publication_tables WHERE pubname = 'analytics_pub'
ORDER BY tablename;

From the source, watch the replication slot the subscription created — confirmed_flush_lsn should advance under writes:

SELECT slot_name, plugin, slot_type, active, restart_lsn, confirmed_flush_lsn,
       pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn) AS lag_bytes
FROM pg_replication_slots
WHERE slot_type = 'logical';

From the target, the subscription state:

SELECT subname, subenabled, subconninfo, subpublications,
       (SELECT status FROM pg_stat_subscription WHERE subname = s.subname) AS status
FROM pg_subscription s;

SELECT subname, received_lsn, latest_end_lsn,
       extract(epoch from now() - latest_end_time)::int AS seconds_behind
FROM pg_stat_subscription;

A simple row-count diff catches the most common divergence (a row inserted on the source that the subscription dropped because the target schema rejected it):

-- on source
SELECT 'orders' AS t, count(*) FROM orders
UNION ALL SELECT 'customers', count(*) FROM customers;
-- on target — run the same and diff

For a more rigorous check, use pg_dump --schema-only on both sides and diff the output. Schema drift is the #1 silent breakage.

The fix

This installer assumes the source and target Postgres 16 instances already exist on Ubuntu 22.04 (you can use the streaming-replication installer in the companion article to bring up each one as a single-node first). The script edits postgresql.conf on both sides to enable wal_level=logical, creates the publication on the source, creates the subscription on the target, runs verification queries, and writes a /root/RUNBOOK-schema-drift.md for the operations team.

#!/usr/bin/env bash
set -euo pipefail

### Postgres 16 logical replication setup
### Run on the COORDINATOR machine that has psql + reachability to both clusters
### Edit SOURCE_* and TARGET_* below

if [[ -z "${PGCLIENT:-}" ]]; then
  PGCLIENT="psql"
fi

# === EDIT ===
SOURCE_HOST="10.30.0.11"
SOURCE_PORT=5432
SOURCE_DB="shop"
SOURCE_SUPERUSER="postgres"
SOURCE_SUPERUSER_PASSWORD="CHANGE_ME"
REPL_USER="logical_replicator"
REPL_PASSWORD="CHANGE_ME_LOGICAL"

TARGET_HOST="10.30.0.21"
TARGET_PORT=5432
TARGET_DB="shop_analytics"
TARGET_SUPERUSER="postgres"
TARGET_SUPERUSER_PASSWORD="CHANGE_ME"

PUB_NAME="analytics_pub"
SUB_NAME="analytics_sub"
TABLES=("orders" "order_items" "customers" "products")
PRIVATE_SUBNET="10.30.0.0/16"
# ============

echo
echo "========================================"
echo "Logical replication: ${SOURCE_HOST}/${SOURCE_DB} -> ${TARGET_HOST}/${TARGET_DB}"
echo "Publication: ${PUB_NAME}"
echo "Tables: ${TABLES[*]}"
echo "========================================"
echo

run_source() {
  PGPASSWORD="${SOURCE_SUPERUSER_PASSWORD}" \
    ${PGCLIENT} -h "${SOURCE_HOST}" -p "${SOURCE_PORT}" \
                -U "${SOURCE_SUPERUSER}" -d "${SOURCE_DB}" \
                -v ON_ERROR_STOP=1 -X -A -t -c "$1"
}
run_target() {
  PGPASSWORD="${TARGET_SUPERUSER_PASSWORD}" \
    ${PGCLIENT} -h "${TARGET_HOST}" -p "${TARGET_PORT}" \
                -U "${TARGET_SUPERUSER}" -d "${TARGET_DB}" \
                -v ON_ERROR_STOP=1 -X -A -t -c "$1"
}

echo "==> Confirming connectivity"
run_source "SELECT version();"
run_target "SELECT version();"

echo "==> Source: ensure wal_level=logical"
WAL_LEVEL=$(run_source "SHOW wal_level;")
if [[ "${WAL_LEVEL}" != "logical" ]]; then
  echo "    Setting wal_level=logical and other params (requires restart)"
  run_source "ALTER SYSTEM SET wal_level = 'logical';"
  run_source "ALTER SYSTEM SET max_replication_slots = 10;"
  run_source "ALTER SYSTEM SET max_wal_senders = 10;"
  run_source "ALTER SYSTEM SET max_logical_replication_workers = 8;"
  run_source "ALTER SYSTEM SET max_worker_processes = 16;"
  echo "    *** RESTART the source cluster now, then re-run this script ***"
  echo "    On source host: sudo systemctl restart postgresql@16-main"
  exit 2
fi

echo "==> Target: ensure subscription-side params"
run_target "ALTER SYSTEM SET max_logical_replication_workers = 8;"
run_target "ALTER SYSTEM SET max_worker_processes = 16;"
run_target "ALTER SYSTEM SET max_sync_workers_per_subscription = 4;"

echo "==> Source: create replication role if missing"
HAS_ROLE=$(run_source "SELECT 1 FROM pg_roles WHERE rolname='${REPL_USER}';")
if [[ "${HAS_ROLE}" != "1" ]]; then
  run_source "CREATE ROLE ${REPL_USER} WITH REPLICATION LOGIN PASSWORD '${REPL_PASSWORD}';"
fi
# grant read on every published table + the schema they live in
for t in "${TABLES[@]}"; do
  run_source "GRANT USAGE ON SCHEMA public TO ${REPL_USER};"
  run_source "GRANT SELECT ON public.${t} TO ${REPL_USER};"
done

echo "==> Source: confirm every replicated table has a primary key"
for t in "${TABLES[@]}"; do
  HAS_PK=$(run_source "SELECT 1 FROM pg_constraint c
                       JOIN pg_class r ON r.oid = c.conrelid
                       WHERE c.contype='p' AND r.relname='${t}';")
  if [[ "${HAS_PK}" != "1" ]]; then
    echo "    ERROR: table ${t} has no primary key."
    echo "    Logical replication needs PK or REPLICA IDENTITY FULL."
    echo "    Add a PK, or run: ALTER TABLE ${t} REPLICA IDENTITY FULL;"
    exit 3
  fi
done

echo "==> Source: (re)create publication ${PUB_NAME}"
run_source "DROP PUBLICATION IF EXISTS ${PUB_NAME};"
TABLE_LIST=$(printf ", public.%s" "${TABLES[@]}")
TABLE_LIST="${TABLE_LIST:2}"
run_source "CREATE PUBLICATION ${PUB_NAME} FOR TABLE ${TABLE_LIST};"
run_source "SELECT pubname, puballtables FROM pg_publication WHERE pubname='${PUB_NAME}';"

echo "==> Target: prepare schema (DDL is NOT replicated)"
echo "    Dumping table DDL from source, applying on target"
for t in "${TABLES[@]}"; do
  # we pull schema-only via pg_dump and replay it on target
  PGPASSWORD="${SOURCE_SUPERUSER_PASSWORD}" \
    pg_dump -h "${SOURCE_HOST}" -p "${SOURCE_PORT}" \
            -U "${SOURCE_SUPERUSER}" -d "${SOURCE_DB}" \
            --schema-only --no-owner --no-privileges \
            --table="public.${t}" \
    | PGPASSWORD="${TARGET_SUPERUSER_PASSWORD}" \
        ${PGCLIENT} -h "${TARGET_HOST}" -p "${TARGET_PORT}" \
                    -U "${TARGET_SUPERUSER}" -d "${TARGET_DB}" \
                    -v ON_ERROR_STOP=1 -X
done

echo "==> Target: drop subscription if exists, then create"
HAS_SUB=$(run_target "SELECT 1 FROM pg_subscription WHERE subname='${SUB_NAME}';")
if [[ "${HAS_SUB}" == "1" ]]; then
  echo "    Disabling + dropping old subscription"
  run_target "ALTER SUBSCRIPTION ${SUB_NAME} DISABLE;"
  run_target "ALTER SUBSCRIPTION ${SUB_NAME} SET (slot_name = NONE);"
  run_target "DROP SUBSCRIPTION ${SUB_NAME};"
fi

CONNINFO="host=${SOURCE_HOST} port=${SOURCE_PORT} dbname=${SOURCE_DB} user=${REPL_USER} password=${REPL_PASSWORD} sslmode=prefer"
run_target "CREATE SUBSCRIPTION ${SUB_NAME}
            CONNECTION '${CONNINFO}'
            PUBLICATION ${PUB_NAME}
            WITH (copy_data = true, create_slot = true, slot_name = '${SUB_NAME}_slot', enabled = true, streaming = on);"

echo "==> Waiting for initial table sync (up to 30 minutes)"
DEADLINE=$(( $(date +%s) + 1800 ))
while true; do
  REMAINING=$(run_target "SELECT count(*) FROM pg_subscription_rel
                          WHERE srsubstate <> 'r';")
  if [[ "${REMAINING}" == "0" ]]; then
    echo "    All tables in 'ready' state."
    break
  fi
  if [[ $(date +%s) -gt ${DEADLINE} ]]; then
    echo "    TIMEOUT — ${REMAINING} tables still syncing. Investigate:"
    run_target "SELECT srrelid::regclass, srsubstate FROM pg_subscription_rel WHERE srsubstate <> 'r';"
    exit 4
  fi
  echo "    ${REMAINING} table(s) still syncing..."
  sleep 10
done

echo "==> Row-count parity (informational; updates may be in-flight)"
for t in "${TABLES[@]}"; do
  SRC=$(run_source "SELECT count(*) FROM public.${t};")
  TGT=$(run_target "SELECT count(*) FROM public.${t};")
  printf "    %-20s source=%-10s target=%-10s\n" "${t}" "${SRC}" "${TGT}"
done

echo "==> Writing /root/RUNBOOK-schema-drift.md"
cat > /root/RUNBOOK-schema-drift.md <<RUNBOOK
# Schema drift runbook (logical replication)

Publication: ${PUB_NAME} on ${SOURCE_HOST}/${SOURCE_DB}
Subscription: ${SUB_NAME} on ${TARGET_HOST}/${TARGET_DB}
Tables: ${TABLES[*]}

## When deploying a schema change to any replicated table

ORDER MATTERS. Apply DDL on the TARGET first, then the SOURCE.

For backward-compatible changes (ADD COLUMN nullable / with default,
ADD INDEX, NEW TABLE later added to publication):
1. Apply DDL on target.
2. Apply DDL on source.
3. If a new table is added: ALTER PUBLICATION ${PUB_NAME} ADD TABLE public.<t>;
   then on target: ALTER SUBSCRIPTION ${SUB_NAME} REFRESH PUBLICATION;

For breaking changes (DROP COLUMN, type narrow, NOT NULL on existing column):
- Plan a maintenance window.
- Pause writes to the affected table on the source.
- Wait for subscription to drain (latest_end_lsn caught up).
- DROP COLUMN / change type on target first.
- DROP COLUMN / change type on source.
- Resume writes.

## When the subscription errors and stops

Symptom: pg_stat_subscription.received_lsn stops advancing, the
postgres log on the target says "ERROR: relation public.X does not exist"
or "logical replication target relation public.X is missing some replicated columns".

1. Identify the offending table in target logs.
2. Apply the missing DDL on target.
3. The worker restarts on its own within seconds.
4. Verify pg_stat_subscription advances.

## Add a new table to the publication

On source:
  ALTER PUBLICATION ${PUB_NAME} ADD TABLE public.<new_table>;
On target:
  -- create the table (schema-only pg_dump --table)
  ALTER SUBSCRIPTION ${SUB_NAME} REFRESH PUBLICATION;

## Remove a table from the publication

On source:
  ALTER PUBLICATION ${PUB_NAME} DROP TABLE public.<table>;
On target (optional cleanup):
  ALTER SUBSCRIPTION ${SUB_NAME} REFRESH PUBLICATION;
  DROP TABLE public.<table>;
RUNBOOK
chmod 600 /root/RUNBOOK-schema-drift.md

echo
echo "========================================"
echo "DONE"
echo "========================================"
echo
echo "Subscription state on target:"
run_target "SELECT subname, subenabled, subpublications FROM pg_subscription;"
echo
echo "Logical slot on source:"
run_source "SELECT slot_name, active, confirmed_flush_lsn FROM pg_replication_slots WHERE slot_type='logical';"
echo
echo "Runbook: /root/RUNBOOK-schema-drift.md"

Two operational hazards worth noting again: first, the initial copy holds a long transaction on the source — for tables over a hundred gigabytes this can collide with vacuum and cause table bloat on the source while the copy runs. For that case, switch the script to copy_data = false and pre-seed via pg_dump --data-only; the subscription will then start tailing the WAL from the slot’s creation point. Second, pg_stat_subscription.seconds_behind is wallclock, not WAL position. A subscription that is “five seconds behind” but flat-lined on a stuck DDL is not fine — always cross-check with the source’s confirmed_flush_lsn.

For analytics replication that needs to be defended as part of your data platform — schema-change gating, drift alerts, parity audits — bring it under Managed Cloud Ops and pair it with our deployment management discipline. Open a scoping conversation and we’ll review the publication design before it ships.