Video in progress

How do streaming (physical) and logical replication differ, and when do you choose which?

Physical (streaming) / Logical — What is copied: the whole cluster, all databases / selected tables; Replica: read-only / writable, can have its own indexes; Major version: must be the same / can differ; DDL: automatic / not copied; Sequences: copied / not copied

📖 Answer

Physical (streaming) Logical
What is copied the whole cluster, all databases selected tables
Replica read-only writable, can have its own indexes
Major version must be the same can differ
DDL automatic not copied
Sequences copied not copied

Physical replication is the basis of HA. If the primary fails, a replica replaces it: it's exactly identical, even the bloat and the indexes.

I've used logical replication for:

  • upgrading a major version with little downtime;
  • moving several tables from one big database to a separate service's database;
  • streaming only the needed tables to an analytics database;
  • CDC like Debezium (which is also built on logical decoding).

The traps of logical: on a table with no PK or REPLICA IDENTITY, UPDATE/DELETE on the publisher fails; migrations have to be applied to both sides by hand; if there's a conflict on the subscriber (a unique violation, say), replication stops and the slot starts accumulating WAL.

-- publisher
CREATE PUBLICATION orders_pub FOR TABLE orders, order_items;
-- subscriber
CREATE SUBSCRIPTION orders_sub
  CONNECTION 'host=old-db dbname=shop user=repl'
  PUBLICATION orders_pub;