Sub topic 15
When to Use Logical Replication Instead
This chapter assumes you have a working streaming-replication pair: a primary, a hot standby built with pg_basebackup, and some familiarity with pg_stat_replication, replication slots, and promotion. It also assumes you know what a publication of rows means in plain SQL terms (tables, primary keys, INSERT/UPDATE/DELETE). Its job is to help you decide when physical streaming replication is the wrong tool and logical replication is the right one.
Physical and logical replication compared
Everything you have built so far is physical replication. The primary ships WAL records that describe changes to disk blocks, and the standby replays them byte for byte. The standby is a binary copy of the whole cluster.
Logical replication decodes the WAL into row-level changes (insert this row, update that row, delete that row) and sends those changes to a subscriber. The subscriber is an ordinary, writable PostgreSQL database that applies the changes with normal SQL machinery. The two servers only have to agree on table names and column types. They do not have to be identical copies.
Logical replication uses a publish/subscribe model:
- A publication on the source database names the tables whose changes are published.
- A subscription on the target database connects to the source, creates a replication slot there, copies the initial table contents, and then applies the stream of changes.
What each approach can and cannot do
| Capability | Physical (streaming) | Logical |
|---|---|---|
| Unit of replication | Entire cluster, all databases | Chosen tables in one database |
| Standby or subscriber writable | No, read-only during recovery | Yes, except for replicated tables you should not modify |
| Different major versions | No, same major version | Yes, can replicate across major versions |
| Different CPU architecture or OS | No, must match | Yes |
| Extra indexes or tables on the target | No, identical copy | Yes |
| Replicates DDL (schema changes) | Yes, as part of the WAL | No, you apply schema changes yourself |
| Replicates sequences and large objects | Yes | No (sequence values are not replicated, and neither are large objects) |
| Failover target | Yes, promote the standby | Not a drop-in failover mechanism |
| Overhead on the primary | Low | Higher, because of logical decoding |
The rows about DDL and sequences are the ones that surprise people most. Physical replication carries everything. Logical replication carries only INSERT, UPDATE, DELETE, and TRUNCATE on published tables (depending on publication options).
Good reasons to choose logical replication
Choose logical replication when a requirement cannot be met by an identical read-only copy.
- Major-version upgrades with little downtime. Build a new cluster on the newer version, subscribe it to the old one, wait until it catches up, then switch applications over. A physical standby cannot do this because it must run the same major version.
- Replicating a subset of data. Send only some tables to a reporting database, or to another team, instead of the entire cluster.
- Writable targets with local additions. The subscriber can have extra indexes, extra columns that default on the subscriber side, or its own additional tables, which suits reporting or analytics workloads.
- Consolidating or distributing data. Several publishers can feed one subscriber, or one publisher can feed many subscribers with different table selections.
- Cross-platform replication. The two servers can run on different operating systems or architectures.
Good reasons to stay with physical replication
Keep streaming replication when the goal is availability and read scaling of the whole database.
- High availability. A physical standby is an exact copy, including schema, roles, sequences, and every database in the cluster. Promotion is simple and well understood.
- Everything must be copied. If you do not want to maintain a list of tables, physical replication cannot "forget" a new table.
- Lowest overhead. The standby just replays WAL. No decoding step runs on the primary.
- Disaster recovery. Combined with WAL archiving, physical replication supports point-in-time recovery.
The two are not exclusive. A common production layout uses a physical standby for failover and a logical subscription for a reporting or upgrade target.
A minimal logical replication setup
Logical replication needs wal_level = logical on the publisher. This is higher than the replica level used for streaming replication, and changing it requires a restart.
# postgresql.conf on the publisher
wal_level = logical
max_replication_slots = 10
max_wal_senders = 10The subscription connects with a role that has the REPLICATION attribute (the one you created earlier works) and SELECT on the published tables. The pg_hba.conf entry must allow the connection to the target database, not only the pseudo-database replication, because logical subscriptions connect to a real database.
First, create the table and publication on the publisher:
-- On the publisher, in database appdb
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer text NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE PUBLICATION orders_pub FOR TABLE orders;Next, create the same table on the subscriber and subscribe. The table definition is not copied for you.
-- On the subscriber, in database reportdb
CREATE TABLE orders (
order_id bigint PRIMARY KEY,
customer text NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE SUBSCRIPTION orders_sub
CONNECTION 'host=primary.example.com dbname=appdb user=replicator password=change-me'
PUBLICATION orders_pub;CREATE SUBSCRIPTION creates a logical replication slot on the publisher, copies the existing rows, and then streams new changes. You can watch it from both sides:
-- On the publisher
SELECT slot_name, plugin, slot_type, active, restart_lsn
FROM pg_replication_slots
WHERE slot_type = 'logical';
-- On the subscriber
SELECT subname, received_lsn, latest_end_lsn, latest_end_time
FROM pg_stat_subscription;Gotchas and failure modes
Tables need a replica identity
For UPDATE and DELETE to be applied on the subscriber, PostgreSQL must be able to identify the old row. By default it uses the primary key. A published table without a primary key rejects updates and deletes unless you set a replica identity, such as ALTER TABLE t REPLICA IDENTITY FULL. The FULL setting logs the entire old row and can make applying changes slow, because the subscriber may have to scan for matching rows.
Schema changes are manual
If you add a column on the publisher, the subscriber does not receive the change. Replication then fails with an error when it sees a row with a column that the subscriber lacks. Apply compatible DDL on the subscriber first (for additive changes), then on the publisher.
Sequences are not replicated
A subscriber's sequences stay at their initial values. If you plan to switch applications to the subscriber, for example after an upgrade, you must set each sequence with setval() before writing to it. Otherwise new rows can collide with existing keys.
Conflicts stop the apply worker
The subscriber is writable, so a local row can conflict with an incoming change. A unique-key violation, for example, makes the apply worker fail and retry. Replication stalls at that change until you fix the data on the subscriber or skip the transaction. Treat replicated tables on the subscriber as read-only in practice.
Slots retain WAL here too
A logical replication slot holds WAL on the publisher until the subscriber confirms it. The risk from the slots chapter applies again. If a subscriber is down for a long time or a subscription is dropped carelessly, the publisher's disk can fill. Monitor pg_replication_slots for inactive logical slots, and remove abandoned ones with pg_drop_replication_slot().
Logical slots and standbys
On a physical standby, logical slots are not carried over by default. After a failover, a subscription may have to be re-created or resynchronized unless your PostgreSQL version and configuration support slot synchronization to the standby. Check the documentation for your version before you rely on it. Plan for this if a logical subscriber depends on a primary that can fail over.
A decision guide
Ask these questions in order.
- Do you need a failover target for the whole server? Use physical streaming replication.
- Do you need to move to a new major version, a different platform, or a subset of tables? Use logical replication.
- Does the target need its own writes, indexes, or extra tables on replicated data? Use logical replication.
- Do you need DDL, sequences, and every database copied automatically? Use physical replication.
Exercise
Your team must upgrade a production database from one major PostgreSQL version to the next with only a brief outage. A colleague proposes adding a hot standby on the new version. Explain why that does not work, which replication type does, and name two things you must handle manually before switching applications to the new server.
Show answer
A physical standby replays WAL blocks and requires the same major version, so it cannot run the newer version. Use logical replication: create a publication on the old server and a subscription on the new one, with the schema already created on the new server. Before switching applications over, handle things logical replication does not carry: set sequence values on the new server with setval(), and apply any schema (DDL) changes made during the migration. Also confirm every published table has a primary key or a replica identity.
Exercise
A subscription was dropped on the subscriber while the publisher was unreachable. A week later the publisher's disk is nearly full. What is the likely cause, and how do you confirm and fix it?
Show answer
The logical replication slot was left behind on the publisher and keeps retaining WAL. Confirm with SELECT slotname, slottype, active, restartlsn, walstatus FROM pgreplicationslots; and look for an inactive logical slot with an old restartlsn. Fix it by running SELECT pgdropreplicationslot('slot_name'); on the publisher, after making sure nothing still needs that slot.