Sub topic 7
Initial table synchronization
This chapter covers what happens between running CREATE SUBSCRIPTION and the moment the subscriber starts applying live changes. It assumes you have already created a publication and a subscription, understand replication slots and WAL retention, and can read pg_stat_* views in psql.
Why an initial copy is needed
A replication slot streams only changes made after the slot was created. If the publisher's orders table already holds ten million rows, those rows never appear in the change stream. The subscriber needs a starting copy of them. PostgreSQL does this automatically unless you tell it not to.
The difficulty is consistency. The copy takes time, and the publisher keeps accepting writes while it runs. PostgreSQL has to join the copied snapshot to the change stream with no gaps and no duplicates. It does this with one slot per table for the copy phase, as described below.
What happens during CREATE SUBSCRIPTION
With default options, the subscriber does the following:
- Connects to the publisher and creates the main slot, named after the subscription.
- Records every table in the publication in the catalog
pg_subscription_rel, with statei(initialize). - Starts the main apply worker. The apply worker launches one table synchronization worker (tablesync worker) per table, within the worker limits described later.
- Each tablesync worker creates its own temporary slot on the publisher. The slot's exported snapshot defines the point in time that the copy reflects.
- The worker runs
COPYfor its table inside that snapshot, then replays changes from its slot until it reaches the apply worker's position. - The table switches to normal streaming through the main slot.
The states in pg_subscription_rel.srsubstate are:
| State | Name | Meaning |
|---|---|---|
| `i` | initialize | The table is registered. Copying has not started. |
| `d` | data is being copied | A tablesync worker is running `COPY`. |
| `f` | finished table copy | The copy is done. The worker is catching up on changes. |
| `s` | synchronized | The tablesync worker has caught up with the apply worker. |
| `r` | ready | The main apply worker now handles the table. |
You only need the states i, d, and r for day-to-day checks. f and s are brief.
Watching the copy
Start with the per-table state on the subscriber:
-- On the subscriber
SELECT c.relname, sr.srsubstate
FROM pg_subscription_rel AS sr
JOIN pg_class AS c ON c.oid = sr.srrelid
ORDER BY c.relname;The initial synchronization is finished when every row shows r. A table stuck at i is usually waiting for a free worker. A table stuck at d is either copying a large table or failing and retrying.
To see how far a running COPY has progressed, query the progress view (PostgreSQL 14 and later):
-- On the subscriber
SELECT relid::regclass AS table_name,
command,
tuples_processed,
pg_size_pretty(bytes_processed) AS bytes_processed
FROM pg_stat_progress_copy;pg_stat_subscription also lists workers. A tablesync worker has a non-null relid. The apply worker has a null relid.
Worker limits control the speed
Three settings determine how many tables copy in parallel:
| Setting | Default | Role |
|---|---|---|
| `max_sync_workers_per_subscription` | 2 | Maximum tablesync workers for one subscription. |
| `max_logical_replication_workers` | 4 | Total pool for apply and tablesync workers across all subscriptions. |
| `max_worker_processes` | 8 | Overall background worker pool. Logical replication workers draw from it. |
With the defaults, a 50-table publication copies two tables at a time. Each worker copies one table with one COPY stream, so a single huge table is not split across workers. To speed up the sync, raise the limits on the subscriber, from the outside in:
-- On the subscriber (all three require a restart except where noted)
ALTER SYSTEM SET max_worker_processes = 16;
ALTER SYSTEM SET max_logical_replication_workers = 8;
ALTER SYSTEM SET max_sync_workers_per_subscription = 4;max_sync_workers_per_subscription can be applied with a reload. The other two need a restart. Each tablesync worker also holds a connection to the publisher, so check max_connections and max_wal_senders on the publisher too.
The copy_data option
copy_data is a subscription option and defaults to true. It decides whether existing rows are copied. It is accepted by CREATE SUBSCRIPTION, ALTER SUBSCRIPTION ... REFRESH PUBLICATION, and ALTER SUBSCRIPTION ... ADD PUBLICATION and SET PUBLICATION (when they refresh).
-- On the subscriber: skip the initial copy for a table that is already loaded
CREATE SUBSCRIPTION orders_sub
CONNECTION 'host=publisher.example.com port=5432 dbname=shop user=repl_user password=change_me'
PUBLICATION orders_pub
WITH (copy_data = false);Use copy_data = false only when the subscriber already holds exactly the data the publisher had when the slot was created. If it does not, the subscriber ends up permanently missing or diverging from the publisher, and PostgreSQL does not detect that. Two typical safe cases:
- A new table with no rows on the publisher yet.
- A subscriber loaded from a dump taken at the same moment the slot was created, for example with a slot you created yourself and a snapshot exported from it.
The same option matters when you add a table later:
-- On the subscriber, after creating order_items by hand
ALTER SUBSCRIPTION orders_sub REFRESH PUBLICATION WITH (copy_data = true);REFRESH PUBLICATION adds new tables in state i, so they go through the same copy process as the original tables.
What the copy includes and excludes
- Row filters and column lists. The initial copy honors them. A publication with
WHERE (status = 'active')copies only active rows. A column list copies only those columns. Both need PostgreSQL 15 or later. - Publication operations. The
publishoption limits which changes are streamed, but it does not limit the initial copy. A publication withpublish = 'insert'still copies all existing rows. - Existing rows on the subscriber. The copy does not truncate the target table. If the subscriber table already contains rows,
COPYruns into primary key conflicts or silently adds duplicates in a table with no unique constraint. - Sequences and DDL. Neither is copied. Create the table definitions first, and set sequence values yourself before you promote a subscriber.
PostgreSQL 16 added a binary subscription option that also applies to the initial copy. If you use it, the column types on both sides must match closely.
Side effects on the publisher
The initial copy is not free for the publisher.
- Held-back WAL. The main slot starts retaining WAL as soon as it is created. A long sync keeps all that WAL on disk until the apply worker catches up.
- Held-back vacuum. Each tablesync slot pins a snapshot while
COPYruns. Long copies prevent vacuum from removing dead rows newer than that snapshot, which can cause table bloat on busy tables. - Load. A full sequential read of each table competes with production queries.
Plan large initial syncs for a quiet period, and watch pg_replication_slots as you did in the monitoring chapter. Tablesync slots have generated names that start with pg_, followed by the subscription OID and the table OID. They are dropped automatically when the table reaches r.
When synchronization fails
A tablesync worker that hits an error rolls back its transaction and exits. The apply worker then starts it again after a delay. The copy restarts from the beginning of that table, not from where it stopped, and the temporary slot is recreated.
The most common causes:
- The table is missing on the subscriber, or a column has a different name or an incompatible type.
- A unique violation, because the subscriber table already contained rows.
- A permissions problem. The subscription owner needs
INSERT(and for updates,UPDATE,DELETE, andSELECT) on the target table. On the publisher, the replication role needsSELECTon the table. - A dropped or missing slot on the publisher.
The error is in the subscriber's server log, not in a system view. Fix the cause and the worker succeeds on its next retry. You do not need to recreate the subscription. If the retries leave a mess, such as extra rows from a partial earlier load, truncate the subscriber table. The next retry copies the data again.
A checklist for a clean initial sync
- On the subscriber, create every target table with compatible columns and no leftover rows.
- Confirm the replication role can read the tables on the publisher.
- Check worker limits against the number of tables.
- Create the subscription.
- Poll
pg_subscription_reluntil every table isr. - Watch
pg_replication_slotson the publisher and the subscriber log while it runs.
Exercise
You create a subscription on a subscriber that already contains a full copy of the table orders, loaded from a dump taken last week. You leave copy_data at its default. What is likely to happen, and how would you avoid it?
Show answer
The tablesync worker runs COPY into a table that already has rows, so it fails with duplicate key errors on the primary key and keeps retrying while the publisher retains WAL. Avoid it by truncating the subscriber table before creating the subscription so the copy starts clean. Use copy_data = false only if the subscriber data exactly matches the publisher at the moment the slot was created, which a week-old dump does not.
Exercise
A publication contains 40 tables. The subscriber uses the default worker settings. Roughly how many tables copy at once, and which setting do you raise first to copy more in parallel?
Show answer
Two at a time, because maxsyncworkerspersubscription defaults to 2. Raise that setting first. Then make sure maxlogicalreplicationworkers and maxworker_processes leave room for the extra workers, and that the publisher has enough connections and WAL senders.