Sub topic 6
Subscribing with CREATE SUBSCRIPTION
This chapter assumes you can run psql as a superuser, that the publisher has wal_level = logical, and that a publication such as orders_pub already exists. It also assumes the publisher accepts connections from the subscriber (pg_hba.conf) and that a role with the REPLICATION attribute and SELECT on the published tables exists. The earlier chapters on configuration and publications cover these steps.
What a subscription is
A subscription is the subscriber-side object that defines one replication link. It stores:
- A connection string to the publisher.
- The names of one or more publications on that publisher.
- The name of a replication slot on the publisher.
- Options that control copying, streaming, and error handling.
The subscriber is an ordinary writable database. It receives row changes and applies them as normal inserts, updates, and deletes. A subscription is not a standby, and the subscriber can hold other tables, indexes, and users of its own.
Creating a subscription
The subscriber must already contain every published table. DDL is not replicated, so you create the tables by hand first.
-- On the subscriber: the table must already exist with compatible columns
CREATE TABLE orders (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
status text NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE SUBSCRIPTION orders_sub
CONNECTION 'host=publisher.example.com port=5432 dbname=shop user=repl_user password=change_me'
PUBLICATION orders_pub;By default this one command does four things:
- It connects to the publisher using the connection string.
- It creates a logical replication slot named after the subscription (
orders_sub). - It registers the subscription in the subscriber's
pg_subscriptioncatalog. - It starts background workers that copy existing rows and then stream new changes.
The caller needs superuser rights, or on PostgreSQL 16 and later membership in pg_create_subscription plus CREATE on the database. On PostgreSQL 16 and later, a non-superuser subscription owner must use a password in the connection string by default.
The connection string is stored in the catalog. The subconninfo column of pg_subscription is readable only by superusers, but treat the password as a stored secret anyway. Use a dedicated replication role with minimal privileges.
What happens behind the command
Each subscription has one apply worker. It applies changes in commit order, one transaction at a time. During the initial copy, extra table synchronization workers run temporarily, one per table, up to max_sync_workers_per_subscription (default 2). Those workers must also fit within max_logical_replication_workers (default 4) on the subscriber. Both limits must also fit inside max_worker_processes (default 8), which is shared with parallel query and other workers. If you subscribe to many tables and see the copy stall, raise these settings. Changing max_worker_processes requires a restart.
The next chapter covers the initial copy in detail. This chapter covers the command and its options.
How rows are matched on the subscriber
The subscriber matches tables by fully qualified name, such as public.orders. It matches columns by name, not position. These rules follow:
- The subscriber table may list columns in a different order.
- The subscriber may have extra columns, as long as they are nullable or have defaults.
- Every column the publisher sends must exist on the subscriber.
- Data types need not be identical. Values travel in text form by default, so each value must be accepted by the subscriber's column type.
- The subscriber table can have different constraints, indexes, and triggers.
Triggers on the subscriber fire only according to session_replication_role. The apply worker runs with replica, so ordinary triggers do not fire for replicated changes unless you enable them with ALTER TABLE ... ENABLE REPLICA TRIGGER or ENABLE ALWAYS TRIGGER.
Common options
Options go in a WITH (...) clause.
| Option | Default | Effect |
|---|---|---|
| `copy_data` | `true` | Copy existing rows before streaming. Set `false` if the data is already on the subscriber. |
| `create_slot` | `true` | Create the slot on the publisher. Set `false` to use a slot you made yourself. |
| `slot_name` | subscription name | Name of the slot on the publisher. `NONE` means no slot is associated. |
| `enabled` | `true` | Start replicating immediately. |
| `connect` | `true` | Connect during the command. `false` implies `enabled`, `create_slot`, and `copy_data` are all false. |
| `synchronous_commit` | `off` | Commit mode used by the apply worker. Affects synchronous replication only if the publisher lists this subscriber in `synchronous_standby_names`. |
| `streaming` | `off` | Stream large in-progress transactions instead of waiting for commit. PostgreSQL 14 and later. |
| `binary` | `false` | Send data in binary format. Faster, but types must match exactly. |
| `disable_on_error` | `false` | Disable the subscription when an apply error occurs. PostgreSQL 15 and later. |
Example with several options:
-- On the subscriber (PostgreSQL 15 or later because of disable_on_error)
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 = true, disable_on_error = true);You can also subscribe to several publications from the same publisher in one subscription: PUBLICATION orders_pub, customers_pub. They share one slot and one apply worker.
Creating the slot yourself
Sometimes the connection from the subscriber cannot create a slot, or you want a slot to exist before you start. Create the slot on the publisher, then attach to it:
-- On the publisher
SELECT pg_create_logical_replication_slot('orders_sub', 'pgoutput');
-- 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
WITH (create_slot = false);The slot must use the pgoutput plugin, and its name must match slot_name. Only one subscription at a time can use a given slot.
Changing a subscription later
ALTER SUBSCRIPTION changes an existing link without recreating it:
-- Pause and resume
ALTER SUBSCRIPTION orders_sub DISABLE;
ALTER SUBSCRIPTION orders_sub ENABLE;
-- Move to a new publisher host (the slot must exist there with the same name)
ALTER SUBSCRIPTION orders_sub
CONNECTION 'host=new-publisher.example.com port=5432 dbname=shop user=repl_user password=change_me';
-- Change which publications are followed
ALTER SUBSCRIPTION orders_sub SET PUBLICATION orders_pub, customers_pub;
-- Pick up tables newly added to a publication
ALTER SUBSCRIPTION orders_sub REFRESH PUBLICATION;ADD PUBLICATION and DROP PUBLICATION change the list one name at a time. Both refresh by default. ALTER SUBSCRIPTION ... REFRESH PUBLICATION copies data for newly added tables by default, controlled by copy_data. If a table is already in sync, leave it out of the refresh by setting copy_data = false. Otherwise the table is copied again and you may see duplicate-key errors.
Inspecting a subscription
Two views show the current state.
-- Configuration
SELECT subname, subenabled, subslotname, subpublications
FROM pg_subscription;
-- Per-table sync state: i = initialize, d = data copy, f = finished copy,
-- s = synchronized, r = ready
SELECT srrelid::regclass AS table_name, srsubstate
FROM pg_subscription_rel;A table in state r is replicating normally. A table that stays in d for a long time is still copying, or its worker is failing and retrying. The subscriber log shows the actual error.
When the subscription breaks
An apply error, such as a unique violation, stops the apply worker. The worker restarts, hits the same change, and fails again. The subscription does not skip the change on its own. Meanwhile the slot on the publisher keeps WAL, because the subscriber has not confirmed it.
With disable_on_error = true, the subscription disables itself after the first error. The loop stops and you can fix the cause. Common causes are a missing table on the subscriber, a row that already exists, or a type that rejects a value. The conflicts chapter covers how to resolve them, including ALTER SUBSCRIPTION ... SKIP.
Dropping a subscription
DROP SUBSCRIPTION orders_sub;This also drops the slot on the publisher, which requires connecting to the publisher. If the publisher is unreachable, the command fails. Detach the slot first, then drop the subscription, then remove the slot by hand once the publisher is back:
-- On the subscriber
ALTER SUBSCRIPTION orders_sub DISABLE;
ALTER SUBSCRIPTION orders_sub SET (slot_name = NONE);
DROP SUBSCRIPTION orders_sub;
-- On the publisher, if the slot is left over
SELECT pg_drop_replication_slot('orders_sub');Dropping a subscription does not delete the replicated tables or their rows. They stay on the subscriber as ordinary tables.
Common mistakes
- Forgetting to create the subscriber table. The subscription is created, but the table sync worker logs an error that the relation does not exist.
- Pointing a subscriber at its own publisher database on the same cluster with the default slot creation. The command hangs, because creating the slot waits for transactions that include the command itself. Create the slot first and use
create_slot = falseandconnect = true, or useconnect = falseand then create the slot and enable manually. - Writing to a replicated table on the subscriber. Nothing prevents it, and a local row can later collide with a replicated one.
- Reusing a slot name for two subscriptions. The second one fails because the slot is already active.
Exercise
You run CREATE SUBSCRIPTION to attach a subscriber to a publisher. The subscriber already holds an exact copy of the published tables, loaded from a backup. Which option do you set so the existing rows are not copied again, and what happens if you leave it at the default?
Show answer
Set copydata = false. With the default copydata = true, each table sync worker copies the existing rows again. Because the rows already exist, the copy fails with duplicate-key errors on tables that have primary keys. Tables without unique constraints would end up with duplicated rows.
Exercise
A subscription has been failing with a unique violation for two hours. What is happening on the publisher, and which option would have limited the damage?
Show answer
The slot for the subscription keeps its restart position, so the publisher retains all WAL generated since the last confirmed position. Disk usage grows for as long as the subscription fails. Creating the subscription with disableonerror = true (PostgreSQL 15 or later) disables it after the first error, which stops the retry loop. You still need to fix the cause or drop the slot, because a disabled subscription keeps its slot and WAL retention continues.