Sub topic 10
Handling schema changes
Logical replication copies row changes. It does not copy table definitions. This chapter explains what that means in practice, how to roll out DDL (data definition language: CREATE, ALTER, DROP) safely, and which errors to expect when the two sides drift apart.
This chapter assumes you can already create a publication and a subscription, and that you know what a replication slot and a replica identity are. Earlier chapters in this tutorial cover those.
What is and is not replicated
The publisher decodes row-level INSERT, UPDATE, DELETE, and TRUNCATE operations from the WAL. DDL statements are not part of that stream. When you run ALTER TABLE orders ADD COLUMN note text on the publisher, the subscriber learns nothing about it.
The following are not replicated:
CREATE TABLE,ALTER TABLE,DROP TABLECREATE INDEXand other index changes- Changes to sequences, views, functions, and roles
- Changes to the publication membership itself on the subscriber side. The subscriber must refresh to notice them.
Two consequences follow. First, every schema change must be applied by hand (or by your migration tool) on both sides. Second, the order in which you apply it matters, because the two schemas must stay compatible with the data in flight.
How the subscriber matches columns
The subscriber maps incoming changes to its local table by name, not by position. The rules are:
- The subscriber table must have the same schema-qualified name as the publisher table, unless you create it in a different schema. Both schema and table name must match.
- Columns are matched by name. Column order does not matter.
- The subscriber table may have extra columns, as long as they are nullable or have defaults. They are filled by the default, not by replication.
- The subscriber table must have every column that the publication sends. A missing column causes an apply error.
- Data types do not have to be identical, but the text representation of the value must be accepted by the subscriber's type. For example,
integeron the publisher can go intobiginton the subscriber.
The extra-column rule is the basis for safe schema changes: one side can be ahead of the other, but only in a direction that does not break the stream.
Compatibility by change type
The safe order depends on which side sends data and which side must accept it.
| Change | Apply first on | Then on | Why |
|---|---|---|---|
| Add a nullable column or one with a default | Subscriber | Publisher | The subscriber must accept the new column before the publisher sends it. |
| Drop a column | Publisher | Subscriber | The publisher stops sending it first, so the subscriber is never missing a column it is sent. |
| Add a new table to the publication | Subscriber (create table) | Publisher (add to publication), then refresh the subscription | The target table must exist before the first change arrives. |
| Rename a column | Needs a coordinated plan | A rename looks like a drop plus an add to the other side. See below. | |
| Change a column type | Depends on the types | The new type must accept the text form of the old values and the new ones. | |
| Add a `NOT NULL` column without a default | Avoid | The subscriber cannot fill it for rows it did not send. |
Worked example: adding a column
Start with the orders table from earlier chapters, published by orders_pub and subscribed by orders_sub. You want to add a note column.
Step 1: add the column on the subscriber. Replication keeps running, because the new column is simply not sent yet.
-- On the subscriber
ALTER TABLE orders ADD COLUMN note text;Step 2: add the same column on the publisher. From this point, row changes include note.
-- On the publisher
ALTER TABLE orders ADD COLUMN note text;Step 3: confirm that new rows arrive with the value.
-- On the publisher
INSERT INTO orders (id, customer_id, status, total, note)
VALUES (1001, 42, 'active', 19.99, 'gift wrap');
-- On the subscriber
SELECT id, note FROM orders WHERE id = 1001;If you reverse steps 1 and 2, the publisher starts sending note and the subscriber fails with an error like logical replication target relation "public.orders" is missing replicated column: "note". The apply worker stops, retries, and fails again. Meanwhile the slot holds back WAL on the publisher. Fixing it means adding the column on the subscriber, after which the worker succeeds on its next retry.
Worked example: adding a table
Adding a table is the most common schema change, and it needs three steps in a fixed order.
-- 1. On the subscriber: create the table first
CREATE TABLE order_items (
id bigint PRIMARY KEY,
order_id bigint NOT NULL,
sku text NOT NULL,
qty integer NOT NULL
);
-- 2. On the publisher: create the table and add it to the publication
CREATE TABLE order_items (
id bigint PRIMARY KEY,
order_id bigint NOT NULL,
sku text NOT NULL,
qty integer NOT NULL
);
ALTER PUBLICATION orders_pub ADD TABLE order_items;
-- 3. On the subscriber: pick up the new table
ALTER SUBSCRIPTION orders_sub REFRESH PUBLICATION;REFRESH PUBLICATION makes the subscriber ask the publisher which tables are now published. For each new table, it runs an initial copy and then streams changes, as described in the initial synchronization chapter. Existing tables are not copied again by default.
If you use CREATE PUBLICATION ... FOR ALL TABLES, new tables on the publisher join the publication automatically. You still must create each table on the subscriber and run REFRESH PUBLICATION. Until you do, changes to the new table cannot be applied, and a subscriber missing the table raises an error and stalls the stream.
Removing a table
To stop replicating a table, remove it from the publication and then refresh the subscription.
-- On the publisher
ALTER PUBLICATION orders_pub DROP TABLE order_items;
-- On the subscriber
ALTER SUBSCRIPTION orders_sub REFRESH PUBLICATION;The subscriber's copy of the table stays in place as an ordinary local table. Dropping the table on the subscriber is a separate step, and you should do it only when you are sure that nothing still needs the data.
Renames and type changes
A column rename is the hardest change because a name is how the two sides match. If you rename status to state on one side only, the other side no longer finds the column.
There are two common approaches:
- Add the new column on the subscriber, then on the publisher, backfill it, switch the application to the new column, and later drop the old one using the drop order from the table above. This is slower and keeps replication running throughout.
- Pause the application writes, rename on both sides while the subscription is disabled, and re-enable it. This is quick, but it needs a write pause.
For the second approach, the sequence on the subscriber is:
-- On the subscriber
ALTER SUBSCRIPTION orders_sub DISABLE;
-- Apply the rename on both servers while no writes are happening
ALTER TABLE orders RENAME COLUMN status TO state;
-- On the subscriber, after the publisher is renamed too
ALTER SUBSCRIPTION orders_sub ENABLE;Disabling the subscription does not drop the slot. The publisher keeps WAL while it waits, so keep the pause short.
Type changes follow a similar logic. Widening integer to bigint on the subscriber first is safe, because every old value fits. Widening on the publisher first is also usually safe if the subscriber's type is already wide enough. Narrowing is risky: a value that fits the publisher's type but not the subscriber's causes an apply error. Some ALTER COLUMN ... TYPE changes rewrite the whole table. A rewrite on the publisher produces no row changes in the stream, because the rewrite is not a logical change, but a rewrite on the subscriber takes a lock that blocks the apply worker for as long as it runs.
Primary keys and replica identity changes
A table that publishes updates and deletes needs a replica identity. If you drop or change the primary key on the publisher, the replica identity changes with it. A table left with no usable identity raises an error on the next UPDATE or DELETE.
-- On the publisher: a table that is losing its primary key
ALTER TABLE audit_log REPLICA IDENTITY FULL;The subscriber also needs a way to find rows. It uses a matching primary key, a unique index, or, with REPLICA IDENTITY FULL, all column values, which is slow on large tables. When you change keys, create the index on the subscriber first, so that the apply worker can locate rows efficiently the moment the publisher begins sending the new identity.
Schema change flow
Recovering from a schema mismatch
When the sides drift apart, the apply worker on the subscriber logs an error and retries. The worker does not skip the failing change, so the stream stops at that point. Work through these steps:
- Read the subscriber log for the exact error. It names the relation and the column or constraint involved.
- Fix the subscriber so that it can accept the change. This is usually the correct fix: add the missing column or table, or widen the type.
- Watch the worker recover. The next retry applies the held change and continues.
- If the problem was a missing table in a
FOR ALL TABLESpublication, runREFRESH PUBLICATIONafter you create it.
While the worker is failing, the slot's restart_lsn does not advance. Check retained WAL with the slot query from the monitoring chapter so that the publisher's disk does not fill up while you fix the problem.
Practical habits
- Keep migrations in version control and run them against both servers with the same tool. Log which side has been applied.
- Design changes as expand then contract: add first, switch the application, remove later. This pairs well with the add and drop ordering above.
- Test the migration on a staging pair with the same publication before production.
- Avoid changes that rewrite large tables on the subscriber while replication is running.
Exercise
You need to drop the column note from orders, which is replicated from a publisher to a subscriber. In which order do you run the ALTER TABLE ... DROP COLUMN statements, and what happens if you reverse the order?
Show answer
Drop it on the publisher first, then on the subscriber. After the publisher drops the column, it stops sending it, so the subscriber can still hold the column harmlessly (it is filled with its default or null) until you drop it. If you drop it on the subscriber first, the publisher keeps sending note, the subscriber reports a missing replicated column, the apply worker fails and retries, and the slot retains WAL on the publisher until you fix it.
Exercise
You add a new table shipments to a publication that was created with FOR TABLE. List the steps, in order, that make it replicate.
Show answer
1. Create shipments on the subscriber. 2. Create shipments on the publisher and run ALTER PUBLICATION ... ADD TABLE shipments. 3. On the subscriber, run ALTER SUBSCRIPTION ... REFRESH PUBLICATION, which copies the existing rows and starts streaming later changes.