Sub topic 1
Physical versus logical replication
PostgreSQL has two built-in ways to keep a second server in step with a first one. Physical replication copies the write-ahead log (WAL) byte for byte. Logical replication copies the row changes that the WAL describes. This chapter explains the difference, what each approach allows and forbids, and how to tell which one a running system uses. Later chapters cover publications, subscriptions, and operations in detail.
Prerequisites
This chapter assumes you have:
- Basic SQL, including creating tables and primary keys.
- Experience running
psqland editingpostgresql.conf. - A general idea of what the write-ahead log (WAL) is: a sequential record of every change, written before the data files change, so the server can recover after a crash.
- A basic understanding of database roles and privileges.
The shared foundation: the WAL
Every PostgreSQL change is first written to the WAL. Both replication types read that log. They differ in what they do with it.
- Physical replication (also called streaming replication) sends the WAL records to another server. The standby replays them and ends up with the same on-disk pages as the primary.
- Logical replication decodes the WAL into a stream of row-level changes: "insert this row into
orders", "update the row with this key", "delete that row". Another server applies those changes with ordinary SQL-level operations.
A short way to remember it: physical replication copies how the files changed, and logical replication copies what the data changed.
What physical replication gives you
A physical standby is a binary copy of the primary. You usually create it with pg_basebackup, then it connects to the primary and replays WAL continuously.
Properties that follow from this design:
- Whole cluster. Every database, table, index, role, and tablespace is copied. You cannot pick a subset.
- Same major version. The WAL format and page layout change between major versions, so a standby must run the same major version as the primary.
- Same platform. The standby needs a compatible CPU architecture, and in practice the same operating system family and a matching build. Data files are not portable across them.
- Read-only. With
hot_standbyenabled, a standby accepts read queries. It never accepts writes, because the replay process owns the data files. - Everything replicates. DDL, sequences, large objects, and unlogged-table metadata all arrive because the pages themselves arrive. (Unlogged table contents are the exception, since they never reach the WAL.)
- Low overhead. The primary does no extra decoding work.
Physical replication is the standard choice for high availability and failover, and for read replicas that must be exact copies.
What logical replication gives you
Logical replication uses a publish and subscribe model, available since PostgreSQL 10. The source server (the publisher) defines a publication, which is a named set of tables. The target server (the subscriber) defines a subscription that connects to the publisher and receives changes for those tables.
Properties that follow from this design:
- Selective. You choose which tables to publish. From PostgreSQL 15 you can also filter rows and columns.
- Cross-version. Row changes are described in a version-independent form, so publisher and subscriber can run different major versions. This is what makes online major-version upgrades possible.
- Cross-platform. The two servers may differ in operating system, architecture, or storage layout.
- Writable subscriber. The subscriber is an ordinary read-write database. It can hold other tables, extra indexes, and its own data alongside the replicated tables.
- Per-table, per-database. A subscription is tied to one database on each side. Cluster-wide objects such as roles are not copied.
- Not everything replicates. The stream carries
INSERT,UPDATE,DELETE, andTRUNCATE. Schema changes, sequences, and large objects do not travel with it. A later chapter covers these limits.
The writable subscriber is both the main advantage and a common source of trouble. PostgreSQL does not stop you from changing a replicated table on the subscriber. If a local change conflicts with an incoming one, the apply worker stops with an error.
Side-by-side comparison
| Aspect | Physical (streaming) | Logical |
|---|---|---|
| What is shipped | WAL records (page-level changes) | Decoded row changes |
| Scope | Entire cluster | Chosen tables in one database |
| Major versions | Must match | May differ |
| Target is writable | No, read-only standby | Yes |
| DDL replicated | Yes | No |
| Sequences replicated | Yes | No (values are not kept in step) |
| Setup object | Base backup plus `primary_conninfo` | Publication and subscription |
| Typical use | Failover, exact read replicas | Upgrades, data distribution, selective copies |
| Required `wal_level` | `replica` or higher | `logical` on the publisher |
The wal_level setting
The wal_level parameter controls how much information the server writes to the WAL.
minimalwrites only what crash recovery needs. It cannot support replication or WAL archiving.replicais the default. It adds what is needed for archiving and physical replication.logicaladds the extra information needed to decode row changes, such as the old key values of updated and deleted rows.
Because logical is a superset of replica, a publisher with wal_level = logical can still feed physical standbys. The cost is somewhat larger WAL volume. The chapter on preparing the publisher shows how to set it and why it needs a restart.
Replication slots exist in both worlds
Both kinds of replication can use a replication slot. A slot is a marker on the primary that records how far a consumer has read, so the primary keeps WAL the consumer still needs. Slots come in two types, physical and logical, and one catalog view lists them:
SELECT slot_name, slot_type, plugin, database, active
FROM pg_replication_slots;For a logical slot, the plugin column shows the output plugin that formats the changes (pgoutput for built-in logical replication) and database shows the database it decodes. For a physical slot, both columns are empty, because a physical slot is not tied to a database or a plugin.
You can also see who is currently connected and which kind of stream they receive:
SELECT application_name, state, sync_state, replay_lsn
FROM pg_stat_replication;Both physical standbys and logical subscribers appear here as walsender connections. A logical subscriber's application_name defaults to the subscription name, which helps you tell the two apart.
Common mistakes at this stage
These errors come from treating logical replication as "physical replication, but selective."
- Expecting DDL to follow. Adding a column on the publisher does not add it on the subscriber. Replication then fails when a change arrives for a column the subscriber lacks. You must apply schema changes to both sides yourself.
- Treating the subscriber as a read-only copy. Writes to replicated tables on the subscriber can cause conflicts, and the apply worker will stall until you fix them.
- Assuming sequences are copied. Sequence values are not replicated. After switching applications to a subscriber, you must advance the sequences by hand or new inserts will collide with existing keys.
- Ignoring tables without a key. Updates and deletes must identify the target row on the subscriber. A table without a primary key needs a configured replica identity, which a later chapter explains.
- Using logical replication for failover. It does not replicate the whole cluster and is not designed to promote a standby. Physical replication fits that job.
- Forgetting slot retention. An unused slot makes the primary keep WAL indefinitely. This holds for both slot types, and it can fill the disk.
Choosing between them
Choose by asking what you need from the second server.
- You need an exact copy for failover or read scaling: use physical replication.
- You need only some tables, or a target that accepts its own writes: use logical replication.
- You need to move between major versions with little downtime: use logical replication.
- You need to feed another system or consolidate several sources into one database: use logical replication.
The two are not exclusive. A common design runs physical standbys for high availability and adds logical replication for a reporting database or an upgrade. A later chapter returns to these decisions after the mechanics are covered.
Summary
Physical replication copies the WAL as it is and produces an identical, read-only copy of a whole cluster on the same major version. Logical replication decodes the WAL into row changes and applies them to selected tables on a writable subscriber, possibly on a different version or platform. The price of that flexibility is that DDL, sequences, and some other objects are not replicated, and wal_level must be logical on the publisher.
Exercise
A team wants to upgrade a production database from one PostgreSQL major version to the next while keeping downtime to a few seconds. They are considering a physical standby on the new version. Explain why that cannot work and which replication type to use instead. Name one thing they must handle manually before switching applications over.
Show answer
A physical standby replays raw WAL and requires the same major version as the primary, so it cannot run the newer version. Logical replication sends version-independent row changes, so a subscriber on the new version can follow a publisher on the old one, and applications can be switched once it catches up. Because sequence values are not replicated, they must advance the sequences on the new server (for example with setval) before switching. They must also create the schema on the subscriber themselves, because DDL is not replicated.
Exercise
Write a query that lists each replication slot on a server along with whether it is physical or logical, and explain how a logical slot differs in the output from a physical one.
Show answer
SELECT slotname, slottype, plugin, database, active FROM pgreplicationslots; A logical slot has slottype = 'logical', a plugin such as pgoutput, and a database name. A physical slot has slottype = 'physical', and its plugin and database columns are empty because it is not tied to a database or output plugin.