Implementing Logical Replication

1. Understanding Logical Replication

AspectDetail
GranularityPer-table row changes
Cross-versionYes (PG 10 → 17 OK)
Writable subscriberYes (unlike physical standby)
Use casesMajor-version upgrade, partial sync, multi-master patterns

2. Configuring wal_level

wal_level = logical

3. Setting max_replication_slots and max_wal_senders

max_replication_slots = 20
max_wal_senders       = 20

4. Creating Publication

CREATE PUBLICATION pub_orders FOR TABLE orders, order_items;

5. Adding Tables to Publication

ALTER PUBLICATION pub_orders ADD TABLE customers;
ALTER PUBLICATION pub_orders DROP TABLE order_items;

6. Publishing All Tables

CREATE PUBLICATION pub_all FOR ALL TABLES;
-- PG 15+: FOR TABLES IN SCHEMA app

7. Filtering Publication

-- PG 15+ row filters & column lists
CREATE PUBLICATION pub_us
   FOR TABLE orders (id, status, total_cents) WHERE (region = 'US');

8. Creating Subscription

CREATE SUBSCRIPTION sub_orders
   CONNECTION 'host=primary dbname=shop user=repl password=...'
   PUBLICATION pub_orders;

9. Setting Subscription Connection

ALTER SUBSCRIPTION sub_orders
   CONNECTION 'host=primary-new dbname=shop user=repl password=...';

10. Setting Publication Name

ALTER SUBSCRIPTION sub_orders SET PUBLICATION pub_orders_v2;

11. Managing Initial Data Copy

CREATE SUBSCRIPTION sub_orders ... WITH (copy_data = true);   -- default
-- Skip copy if data already loaded:
CREATE SUBSCRIPTION sub_orders ... WITH (copy_data = false, create_slot = true);

12. Monitoring Subscriptions

SELECT subname, pid, received_lsn, latest_end_lsn, last_msg_send_time
  FROM pg_stat_subscription;
SELECT * FROM pg_subscription;

13. Refreshing Publication

ALTER SUBSCRIPTION sub_orders REFRESH PUBLICATION;
-- Adds/removes tables on subscriber to match publisher

14. Dropping Subscription

ALTER SUBSCRIPTION sub_orders DISABLE;
ALTER SUBSCRIPTION sub_orders SET (slot_name = NONE);  -- if slot already gone
DROP SUBSCRIPTION sub_orders;

15. Dropping Publication

DROP PUBLICATION pub_orders;
Note: Tables without REPLICA IDENTITY (PK or explicit) cannot UPDATE/DELETE-replicate. Add primary key first.