Sub topic 2
Replication slots and WAL retention
This chapter assumes you can create tables with primary keys, edit postgresql.conf, and run psql. You should also know that the write-ahead log (WAL) is PostgreSQL's record of every change, and that the publisher has wal_level set to logical.
Replication slots and WAL retention
A replication slot is a server-side bookmark that records how far a consumer has read the WAL. The publisher keeps every WAL segment after that position, even if the subscriber is offline. This guarantees that no change is lost, but it means an idle or lagging slot can fill the disk.
-- On the publisher: WAL held back by each slot
SELECT slot_name,
active,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots;Subscribing with CREATE SUBSCRIPTION
A subscription connects to a publication and creates a slot on the publisher unless you say otherwise. The subscriber's tables must exist before you create the subscription, because DDL is not replicated.
-- On the subscriber
CREATE SUBSCRIPTION orders_sub
CONNECTION 'host=publisher.example.com port=5432 dbname=shop user=repl_user password=change_me'
PUBLICATION orders_pub;Initial table synchronization
When a subscription starts, PostgreSQL copies the existing rows of each published table, then applies changes as they arrive. Rows that change during the copy are not lost. Large tables can take a long time to copy, and the slot holds WAL for that whole period.
Replica identity: how updates and deletes find rows
For an update or delete, the publisher must tell the subscriber which row to change. The default replica identity uses the primary key. A table without a primary key cannot publish updates or deletes until you set a replica identity.
-- On the publisher: table without a primary key
ALTER TABLE audit_log REPLICA IDENTITY FULL;REPLICA IDENTITY FULL sends all old column values. It works, but it sends more data and matches slowly on large tables.
Filtering by operation, row, and column
You can limit what a publication sends. The publish option, which chooses insert, update, delete, or truncate, works in all supported versions. Row filters and column lists require PostgreSQL 15 or later.
-- Any supported version: send only inserts
CREATE PUBLICATION orders_inserts_pub
FOR TABLE orders
WITH (publish = 'insert');
-- PostgreSQL 15 or later: row filter and column list
CREATE PUBLICATION active_orders_pub
FOR TABLE orders (id, customer_id, status)
WHERE (status = 'active');> Do not use block quotes in the chapter.
Exercise
Exercise
A table named audit_log has no primary key. Which statement lets updates and deletes replicate, and what is its cost?
Show answer
Run ALTER TABLE audit_log REPLICA IDENTITY FULL on the publisher. It sends all old column values with each update or delete, which adds data volume and makes row matching slower on large tables.