Sub topic 3
Handling Schema Changes
This chapter assumes a working publisher and subscriber, basic SQL, and the ability to read the server log.
Handling schema changes
Logical replication does not copy DDL (schema statements such as ALTER TABLE). A column you add on the publisher does not appear on the subscriber automatically. Apply the change to the subscriber first, so it can accept the new data before the publisher sends it.
-- On the subscriber first
ALTER TABLE orders ADD COLUMN channel text;
-- Then on the publisher
ALTER TABLE orders ADD COLUMN channel text;For a new table, create it on the subscriber, add it to the publication, then refresh the subscription:
-- On the publisher
ALTER PUBLICATION orders_pub ADD TABLE order_items;
-- On the subscriber, after creating order_items
ALTER SUBSCRIPTION orders_sub REFRESH PUBLICATION;Apply errors and conflicts
The subscriber's apply worker replays changes in commit order. When a change cannot be applied, such as a unique-key violation, the worker stops and retries. The subscription stays stuck until you act.
Find the failing log line, which names the transaction's LSN (log sequence number). On PostgreSQL 15 and later, you can skip that transaction:
ALTER SUBSCRIPTION orders_sub SKIP (lsn = '0/1A2B3C4D');Monitoring replication and cleaning up slots
An inactive replication slot makes the publisher keep WAL (write-ahead log) files, which can fill the disk. Check retained WAL on the publisher:
SELECT slot_name,
active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;If the publisher is unreachable and you must remove a subscription, detach its slot first, then drop it:
ALTER SUBSCRIPTION orders_sub DISABLE;
ALTER SUBSCRIPTION orders_sub SET (slot_name = NONE);
DROP SUBSCRIPTION orders_sub;
-- On the publisher, if the slot remains
SELECT pg_drop_replication_slot('orders_sub');What logical replication does not replicate
- DDL, so schema changes must be made on both sides.
- Sequence current values, so sequences need manual sync.
- Large objects.
- Tables that are not in a publication.
When to choose logical replication
| Need | Physical | Logical |
|---|---|---|
| Whole-cluster standby | Good fit | Poor fit |
| Selected tables only | Not possible | Good fit |
| Online major-version upgrade | Requires same version | Good fit |
Exercise:
Exercise
A column is added to a published table on the publisher but not on the subscriber. What happens, and what should you do first?
Show answer
Replication fails on the subscriber because the incoming data has a column the subscriber's table lacks. Add the column to the subscriber first, then add it on the publisher.