How to Implement Logical Replication
Replicate selected tables between databases with logical replication: publications, subscriptions, initial sync and conflict handling.
On this page
Introduction
Physical replication copies the whole database to an identical standby. Logical replication is different: it streams row changes for selected tables as logical operations, so the subscriber can be a different database with a different schema, running a different version, or holding only a subset of the data. It is the basis for zero-downtime migrations, for feeding analytics from production, and for selective replication across environments. It also has its own set of rules that, ignored, produce a subscription that silently stops or misses data.
Logical Versus Physical Replication
Physical replication ships the write-ahead log and produces a byte-for-byte copy of the primary’s storage; the standby is the same database, same version, all tables. Logical replication decodes the write-ahead log into row-level changes and ships them per publication, so the subscriber applies inserts, updates and deletes to tables it chooses, in a schema it controls.
The flexibility is the point: replicate a subset of tables, transform on apply, replicate across versions during an upgrade, or replicate to a database that also serves other workloads and merges the replicated tables with its own. The cost is that logical replication has more moving parts and does not replicate everything (for example, sequence values are not synced by default).
# physical vs logical
physical: WAL -> identical standby; whole cluster, same version
logical: decoded row changes -> subscriber chooses tables + schema
# logical enables: subset replication, cross-version, migrations, CDC
# logical does NOT copy by default: sequences, DDL, large objects
Setting Up a Publication and Subscription
On the source (publisher), create a publication that lists the tables to replicate, optionally restricted to specific operations. On the target (subscriber), create a subscription that connects to the publisher and applies the stream. The publisher’s write-ahead log must be configured for logical decoding, which requires a restart.
Grant the replication connection the privileges it needs and use a dedicated user, so the subscription reads only what it requires. Set the subscription’s connection string carefully and note that it runs a background worker on the subscriber, so it needs a role with replication rights.
-- Publisher: enable logical decoding (postgresql.conf, requires restart)
-- wal_level = logical
CREATE PUBLICATION orders_pub FOR TABLE orders, order_items;
-- Subscriber: create the schema first (DDL is NOT replicated), then subscribe
CREATE SUBSCRIPTION orders_sub
CONNECTION 'host=primary port=5432 dbname=app user=replicator password=...'
PUBLICATION orders_pub
WITH (copy_data = true); -- initial snapshot, then stream changes
Initial Synchronisation
When a subscription is created with copy_data, the subscriber takes an initial snapshot of each published table and then streams subsequent changes from that point. The snapshot and the stream boundary must be consistent, which the engine handles, but a large table means a long initial copy during which the subscription is not yet caught up.
For a large initial copy, expect resource use on both sides and plan for it. Alternatively, pre-load the data by another means and create the subscription with copy_data disabled, then let the stream catch up, which can be faster when you can copy the bulk efficiently. Always verify that the initial state plus the stream equal the publisher’s current state.
# initial sync options
copy_data = true -> engine snapshots each table, then streams from that LSN
copy_data = false -> subscriber already has data; stream from now
# for big tables: bulk-load first, then copy_data=false + let it catch up
# verify: row counts and a checksum-ish sample match after catch-up
What Is Not Replicated
Logical replication copies row changes for the published tables. It does not copy DDL: creating a new column on the publisher does not create it on the subscriber, and an insert into a column the subscriber lacks fails. Sequence values are not synchronised by default, so a subscriber using a serial column can generate conflicting ids unless the sequence is advanced manually.
Large objects, some data types and certain operations are also not replicated or are replicated with caveats. Keep the subscriber’s schema in step with the publisher by applying DDL to both, and manage sequences separately. A schema change on the publisher without the corresponding change on the subscriber stops replication for the affected table.
# logical replication does not copy:
[ ] DDL (CREATE/ALTER/DROP) -> apply to both sides
[ ] sequence values -> advance the subscriber's sequences
[ ] large objects (LOBs) -> replicate by other means
[ ] unlogged tables -> not in the WAL
# a publisher schema change without the subscriber's => replication stalls
Monitoring and Conflict Handling
Monitor the subscription’s state and lag on the subscriber. A subscription that has errored stops applying, and the lag grows silently until you notice. Watch for errors, for the last received position, and for the lag between the publisher’s position and the subscriber’s applied position.
Conflicts happen when the subscriber’s copy of a row diverges, for example because something else wrote to the replicated table. By default a conflict stops the subscription. Decide the policy: make the subscriber’s replicated tables read-only and written only by replication, or configure conflict handling to skip, or resolve manually. A subscriber that also writes the same tables invites conflicts.
-- Subscriber: check subscription health and lag.
SELECT subname, pid, received_lsn, latest_end_lsn,
now() - last_msg_receipt_time AS since_last_msg
FROM pg_stat_subscription;
-- Check for a stopped subscription (worker not running => lag grows unseen)
SELECT subname, subenabled FROM pg_subscription;
Use Cases: Migration and Analytics
For a zero-downtime migration, replicate from the old database to the new one, let it catch up, then cut writes over and keep replicating until the switch, at which point the new database is current. Logical replication makes the migration a controlled cutover rather than a big-bang dump and restore.
For analytics, replicate a subset of tables into a reporting database that can be indexed differently, avoiding analytical load on the primary. Because the subscriber is a normal database, it can hold materialised views and indexes tuned for reports without affecting the source.
# migration cutover with logical replication
1. publisher (old) -> subscriber (new), copy_data=true
2. wait until lag ~ 0 (caught up)
3. stop writes to old (brief), confirm lag 0, point app at new
4. drop the subscription
# analytics: replicate select tables -> reporting DB, index for reports
# keeps heavy read load off the primary
Common Pitfalls and Conclusion
Do not expect DDL or sequences to replicate. Do not let the subscriber write the same tables and then be surprised by conflicts. Do not ignore a stopped subscription, which silently grows lag. Do not assume the publisher’s schema and the subscriber’s stay in step without effort. And do not use logical replication where physical replication’s whole-database copy is what you actually need.
Logical replication streams row changes for the tables you choose, enabling subset replication, cross-version upgrades and migrations. Set up a publication and subscription, do a consistent initial sync, apply DDL and manage sequences on both sides, monitor for a stopped subscription, and decide a conflict policy. Then you can replicate exactly what you need, between databases that need not be identical.
Sources: PostgreSQL: Logical replication, PostgreSQL: Logical decoding, PostgreSQL: CREATE PUBLICATION.
FAQ
- Is DDL replicated with logical replication?
- No. Only row changes for published tables are replicated. Creating a column on the publisher does not create it on the subscriber, and an insert into a column the subscriber lacks fails. Apply DDL to both sides to keep the schemas in step.
- Why does my subscription stop silently?
- Usually a conflict (the subscriber already has a divergent row) or a schema mismatch (a column the publisher has but the subscriber does not). By default a conflict stops the subscription, and lag grows unseen, so monitor the subscription state and errors.
Report a problem with this articleOpens a pre-filled issue on GitHub.