Sub topic 1
Physical versus logical replication
Prerequisites
This chapter assumes you can run psql, edit postgresql.conf, and create tables with primary keys. You should also know that the write-ahead log (WAL) is PostgreSQL's sequential record of every change, written before the change reaches the data files.
Physical versus logical replication
Physical replication copies WAL bytes to a standby server. The standby becomes a byte-for-byte copy of the entire cluster, so it cannot hold a different subset of tables or a different major version.
Logical replication sends row-level changes, such as "insert this row into orders." A subscriber applies those changes to its own tables. Because the stream describes rows, not disk pages, you can replicate selected tables and run a newer major version on the subscriber.
How the WAL becomes a stream of row changes
Each committed change is written to the WAL. A logical decoding plugin reads the WAL and converts it into row changes. PostgreSQL's built-in pgoutput plugin does this for logical replication. A replication slot tracks how far each subscriber has read, so the publisher keeps the WAL the subscriber still needs.
Preparing the publisher and subscriber
Logical decoding requires wal_level set to logical on the publisher. This setting needs a server restart.
-- On the publisher
ALTER SYSTEM SET wal_level = 'logical';
-- After restarting PostgreSQL, confirm the setting
SHOW wal_level;Create a role that the subscriber uses to connect. The role needs the LOGIN and REPLICATION attributes.
-- On the publisher
CREATE ROLE repl_user WITH LOGIN REPLICATION PASSWORD 'change_me';> The tutorial uses the placeholder password change_me in its examples. Replace it before use.
Allow the subscriber's address to connect in pg_hba.conf on the publisher, then reload the configuration.
Publishing tables with CREATE PUBLICATION
A publication is a named list of tables whose changes are sent to subscribers. Create the table on the publisher and add it to a publication.
-- On the publisher
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE PUBLICATION orders_pub FOR TABLE orders;The subscriber must also have a table with the same name and compatible columns. Logical replication does not copy schema changes, so you create that table by hand.
Exercise
Why can a logical subscriber receive only some tables while a physical standby cannot?
Show answer
Physical replication ships all WAL bytes for the whole cluster, so the standby mirrors every table. Logical replication sends only the row changes for tables in a publication, so a subscriber can receive just the tables it needs.