Sub topic 14
When to Choose Logical Replication
This chapter assumes you have read the earlier chapters. You should know what publications, subscriptions, replication slots, and replica identity are. You should also know the limits of logical replication. Here you will use that knowledge to decide when logical replication fits a job and when another tool fits better.
The decision in one view
Logical replication copies row changes for selected tables. Physical replication copies the whole cluster, byte for byte. Most design choices follow from that difference.
| Need | Logical replication | Physical (streaming) replication |
|---|---|---|
| Replicate only some tables | Yes | No, whole cluster |
| Replicate between major versions | Yes | No |
| Standby accepts writes to other tables | Yes | No, read-only |
| Copy DDL, sequences, large objects | No | Yes |
| Exact byte-for-byte copy for failover | No | Yes |
| Low setup overhead for a full HA standby | No | Yes |
Use the table as a first filter. The sections below cover the common cases and their trade-offs.
Use case 1: online major-version upgrade
This is the most common reason to choose logical replication. Physical replication needs identical major versions, so it cannot help here. Logical replication works across versions, because it sends row changes, not storage pages.
The usual plan has these steps:
- Build a new cluster on the target version.
- Copy the schema with
pg_dump --schema-onlyand restore it on the new cluster. - Create a publication on the old cluster and a subscription on the new one.
- Wait for the initial sync to finish and for lag to reach near zero.
- Stop writes on the old cluster briefly.
- Synchronize sequences by hand, because logical replication does not replicate them.
- Point applications at the new cluster.
Step 6 is the one people forget. A sequence on the subscriber still holds its starting value, so the first insert after cutover can collide with existing keys. Set each sequence past the publisher's current value before you accept writes.
-- On the publisher, after writes are stopped: read the current value
SELECT last_value FROM orders_id_seq;
-- On the subscriber: move the sequence past it, with a safety margin
SELECT setval('orders_id_seq', 1000000 + 1000);Replace 1000000 with the value you read. The margin guards against rows committed just before you stopped writes.
Compare this with pg_upgrade. It is often faster and simpler, and it needs downtime that grows with the upgrade mode and data size. Choose logical replication when the allowed downtime is seconds to a few minutes and you can accept the extra work of sequences, schema copying, and a long initial sync.
Use case 2: selective replication to another system
You may want only part of the data somewhere else. Examples are a reporting database that needs three tables, or a regional database that needs one customer segment.
Publications fit this directly. You pick tables, and on PostgreSQL 15 and later you can also pick columns and rows.
-- Requires PostgreSQL 15 or later
CREATE PUBLICATION reporting_pub
FOR TABLE orders (id, customer_id, status, total)
WHERE (status <> 'cancelled');Keep these points in mind:
- The subscriber table can have extra columns, and it can have its own indexes. Reporting databases often add indexes that the primary would not want.
- A column list leaves out sensitive columns, but it is not a security boundary by itself. The subscriber's role needs to be trusted with the data it does receive, and the publisher still sends every published column over the connection. Use TLS in the connection string.
- A row filter on
UPDATEandDELETEcan only use columns that are part of the replica identity. Check this when you design the filter.
Use case 3: consolidating data from several databases
A subscriber can subscribe to publications from several publishers. This lets you collect data from many source databases into one analytical database.
The main risk is key collisions. If two publishers both have orders rows with id = 1, the second insert fails with a unique violation, and the apply worker stops. Avoid this in one of these ways:
- Give each source a different key range or use globally unique keys such as UUIDs.
- Replicate each source into a separate table or schema on the subscriber.
- Include a source identifier in the primary key.
Use case 4: a writable copy with its own data
A logical subscriber is a normal read-write database. Only the replicated tables are managed by the subscription. You can create other tables on it, write to them, and run extra workloads there.
This is useful for a derived store, for example a table that holds aggregates built from replicated rows. It is risky if applications also write to the replicated tables. Those writes can conflict with incoming changes. Treat replicated tables as read-only on the subscriber, and enforce that with privileges.
-- On the subscriber: applications get read access only
REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON orders FROM app_user;
GRANT SELECT ON orders TO app_user;The apply worker runs under the subscription owner, so revoking rights from application roles does not stop replication.
Use case 5: change feeds for other systems
Logical decoding is the mechanism underneath. With an output plugin and a consumer, you can stream row changes to a message bus or a search index. Built-in publications and subscriptions only connect PostgreSQL to PostgreSQL. For other targets, you use a tool that reads a logical slot directly, such as a change-data-capture connector.
This choice has an operational cost. Each slot is a durable reservation of WAL on the publisher. A consumer that stops reading makes the publisher keep WAL until the disk fills. Decide who owns each slot and who is alerted when it lags.
When not to choose logical replication
Logical replication is the wrong tool in these cases.
You need a failover standby
Physical replication gives an exact copy that can take over. A logical subscriber lacks sequence values, DDL history, and any table you did not publish. Promoting it is not a real failover. Tools for automatic failover are built around physical replication.
Your schema changes often
DDL is not replicated. Every ALTER TABLE must be applied by hand on the subscriber, in an order that does not break the stream. A team that changes the schema many times a week pays for this repeatedly. Consider whether a migration tool that runs on both sides covers it, or whether physical replication is simpler.
Your tables have no usable key
Tables that publish updates or deletes need a replica identity. REPLICA IDENTITY FULL works, but the subscriber must search for the matching row using every column. Without a suitable index, that can mean a sequential scan for each change. For large tables this can make the subscriber fall far behind.
Your write volume is very high on one large transaction
Before PostgreSQL 14, the publisher decoded a transaction and sent it only after it committed. Large transactions caused delay and memory or disk spill. Streaming of in-progress transactions arrived in version 14, as an option on the subscription. Even so, the apply side is generally a single process per subscription for a given table, so it can fall behind a busy primary that writes in parallel. Measure lag under realistic load before you commit to the design.
You need conflict resolution
PostgreSQL's built-in logical replication detects errors, such as a unique violation, and stops the apply worker. It does not decide which version of a row wins. Multi-writer designs where both sides update the same rows need extra tooling or application rules. Without these, you will repair conflicts by hand.
A decision procedure
Work through these questions in order.
Operating costs to budget for
Before you choose, list the recurring work:
- Monitoring slot lag and retained WAL on the publisher.
- Applying every schema change to both sides, in the right order.
- Running
ALTER SUBSCRIPTION ... REFRESH PUBLICATIONafter adding tables. - Checking sequence values before any cutover.
- Handling apply errors, which stop replication until fixed.
- Keeping a plan to drop slots when a subscriber is retired.
Combining both kinds
The two methods work together. A common layout uses a physical standby for high availability and logical replication for data distribution. Note one limitation: in versions before PostgreSQL 17, logical slots exist only on the primary and are not copied to physical standbys. After a failover, the new primary lacks the slot, and subscribers cannot continue without a resync. PostgreSQL 17 added slot synchronization to standbys, which reduces this problem. Check the version you run and test a failover with a subscriber attached.
Summary of criteria
Choose logical replication when you need at least one of these:
- A major-version upgrade with a short outage.
- A subset of tables, rows, or columns in another database.
- A target that accepts its own writes to other tables.
- Data consolidated from several sources.
Choose something else when you need an identical standby, when the schema changes constantly and nobody owns the manual work, or when several writers update the same rows.
Exercise
A team wants a hot standby that can take over automatically if the primary fails. They also want to move to a newer major version next quarter. Which replication types do they use for each goal, and why?
Show answer
Use physical (streaming) replication for the failover standby, because it copies the entire cluster exactly, including DDL and sequences, and failover tools are built around it. Use logical replication for the major-version upgrade, because it works across versions. Physical replication cannot do that. For the upgrade they must copy the schema manually, wait for the initial sync, synchronize sequences, and then cut over.
Exercise
You subscribe a reporting database to a publication, and after cutover the first insert on the new cluster fails with a duplicate key error on orders.id. The data was copied correctly. What is the likely cause, and how do you fix it?
Show answer
Logical replication does not replicate sequence values. The sequence on the new cluster still holds its starting value, so it generates ids that already exist. Read the current value of the sequence on the old cluster after stopping writes, then run SELECT setval('orders_id_seq', <value plus margin>); on the new cluster before accepting writes.
Exercise
Two regional databases each have an orders table with ids starting at 1. You want to subscribe one central database to both. What goes wrong, and name two ways to avoid it.
Show answer
Rows from the second publisher collide with rows from the first on the primary key. The insert fails with a unique violation and the apply worker stops. Avoid it by using globally unique keys such as UUIDs or non-overlapping id ranges, by replicating each source into a separate table or schema, or by adding a source identifier to the primary key.