PostgreSQL Logical Replication, Part 2: Operating It with DDL, Sequences and Conflicts

Manosh Malai
Dec 2, 2026
10
Mins to Read
All
Operating PostgreSQL logical replication with DDL, sequences and conflict handling
Operating PostgreSQL logical replication with DDL, sequences and conflict handling

This is Part 2 of the logical replication series. Part 1: Setting Up a Source and Destination Between Two Servers built a working replication and verified it. This post covers what comes after that: handling schema changes and sequences, managing publications and subscriptions, keeping the replication slot under control, and resolving conflicts.

It continues with the same environment from Part 1, so complete Part 1 first if you have not. As in Part 1, the source is the publisher and the destination is the subscriber, and every step says which server to run it on:

ItemValue
Source (publisher)pg-publisher, 172.16.20.21, database appdb
Destination (subscriber)pg-subscriber, 172.16.20.22, database appdb
Publication (on the source)app_pub (tables public.customers and public.orders)
Subscription (on the destination) and slot (on the source)app_sub
Replication user (on the source)replicator

The key point to carry over from Part 1: logical replication copies row changes only. Everything else, such as table definitions, sequence values, roles and statistics, stays your responsibility. The sections below show how to handle each one.

1. Important Behaviour and Tuning

Most logical replication incidents come from what is not replicated automatically. This section covers each case and the safe way to handle it.

1.1 Schema changes (DDL)

Run on: both servers, in the order given below. DDL is never replicated, so schema changes must be applied on the source and on the destination, in an order that keeps the apply worker working:

ChangeOrder
Add a columnDestination first, then source. The reverse fails because the destination lacks the column
Drop a columnSource first, then destination
Add a new tableCreate it on both. Then ALTER PUBLICATION app_pub ADD TABLE public.new_table; on the source and ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION; on the destination
Rename a table or columnNot safe to do live: matching is by name. Add the new object, migrate, then drop the old one
Add an indexIndependent on each side. The destination can have extra indexes, and they help if it is used for reporting
Adding a column: apply it on the destination first
1DestinationALTER TABLE ... ADD COLUMN
2SourceALTER TABLE ... ADD COLUMN
Reverse order: the apply worker stops with missing replicated column and retries until the destination is fixed.

If the apply worker meets a change it cannot map, it stops with an error like this in the destination log and retries until you fix the schema:

2026-11-12 14:20:31.552 UTC [1950] ERROR:  logical replication target relation "public.orders" is missing replicated column: "discount"
2026-11-12 14:20:31.553 UTC [1812] LOG:  background worker "logical replication apply worker" (PID 1950) exited with exit code 1

For schema changes that must not block writes, see our post on online schema changes in PostgreSQL with pg_osc.

1.2 Sequences

Sequence values are not replicated. The destination's sequences stay at their starting value while the tables fill up with rows from the source. This is harmless while the destination is read-only, and it causes duplicate-key errors the moment applications start writing to it. Before you switch applications to the destination, copy the current values.

Run on: source (pg-publisher), in psql, connected to appdb:

SELECT schemaname, sequencename, last_value FROM pg_sequences ORDER BY 1, 2;
 schemaname |    sequencename    | last_value
------------+--------------------+------------
 public     | customers_id_seq   |      48210
 public     | orders_id_seq      |     912764
(2 rows)

Run on: destination (pg-subscriber), in psql, connected to appdb. Set each sequence to the source value with a safety margin, after writes to the source have stopped or just before the switch:

SELECT setval('public.customers_id_seq', 48210 + 1000);
SELECT setval('public.orders_id_seq', 912764 + 1000);

1.3 Triggers, foreign keys and rules on the destination

The apply worker runs with session_replication_role = replica. That has two effects:

  • Foreign key constraints are not checked while applying, because they are enforced by triggers. The data is already consistent on the source
  • Ordinary triggers do not fire on the destination for replicated changes. Only triggers marked ENABLE REPLICA or ENABLE ALWAYS do

Run on: destination (pg-subscriber). This avoids double work, but it matters if you rely on a trigger on the destination, for example to write an audit row. Enable it explicitly:

ALTER TABLE public.orders ENABLE REPLICA TRIGGER orders_audit_trg;

1.4 Replicating part of a table

Run on: source (pg-publisher), in psql, connected to appdb. On PostgreSQL 15 and later, a publication can send only some rows or some columns:

-- orders: only rows that are not archived
-- customers: only the id and name columns (replica identity columns must be included)
ALTER PUBLICATION app_pub SET TABLE
  public.orders WHERE (status <> 'archived'),
  public.customers (id, name);

Notes:

  • SET TABLE replaces the whole table list of the publication, so list every table you still want
  • A row filter on a table that publishes UPDATE or DELETE may only use columns that are part of the replica identity
  • The destination must have the published columns. It can have more columns, which then get their defaults
  • After a change that alters what is published, run ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION; on the destination

1.5 TRUNCATE and partitioned tables

Run on: source (pg-publisher), when you create or alter the publication:

  • TRUNCATE is replicated by default (PostgreSQL 11+). Remove it with WITH (publish = 'insert, update, delete') if the destination must keep its rows
  • For a partitioned table, the publication sends changes using the identity of each leaf partition by default. Create the publication with WITH (publish_via_partition_root = true) (PostgreSQL 13+) to publish them as if they came from the parent table. That lets the destination have a different partition layout, or a plain table

1.6 Large transactions and memory

By default the source decodes a transaction in memory and sends it only after it commits. When a transaction is larger than logical_decoding_work_mem (default 64MB, set on the source), the source spills the rest to disk, in the pg_replslot directory. For bulk loads, raise the parameter, or enable streaming so the destination starts applying a large transaction before it commits.

Run on: destination (pg-subscriber), in psql:

ALTER SUBSCRIPTION app_sub SET (streaming = parallel);   -- PostgreSQL 16; use 'on' for 14 and 15

1.7 Throughput

One subscription uses one apply worker on the destination, which applies transactions one at a time in commit order. If a single worker cannot keep up with the write rate:

  • Make sure the destination tables have the indexes that UPDATE and DELETE need to find rows by the replica identity. A missing index on a REPLICA IDENTITY FULL table is the most common cause of a slow apply worker (see the disadvantages in Part 1, Section 4.6)
  • Use streaming = parallel on PostgreSQL 16 for large transactions
  • Split the tables over several publications and subscriptions. Each has its own slot and apply worker, but the subscriptions are no longer consistent with each other at one point in time, so keep tables that are queried together (or linked by foreign keys) in the same subscription

2. Managing Publications and Subscriptions

Day-to-day changes are small ALTER statements, and the order of the steps on the source and the destination matters. Each statement below is marked with the server it runs on. The full list of options is in the ALTER SUBSCRIPTION reference.

2.1 Add a table

-- 1. on the destination: create the table (same name, columns and key)
-- 2. on the source:
ALTER PUBLICATION app_pub ADD TABLE public.payments;
ALTER PUBLICATION

-- 3. on the destination:
ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION;
ALTER SUBSCRIPTION

The refresh starts a table synchronization worker for the new table only. Other tables are not copied again.

2.2 Remove a table

-- on the source
ALTER PUBLICATION app_pub DROP TABLE public.payments;

-- on the destination
ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION;

The table and its rows stay on the destination. They simply stop receiving changes.

2.3 Re-synchronize one table

There is no single command for this. Remove the table, empty it and add it back:

-- on the source
ALTER PUBLICATION app_pub DROP TABLE public.orders;

-- on the destination
ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION;
TRUNCATE public.orders;

-- on the source
ALTER PUBLICATION app_pub ADD TABLE public.orders;

-- on the destination
ALTER SUBSCRIPTION app_sub REFRESH PUBLICATION;

The last refresh copies the table again with copy_data = true, which is the default.

2.4 Pause and resume

Run on: destination (pg-subscriber), in psql:

ALTER SUBSCRIPTION app_sub DISABLE;
ALTER SUBSCRIPTION app_sub ENABLE;

While a subscription is disabled, the slot stays on the source and keeps retaining WAL. Do not leave a subscription disabled for long (see Section 3).

2.5 Change the connection details

Run on: destination (pg-subscriber), in psql:

ALTER SUBSCRIPTION app_sub CONNECTION 'host=172.16.20.31 port=5432 dbname=appdb user=replicator password=Use_A_Strong_Password_Here sslmode=require';

Use this after a password change of replicator or when the source moves to a new address. The slot and its position are kept.

2.6 Skip a failing transaction

Run on: destination (pg-subscriber), in psql. When the apply worker fails on a conflict, the destination log names the LSN where the failed transaction finished. On PostgreSQL 15 and later you can skip exactly that transaction:

ALTER SUBSCRIPTION app_sub SKIP (lsn = '1A/70002B10');
ALTER SUBSCRIPTION

This discards every change of that transaction on the destination, so the two sides will differ afterwards. Prefer fixing the conflicting row on the destination, and use SKIP only when you accept the difference and have a plan to repair it (see Section 4).

2.7 Drop a subscription and its slot

Run on: destination (pg-subscriber), in psql. When the source is reachable, one statement removes the subscription and also the slot on the source:

DROP SUBSCRIPTION app_sub;
NOTICE:  dropped replication slot "app_sub" on publisher
DROP SUBSCRIPTION

If the source is unreachable, detach the slot first, then drop the slot on the source yourself when it is back:

-- on the destination
ALTER SUBSCRIPTION app_sub DISABLE;
ALTER SUBSCRIPTION app_sub SET (slot_name = NONE);
DROP SUBSCRIPTION app_sub;

-- on the source, later
SELECT pg_drop_replication_slot('app_sub');

The publication stays on the source until you run DROP PUBLICATION app_pub; there. The tables and data on the destination are never removed by dropping the subscription.

3. Best Practices and Pitfalls

The biggest operational risk is a replication slot that nobody consumes, because it fills the source's disk. Most other problems are schema drift and unmanaged writes on the destination.

3.1 Monitor replication slots

A slot retains WAL until its destination confirms it. A destination that is stopped, disabled, broken by an error, or removed without dropping its slot makes the source keep WAL indefinitely, and the disk of the source fills up. Set max_slot_wal_keep_size on the source (Part 1, Section 4.2), and alert on inactive slots and on the size of pg_wal.

Run on: source (pg-publisher), in psql:

SELECT slot_name, active, wal_status,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;
 slot_name | active | wal_status | retained_wal
-----------+--------+------------+--------------
 app_sub   | t      | reserved   | 48 MB
(1 row)

Watch wal_status in pg_replication_slots: reserved is healthy, extended means the slot is holding WAL beyond max_wal_size, unreserved means it is about to lose WAL, and lost means it is already invalid.

Replication slot wal_status: from healthy to lost
reservedHealthy
extendedHolding WAL beyond max_wal_size
unreservedAbout to lose WAL
lostSlot is invalid, recreate the subscription

If a disconnected destination falls further behind than max_slot_wal_keep_size allows, the source invalidates the slot:

# source
2026-11-12 16:29:36.402 UTC [2284] LOG:  invalidating obsolete replication slot "app_sub"
2026-11-12 16:29:36.402 UTC [2284] DETAIL:  The slot's restart_lsn 1A/71000000 exceeds the limit by 33554432 bytes.
2026-11-12 16:29:36.402 UTC [2284] HINT:  You might need to increase max_slot_wal_keep_size.

# destination
2026-11-12 16:31:09.774 UTC [1950] ERROR:  could not receive data from WAL stream: ERROR:  can no longer get changes from replication slot "app_sub"
2026-11-12 16:31:09.774 UTC [1950] DETAIL:  This slot has been invalidated because it exceeded the maximum reserved size.

An invalidated logical slot cannot be recovered. You must drop the subscription, empty or reload the tables, and create it again with a full initial copy. That is the price of the safety cap, and it is far cheaper than a full disk on the production source.

3.2 Keep long transactions and the initial copy in mind

The initial copy runs inside a snapshot on the source, and a slot also holds back the cleanup of old catalog rows. A very long copy or a very long-running transaction therefore delays vacuum on the source. Schedule the first synchronization of large tables outside peak hours, and watch table bloat while it runs.

3.3 Treat replicated tables as read-only on the destination

Run on: destination (pg-subscriber), in psql. Writes made directly on the destination are not sent anywhere, and they can collide with replicated rows. Take the write privileges away from application roles on the replicated tables:

REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON public.customers, public.orders FROM app_user;

Extra tables that are not published are fine to write to. That is one of the strengths of logical replication.

3.4 Keep the schema under control

  • Give every table a primary key before it is published. Avoid REPLICA IDENTITY FULL on large tables
  • Run schema changes through one migration process that applies them to both servers in the order from Section 1.1
  • Compare schemas of the two servers regularly, for example with pg_dump --schema-only and a diff

3.5 Plan for failover separately

Logical replication is a data distribution tool, not a high availability solution. It has no automatic failover, and the destination lags behind by design. For failover, use physical replication with Patroni or repmgr, and use logical replication for upgrades, migrations and selective copies. Our guide on converting a standalone PostgreSQL database to a Patroni cluster shows one way to do it.

If the source itself has a physical standby, be aware that before PostgreSQL 17 the logical slot is not copied to that standby. After a failover the destination loses its slot and needs a full resynchronization. PostgreSQL 17 adds failover slots (the failover option of CREATE SUBSCRIPTION) to solve this.

3.6 Alert on the right signals

  • On the source: pg_stat_replication is empty for the subscription's application_name, which means the destination is disconnected
  • On the source: a logical slot with active = f, or with retained WAL above your threshold
  • On the destination: apply_error_count or sync_error_count of pg_stat_subscription_stats is increasing
  • On the source: lag_size from Part 1, Section 6.4 keeps growing
  • On the source: disk usage of the pg_wal directory

Our guide on PostgreSQL observability with Grafana and Prometheus shows how to turn these signals into dashboards and alerts.

3.7 Keep real backups

Logical replication copies DELETE and TRUNCATE just as it copies INSERT. A wrong delete on the source is replayed on the destination within seconds. Keep regular backups and WAL archiving on the source for point-in-time recovery.

4. Runtime Issues and Conflict Resolution

Setup-time errors (connection, permissions, missing tables) are covered in Part 1, Section 7. Once replication is running, the problems you meet are schema drift, data conflicts and invalidated slots.

SymptomServerLikely cause and fix
logical replication target relation "public.x" is missing replicated columnDestinationA column was added on the source first. Add it on the destination (Section 1.1) and the worker retries on its own
duplicate key value violates unique constraintDestinationA row on the destination collides with a replicated row. See Section 4.1
can no longer get changes from replication slotDestination (error), source (slot)The slot was invalidated. Recreate the subscription with a full copy (Section 3.1)
apply_error_count keeps risingDestinationThe apply worker is failing and retrying. Read the destination log for the first error and fix its cause

4.1 Resolving a data conflict

When the apply worker cannot apply a change, it stops, logs the error, and retries every few seconds until the cause is removed. Replication then stands still and the slot retains WAL on the source, so act quickly. A duplicate key looks like this in the destination log (see also the PostgreSQL notes on logical replication conflicts):

2026-11-12 15:02:18.930 UTC [1950] ERROR:  duplicate key value violates unique constraint "orders_pkey"
2026-11-12 15:02:18.930 UTC [1950] DETAIL:  Key (id)=(912765) already exists.
2026-11-12 15:02:18.930 UTC [1950] CONTEXT:  processing remote data for replication origin "pg_16413" during message type "INSERT" for replication target relation "public.orders" in transaction 742, finished at 1A/70002B10

Fix it in this order, all on the destination (pg-subscriber):

  1. Read the table, key and LSN from the error. The CONTEXT line has all three
  2. Look at the conflicting row on the destination and decide which version is right
  3. Delete or correct the row on the destination. The next retry then succeeds on its own, and no restart is needed
  4. Only if the whole transaction must be discarded: ALTER SUBSCRIPTION app_sub SKIP (lsn = '1A/70002B10'); (PostgreSQL 15+), and then repair the difference by hand
  5. Find the cause, which is usually a write directly on the destination (Section 3.3) or a sequence that was not advanced (Section 1.2)
Fixing a conflict on the destination
  1. 1
    Read the errorTable, key and LSN are in the CONTEXT line
  2. 2
    Check the conflicting rowDecide which version is right
  3. 3
    Delete or correct the rowThe next retry succeeds, no restart needed
  4. 4
    Skip only as a last resortALTER SUBSCRIPTION ... SKIP, then repair by hand
  5. 5
    Find the causeDirect writes on the destination, or a sequence not advanced

To stop a subscription from retrying forever, create it or alter it with disable_on_error = true (PostgreSQL 15+). The subscription is then disabled after the first error, so you notice it in monitoring, but you must enable it again after the fix:

ALTER SUBSCRIPTION app_sub SET (disable_on_error = true);
-- after the fix
ALTER SUBSCRIPTION app_sub ENABLE;

5. Conclusion

Part 1 gave you a working replication. Running it safely comes down to five habits:

  1. Apply every schema change on both servers, in the order from Section 1.1
  2. Copy sequence values from the source before switching applications to the destination (Section 1.2)
  3. Keep replicated tables read-only on the destination, so conflicts stay rare (Section 3.3)
  4. Cap max_slot_wal_keep_size on the source and alert on inactive slots, so a stuck destination cannot fill the source's disk (Section 3.1)
  5. Fix conflicts at the row on the destination, and use SKIP only as a last resort (Section 4.1)

Next, we can build on this with bidirectional setups and a failover-friendly topology using Patroni.

Running logical replication in production means watching slots, schema drift and conflicts every day. With 10+ years of database expertise, 800+ clients and 6000+ servers managed, Mydbops can plan, run and monitor logical replication, live migrations and major version upgrades for your PostgreSQL databases.

No items found.

About the Author

CTO of Mydbops, leading the engineering behind its managed database services and agentic platforms for databases. He has 16+ years of Linux and open-source experience, from kernel tuning to MongoDB performance and automation.

Topic covered

Subscribe Now!

Subscribe here to get exclusive updates on upcoming webinars, meetups, and to receive instant updates on new database technologies.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.