Skip to content

Set Up Logical Replication

Replicate selected tables between a Managed PostgreSQL service and another PostgreSQL server, in either direction, with PostgreSQL publications and subscriptions.

When to Use It

Logical replication sends the row changes of the tables you choose from a publisher to a subscriber. The two servers can run different major versions. Use it when you need:

  • a subset of tables rather than whole databases,
  • replication out of Managed PostgreSQL into another PostgreSQL server,
  • a long-lived replication link rather than a one-time migration.

To move a whole database into Managed PostgreSQL and cut over, use Migrate to Managed PostgreSQL, which sets up the replication for you. For a read-only copy of an entire service, use read replicas.

The example on this page replicates the tables orders and customers of defaultdb from a publisher to a subscriber. Either side can be a Managed PostgreSQL service.

Prerequisites

  • wal_level set to logical on the publisher. Managed PostgreSQL services run with wal_level = logical. On a self-managed publisher, set it and restart PostgreSQL.
  • A free replication slot on the publisher for each subscription.
  • A network path from the subscriber to the publisher: the subscriber opens the connection.
  • psql and pg_dump, see Connect with psql.

Prepare the Publisher

Check WAL Level and Free Slots

SHOW wal_level;

SELECT current_setting('max_replication_slots')::int AS max_slots,
       count(*) AS used_slots
FROM pg_replication_slots;

On a Managed PostgreSQL service, one slot is always in use: pghoard_local belongs to the backup system. Leave it alone.

Create a Replication User

On a Managed PostgreSQL publisher, create a service user with the replication attribute:

exo dbaas user create SERVICE_NAME USERNAME -z ZONE --pg-allow-replication

Parameters:

  • SERVICE_NAME: name of the publisher service, for example my-postgresql.
  • USERNAME: name of the new user, for example replicator.
  • ZONE: zone of the service, for example ch-gva-2.

The CLI sets the attribute only at creation. To change it on an existing user, use the API:

echo '{"allow-replication":true}' | \
  exo api update-dbaas-postgres-allow-replication SERVICE_NAME USERNAME -z ZONE

Read the password of the user, which the subscription needs:

exo dbaas user reveal-secrets SERVICE_NAME USERNAME -z ZONE

The user also needs to read the published tables, for the initial copy. Connected to the publisher as avnadmin:

GRANT SELECT ON orders, customers TO replicator;

Without this grant the subscription is created, but the initial copy fails in a loop and the tables on the subscriber stay empty.

Create the Publication

CREATE PUBLICATION pub_orders FOR TABLE orders, customers;

By default a publication sends INSERT, UPDATE, DELETE and TRUNCATE. Restrict it with, for example, WITH (publish = 'insert,update,delete').

List what the publication covers:

SELECT pubname, schemaname, tablename FROM pg_publication_tables;

Give Each Table a Replica Identity

A published table needs a replica identity so that updates and deletes can be matched on the subscriber. A primary key is enough. On a published table without one, the publisher refuses the statement:

ERROR:  cannot update table "events" because it does not have a replica identity and publishes updates

Find the tables without a primary key before you publish them:

SELECT c.relname
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
  AND n.nspname = 'public'
  AND NOT EXISTS (
    SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary
  );

Then add a primary key, or set the identity to the whole row:

ALTER TABLE events REPLICA IDENTITY FULL;

Prepare the Subscriber

Copy the Schema

Logical replication copies rows, not table definitions. Create the tables on the subscriber first, from the publisher’s schema:

pg_dump --schema-only --no-publications "PUBLISHER_URI" \
  -t orders -t customers > schema.sql
psql "SUBSCRIBER_URI" -f schema.sql

Parameters:

  • PUBLISHER_URI, SUBSCRIBER_URI: connection URIs of the two servers. For a Managed PostgreSQL service, read it with exo dbaas show SERVICE_NAME -z ZONE --uri.

Allow the Subscriber Through the Publisher’s IP Filter

When the publisher is a Managed PostgreSQL service, its IP filter must allow the subscriber. Otherwise the subscription fails after a long wait with Connection timed out. A Managed PostgreSQL subscriber connects from the public IP address its hostname resolves to:

dig +short "$(exo dbaas show SUBSCRIBER_SERVICE -z ZONE -O json | jq -r .pg.uri_params.host)"

Add that address to the publisher’s filter, together with the blocks already in it, because the list you set replaces the previous one:

exo dbaas update PUBLISHER_SERVICE -z ZONE -f --pg-ip-filter EXISTING_CIDRS,SUBSCRIBER_IP/32

Parameters:

  • SUBSCRIBER_SERVICE, PUBLISHER_SERVICE: names of the two services.
  • EXISTING_CIDRS: the blocks already in the publisher’s filter, comma-separated.
  • SUBSCRIBER_IP: the address returned by dig.

The address belongs to the node of the subscriber and changes when that node is replaced, for example by a plan change or maintenance. Check it again afterwards. See Restrict connections.

When the publisher is a server you run, allow the same address in its firewall and in pg_hba.conf.

Create the Subscription

The connection string must contain a password and request TLS:

host=PUBLISHER_HOST port=PUBLISHER_PORT dbname=defaultdb user=replicator password=PASSWORD sslmode=require

Parameters:

  • PUBLISHER_HOST, PUBLISHER_PORT: host and port of the publisher. For a Managed PostgreSQL publisher, use the pg component, not the PgBouncer port.
  • PASSWORD: the password of the replication user.

Without a password, the subscriber refuses the statement: password is required / Non-superusers must provide a password in the connection string. A Managed PostgreSQL publisher refuses an unencrypted connection: with sslmode=disable the error is no pg_hba.conf entry for host ..., no encryption.

On PostgreSQL 16 and Later

avnadmin has the privileges of the pg_create_subscription role and can run the standard statement, connected to the subscriber database:

CREATE SUBSCRIPTION sub_orders
CONNECTION 'CONNECTION_STRING'
PUBLICATION pub_orders
WITH (slot_name = 'sub_orders', copy_data = true);

Parameters:

  • CONNECTION_STRING: the connection string above.

CREATE SUBSCRIPTION creates the replication slot on the publisher and, with copy_data = true, copies the current content of the tables before streaming changes. With copy_data = false, only changes made from now on are replicated. Naming the slot after the subscription makes an abandoned slot easy to trace.

To subscribe as another service user, that user needs pg_create_subscription and CREATE on the database. Check with:

SELECT pg_has_role(current_user, 'pg_create_subscription', 'USAGE') AS can_subscribe,
       has_database_privilege(current_user, current_database(), 'CREATE') AS can_create;

On PostgreSQL 15

On PostgreSQL 15, CREATE SUBSCRIPTION answers must be superuser to create subscriptions. Use the aiven_extras extension, which creates the subscription with elevated rights. Install it once per database:

CREATE EXTENSION aiven_extras;

Then create the subscription:

SELECT aiven_extras.pg_create_subscription(
  'sub_orders',          -- subscription name
  'CONNECTION_STRING',   -- connection string to the publisher
  'pub_orders',          -- publication on the publisher
  'sub_orders',          -- replication slot to create on the publisher
  TRUE,                  -- create the slot
  TRUE);                 -- copy the existing rows

A subscription created this way is owned by postgres, so ALTER SUBSCRIPTION and DROP SUBSCRIPTION fail with must be owner of subscription. Manage it with the other functions of the extension, shown in the sections below. On PostgreSQL 16 and later these functions still work but pg_create_subscription prints a deprecation warning: use the standard statements.

Check That Replication Runs

On the subscriber:

SELECT subname, subenabled, subslotname FROM pg_subscription;

SELECT subname, pid, received_lsn, last_msg_receipt_time FROM pg_stat_subscription;

SELECT srrelid::regclass AS table_name, srsubstate FROM pg_subscription_rel;

SELECT subname, apply_error_count, sync_error_count FROM pg_stat_subscription_stats;
  • subenabled is t, and pid is not empty: the apply worker runs. An empty pid on an enabled subscription means the worker fails and restarts.
  • srsubstate is r (ready) for every table once the initial copy is done. A table that stays in d (copying) with a growing sync_error_count usually means the replication user cannot read it.
  • A growing apply_error_count means the changes received cannot be applied, for example after a column was added on the publisher only.

The subconninfo column of pg_subscription is not readable by avnadmin, because it holds the password. aiven_extras.pg_list_all_subscriptions() returns it, in clear text.

On the publisher, the subscription appears as a replication connection:

SELECT application_name, state,
       pg_wal_lsn_diff(sent_lsn, replay_lsn) AS outstanding_bytes
FROM pg_stat_replication
WHERE application_name <> 'pghoard';

The pghoard row, present on every service, is the backup system.

Watch the Replication Slots

A replication slot makes the publisher keep every WAL segment its subscriber has not confirmed. If the subscriber stops reading, the WAL piles up on the publisher’s disk until it is full. Check on the publisher:

SELECT slot_name, slot_type, active,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained_wal
FROM pg_replication_slots
ORDER BY pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn) DESC;

During the initial copy, temporary slots named pg_..._sync_... appear next to the subscription slot and disappear when the copy completes.

Caution

A logical slot with active = f and a growing retained_wal fills the disk. Restart the subscriber, or drop the slot when the subscription is gone. Never drop pghoard_local: it belongs to the backup system.

See Disk usage for the other causes of disk growth.

Change the Subscription

Pause and resume a subscription, on PostgreSQL 16 and later:

ALTER SUBSCRIPTION sub_orders DISABLE;
ALTER SUBSCRIPTION sub_orders ENABLE;

A table added to the publication later is not replicated until the subscription is refreshed. Create the table on the subscriber, then:

ALTER SUBSCRIPTION sub_orders REFRESH PUBLICATION WITH (copy_data = true);

For a subscription created through aiven_extras on PostgreSQL 15:

SELECT aiven_extras.pg_alter_subscription_disable('sub_orders');
SELECT aiven_extras.pg_alter_subscription_enable('sub_orders');
SELECT aiven_extras.pg_alter_subscription_refresh_publication('sub_orders', TRUE);

The second argument of the refresh function is copy_data.

Remove a Subscription

Dropping a subscription also drops its slot on the publisher:

DROP SUBSCRIPTION sub_orders;

If the slot no longer exists on the publisher, or the publisher cannot be reached, the statement fails, for example with could not drop replication slot "sub_orders" on publisher. Detach the slot first, then drop the subscription:

ALTER SUBSCRIPTION sub_orders DISABLE;
ALTER SUBSCRIPTION sub_orders SET (slot_name = NONE);
DROP SUBSCRIPTION sub_orders;

For a subscription created through aiven_extras, use SELECT aiven_extras.pg_drop_subscription('sub_orders');, or SELECT aiven_extras.pg_drop_subscription('sub_orders', FALSE); to keep the slot on the publisher.

Then remove any slot left on the publisher. On a Managed PostgreSQL publisher, avnadmin can drop it:

SELECT pg_drop_replication_slot('sub_orders');

What Logical Replication Does Not Copy

  • Schema changes. A column added on the publisher only stops the replication: the subscriber cannot apply the new rows, and resumes once the column exists on its side too. Apply schema changes to the subscriber first, then to the publisher.
  • Sequence values. The sequences on the subscriber stay where they were. Before writing to the subscriber, set each sequence with setval().
  • Large objects.

The full list is in the PostgreSQL restrictions on logical replication.

Warning

A major version upgrade from PostgreSQL 15 or 16 removes the replication slots of a publisher and disables the subscriptions of a subscriber. Plan to re-create the subscriptions after the upgrade.

Related Pages

Last updated on