PostgreSQL 17/18: Physical vs Logical Replication

Updated

PostgreSQL physical and logical replication illustration

Use physical (streaming) replication when you want a failover target: it copies the whole cluster byte-for-byte, the standby is strictly read-only, and both servers must run the same major version. Use logical replication when you want some tables on a writable server, possibly on a different major version. The two setups are three commands each:

# physical: standby is a clone of the entire cluster
pg_basebackup -h primary -p 5432 -U postgres -D /path/to/standby -R -X stream -c fast

# logical: publisher picks tables, subscriber pulls them
psql -c "CREATE PUBLICATION hw_pub FOR TABLE hw_customers, hw_audit;"          # on publisher
psql -c "CREATE SUBSCRIPTION hw_sub CONNECTION 'host=... dbname=postgres'
         PUBLICATION hw_pub;"                                                   # on subscriber

Everything in the physical and logical sections below was run on PostgreSQL 17.10 on 2026-08-10, re-confirmed on 17.11 on 2026-08-17, across three initdb clusters: 55501 (primary/publisher), 55502 (physical standby), 55503 (logical subscriber). The pg_createsubscriber section used its own clusters on 17.11. The exception is every passage marked 18.6, run on 15 October 2026 on separate PostgreSQL 18.6 clusters. Output is pasted unedited.

Physical replication: everything, read-only

After pg_basebackup -R writes standby.signal and primary_conninfo, starting the standby with hot_standby = on gives you a queryable replica. It refuses every write, including DDL:

$ psql -p 55502 -c "SELECT pg_is_in_recovery();"
 pg_is_in_recovery
-------------------
 t

$ psql -p 55502 -c "INSERT INTO hw_orders (item, qty) VALUES ('nope', 1);"
ERROR:  cannot execute INSERT in a read-only transaction

$ psql -p 55502 -c "CREATE TABLE hw_x (i int);"
ERROR:  cannot execute CREATE TABLE in a read-only transaction

Because it replays WAL rather than row changes, schema changes arrive for free. A CREATE TABLE and an ALTER TABLE ... ADD COLUMN on the primary appeared on the standby with nothing done there:

$ psql -p 55502 -c "SELECT * FROM hw_ddl_proof;" -c "\d hw_orders"
 id |        note
----+--------------------
  1 | created on primary

                             Table "public.hw_orders"
 Column  |  Type   | Collation | Nullable |                Default
---------+---------+-----------+----------+---------------------------------------
 id      | integer |           | not null | nextval('hw_orders_id_seq'::regclass)
 item    | text    |           |          |
 qty     | integer |           |          |
 shipped | boolean |           |          | false

Progress shows on the primary in pg_stat_replication (state | streaming, sync_state | async by default). The trade is that “everything” is not negotiable: the standby held all 5 public tables and the same database list as the primary. What this page does not cover is how much WAL the primary must hold on to for that standby — wal_keep_size against a replication slot is the decision that bites once a replica disconnects.

Logical replication: some tables, writable — and four ways it breaks

The subscriber only received the 3 published tables out of 5, and hw_orders — never added to the publication — simply does not exist there. That selectivity is the point. But the flexibility is paid for in four failure modes.

1. The schema is yours to create and yours to keep in sync. The docs are blunt: “The database schema and DDL commands are not replicated.” Add a column on the publisher and insert into it, and the apply worker dies — then restarts and dies again, every five seconds, forever:

2026-08-10 13:03:49.750 CDT [85852] ERROR:  logical replication target relation "public.hw_audit" is missing replicated column: "severity"
2026-08-10 13:03:49.750 CDT [85852] CONTEXT:  processing remote data for replication origin "pg_16398" during message type "INSERT" in transaction 745, finished at 0/30384A0
2026-08-10 13:03:49.752 CDT [78125] LOG:  background worker "logical replication apply worker" (PID 85852) exited with exit code 1
2026-08-10 13:03:49.753 CDT [17447] LOG:  logical replication apply worker for subscription "hw_sub" has started
2026-08-10 13:03:49.766 CDT [17447] ERROR:  logical replication target relation "public.hw_audit" is missing replicated column: "severity"

One broken table halts the whole subscription. A row inserted into hw_customers — a healthy, unrelated table — never arrived while hw_audit was stuck. Running the same ALTER TABLE on the subscriber cleared it and both tables caught up. Watch pg_stat_subscription_stats.apply_error_count; it climbed to 12 during this test.

2. Sequences are not replicated. “Sequence data is not replicated.” After copying 3 rows, the publisher’s sequence was at 3 and the subscriber’s was still at 1:

-- publisher:                    -- subscriber:
 last_value | is_called           last_value | is_called
------------+-----------          ------------+-----------
          3 | t                            1 | t

So the first local INSERT on the subscriber failed with duplicate key value violates unique constraint "hw_customers_pkey". After setval() it worked. Plan for this before any failover to a logical subscriber.

3. A table with no primary key stops accepting UPDATE and DELETE the moment you publish it. This is the one that bites in production, and it errors on the publisher, not the replica:

$ psql -p 55501 -c "UPDATE hw_nopk SET price = 9.99 WHERE sku = 'a';"
ERROR:  cannot update table "hw_nopk" because it does not have a replica identity and publishes updates
HINT:  To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.

$ psql -p 55501 -c "DELETE FROM hw_nopk WHERE sku = 'b';"
ERROR:  cannot delete from table "hw_nopk" because it does not have a replica identity and publishes deletes

INSERT still worked, which is why this often ships to production undetected. ALTER TABLE hw_nopk REPLICA IDENTITY FULL; fixed both immediately — but FULL means every UPDATE and DELETE ships the entire old row and the subscriber matches it with a sequential scan. A primary key is the better answer.

4. Writing to the subscriber creates conflicts PostgreSQL will not resolve for you. A row inserted locally on the subscriber took id 4; when the publisher later replicated its own id 4, the apply worker entered the same permanent restart loop:

ERROR:  duplicate key value violates unique constraint "hw_customers_pkey"
DETAIL:  Key (id)=(4) already exists.
CONTEXT:  processing remote data for replication origin "pg_16398" during message type "INSERT" for replication target relation "public.hw_customers" in transaction 746, finished at 0/3038588

Replication only resumed after a human deleted the offending local row. On PostgreSQL 18.6, which I ran on 15 October 2026, the same collision is logged with different words, so an alert that greps for duplicate key stays silent. The DETAIL line also shows both rows:

ERROR:  conflict detected on relation "public.hw_customers": conflict=insert_exists
DETAIL:  Key already exists in unique index "hw_customers_pkey", modified in transaction 766.
	Key (id)=(4); existing local row (4, local-only-row); remote row (4, dave).
CONTEXT:  processing remote data for replication origin "pg_16399" during message type "INSERT" for replication target relation "public.hw_customers" in transaction 758, finished at 0/3049148

18 counts each conflict type separately in pg_stat_subscription_stats, and the documentation says a conflict that causes an apply error is counted in both apply_error_count and the matching confl_* column. On a fresh pair of 18.6 clusters with a one-second retry interval, the query below returned 9 and 9. Both counters rise by one on every retry, so the figure depends on how long the conflict stands (a second run returned 14 and 14):

SELECT subname, apply_error_count, confl_insert_exists FROM pg_stat_subscription_stats;

 subname | apply_error_count | confl_insert_exists
---------+-------------------+---------------------
 hw_sub  |                 9 |                   9

The behavior is unchanged: the apply worker keeps restarting and waits for a human, and replication resumed once I deleted the local row.

PostgreSQL 17 added a third path: converting a standby into a subscriber

pg_createsubscriber (new in PostgreSQL 17) turns an existing physical standby into a logical subscriber in place — no initial copy needed, it’s already a full clone. I stopped the standby and ran it:

$ pg_createsubscriber --verbose --pgdata=$BASE/sby \
    --publisher-server="host=127.0.0.1 port=55531 user=postgres dbname=postgres" \
    --subscriber-username=postgres --database=postgres --socketdir=$BASE
...
pg_createsubscriber: modifying system identifier of subscriber
pg_createsubscriber: running pg_resetwal on the subscriber
pg_createsubscriber: Done!

--dry-run narrates the whole plan but changes nothing: I confirmed standby.signal survived it and the node came back up as an ordinary standby. What the real run doesn’t fix: a local insert on the converted node got id=4 — the cloned sequence value — and the primary’s next insert wanted the same id, hitting the identical wall from the section above:

ERROR:  duplicate key value violates unique constraint "t_pkey"
DETAIL:  Key (id)=(4) already exists.

Deleting the row unstuck it, same fix as before. I ran the same conversion on 18.6 on 15 October 2026: the dry run, the real run and the writable converted node (id=4) behaved as on 17, and the collision appeared as conflict=insert_exists instead of duplicate key. The tool also only works within one major version — for cross-version, CREATE SUBSCRIPTION above is still it.

Multi-master, storage requirements and SQL text

Built-in logical replication in PostgreSQL 17 is not multi-master, and the log above is why: it is one-way and has no conflict resolution. The subscriber-local row never travelled back to the publisher, and the first collision stopped replication until it was fixed by hand. Multi-master on PostgreSQL requires an external system (BDR, pglogical, Bucardo); it is not something CREATE SUBSCRIPTION gives you.

Physical replication needs a full second copy of the cluster. Limited storage is an argument against it, not for it.

The default pgoutput plugin for logical decoding streams a binary row-change protocol, not SQL text — which is why the subscriber’s column list has to match, and why the failure above is “missing replicated column” rather than a syntax error.

What was and wasn’t tested

On 15 October 2026 I ran PostgreSQL 18.6 beside 17.11 on one machine. Logical replication from a 17.11 publisher to an 18.6 subscriber worked: the initial sync copied 5 rows and a row inserted afterwards streamed across. A data directory taken from 17 with pg_basebackup would not start under 18.6:

FATAL:  database files are incompatible with server
DETAIL:  The data directory was initialized by PostgreSQL version 17, which is not compatible with this version 18.6 (Homebrew).

I did not run a streaming standby across versions. For that, and for hardware, I am quoting the documentation, not measuring: “In general, log shipping between servers running different major PostgreSQL release levels is not possible” and “In any case the hardware architecture must be the same — shipping from, say, a 32-bit to a 64-bit system will not work.” Logical replication lists “Replicating between different major versions of PostgreSQL” as a supported use case, which is what makes it the standard tool for near-zero-downtime major upgrades.

The script reproducing the physical and logical sections builds its own three clusters and checks 33 assertions: physical-vs-logical-replication.sh, PASS=33 FAIL=0 SKIP=2 on 17.10 in 2026-08-10 and again, unchanged, on 17.11 (re-confirmed 15 October 2026). The pg_createsubscriber section has its own reproducer, physical-vs-logical-replication-createsubscriber.sh — PASS=12 FAIL=0 SKIP=0 on 17.11, also re-confirmed 15 October 2026. Both scripts target 17 and grep for 17’s wording; the 18.6 results above come from my runs of the same scenarios with 18’s binaries.

Synchronous versus asynchronous is a separate axis from physical versus logical, set by synchronous_commit and synchronous_standby_names; every run above was asynchronous, the default.

Photo of author
Sudhir P. founded HeatWare.com in 1999 and has built and operated it full-stack ever since; it is now used by more than 88,000 people. He writes here about the PostgreSQL, MySQL, Linux and DevOps work that keeps it running. Articles are rewritten only after the commands in them have actually been run, and the verification scripts are published alongside them so anyone can check the claims. Reach him at blog@heatware.net.