PostgreSQL Logical Replication, Part 1: Setting Up a Source and Destination Between Two Servers


Logical replication copies row-level changes of selected tables from one PostgreSQL database to another, so you can replicate part of a database instead of the whole cluster. Physical replication copies every byte of the cluster. Logical replication copies only the data changes (INSERT, UPDATE, DELETE and TRUNCATE) of the tables you choose, and it does so while both servers stay fully read-write.
That gives you:
- Selective replication: replicate chosen tables, or one database out of many, not the whole cluster
- Zero-downtime major version upgrades: the source and destination can run different major versions
- Live migrations: move data between servers, clouds or operating systems with a short cutover
- Read-write destination: the destination is a normal database. It can have its own extra tables, indexes and users
- Data distribution and consolidation: send one table to many databases, or gather tables from many databases into one reporting database
- Change data capture: the same logical decoding mechanism feeds tools such as Debezium
This is Part 1 of a two-part series. It takes a standalone PostgreSQL server and sets up logical replication of one database to a second server, step by step, with the outputs you should expect at each stage. It ends with a working, verified replication. Part 2 covers running it in production: schema changes, sequences, slot monitoring and conflicts.
Terminology used in this post: the source is the server that holds the data and sends the changes. PostgreSQL calls it the publisher. The destination is the server that receives the changes. PostgreSQL calls it the subscriber. Every step below says which server to run it on.
1. How Logical Replication Works
Logical replication reads the same WAL as physical replication, but it decodes it into row changes and replays them as ordinary SQL-level operations on the destination. It uses a publish and subscribe model:
- Every change on the source is written to the WAL first.
- A publication on the source defines which tables (and which operations) are published.
- A subscription on the destination connects to the source and creates a logical replication slot there.
- A walsender process on the source decodes the WAL using the built-in pgoutput plugin and sends only the changes of published tables.
- An apply worker on the destination receives the changes and applies them as normal transactions, in commit order.
- When a table is first added, a table synchronization worker copies its existing rows (the initial snapshot) and then hands over to the apply worker.
The destination is not a byte-for-byte copy. Its tables must already exist (logical replication does not create them), and they are matched to the source's tables by schema and table name.
1.1 Flow diagram
Figure 1 shows the flow end to end. The left lane is the source, the right lane is the destination, and the middle column shows what travels between them on port 5432.
Figure 1: Logical replication flow from the source to the destination
1.2 Physical vs logical replication
1.3 Key terms
- Publication: a named set of tables on the source, created with CREATE PUBLICATION.
- Subscription: a connection from the destination to one or more publications, created with CREATE SUBSCRIPTION.
- Logical replication slot: a source-side bookmark that retains WAL until the destination has confirmed it. By default there is one slot per subscription, with the same name as the subscription.
- Replica identity: the columns the source uses to identify a row in UPDATE and DELETE messages. Normally the primary key.
2. Environment and Prerequisites
This walkthrough replicates one database, appdb, from an existing standalone server to a new server.
The examples use PostgreSQL 16 on Ubuntu, and two sample tables, customers and orders, in the public schema.
Requirements
- PostgreSQL 10 or later on both servers (this post uses features from 13 to 16, noted where they apply). The major versions may differ, and the destination should normally be the same or newer
- Network access from the destination to the source on port 5432
- A primary key (or another replica identity) on every table that receives UPDATE or DELETE
- Enough disk on the destination for the data you replicate, plus its own WAL
- Disk headroom on the source for WAL retained by the replication slot
- The same extensions that your tables depend on (for data types and functions) installed on the destination
What logical replication does not replicate
- DDL: CREATE, ALTER and DROP of tables, indexes, views and other objects
- Sequences: the values of sequences are not copied. Columns that use them are copied as plain numbers
- Large objects (pg_largeobject)
- Views, materialized views and foreign tables: only ordinary and partitioned tables are published
- Roles, grants and other cluster-level objects
- Anything on the source in a different database from the one the subscription points to
Plan for each of these before you start. Part 2 covers how to handle them.
3. Source (Publisher) Configuration
Everything in this section is done on the source server (pg-publisher, 172.16.20.21). The source needs wal_level = logical, which is not the default and requires a restart. The rest of the section prepares the network access, the replication user and the tables.
3.1 Check the current settings first
Run on: source (pg-publisher), in psql as a superuser:
SHOW wal_level;
wal_level
-----------
replica
(1 row)
SHOW max_replication_slots;
max_replication_slots
-----------------------
10
(1 row)
SHOW max_wal_senders;
max_wal_senders
-----------------
10
(1 row)
SHOW listen_addresses;
listen_addresses
------------------
localhost
(1 row)
SHOW max_slot_wal_keep_size;
max_slot_wal_keep_size
------------------------
-1
(1 row)Compare the values with the table in Section 4.2. In this example wal_level (replica) and listen_addresses (localhost) must change, and max_slot_wal_keep_size (-1, unlimited) should be capped. The other two values are already enough. A server that was set up for physical replication earlier typically has them.
3.2 Edit the variables in postgresql.conf
Run on: source (pg-publisher). Edit /etc/postgresql/16/main/postgresql.conf on Debian and Ubuntu (on RHEL-based systems it is in the data directory)
listen_addresses = '*' # or the source's specific IP (restart required)
wal_level = logical # restart required
max_replication_slots = 10 # restart required (default is already 10)
max_wal_senders = 10 # restart required (default is already 10)
max_slot_wal_keep_size = '50GB' # PostgreSQL 13+, safety cap for slots (reload)What each variable does, and why it needs to be set:
Restart-required variables need sudo systemctl restart postgresql (Section 4.5). The max_slot_wal_keep_size setting needs only a reload.
3.3 Create a dedicated replication user
Run on: source (pg-publisher), in psql as a superuser. The user is created on the source because the destination logs in to the source with it:
CREATE ROLE replicator WITH REPLICATION LOGIN PASSWORD 'Use_A_Strong_Password_Here';
CREATE ROLE
\c appdb
GRANT USAGE ON SCHEMA public TO replicator;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO replicator;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO replicator;The destination connects as this user. It needs the REPLICATION attribute to stream changes, and SELECT on every published table because the initial copy reads the rows with COPY. Do not reuse the postgres superuser (see the PostgreSQL security hardening checklist for more). The ALTER DEFAULT PRIVILEGES line applies to tables created later by the role that runs it, so repeat it for any other table owner.
3.4 Allow the destination in pg_hba.conf
Run on: source (pg-publisher). The source decides who may connect, so the entry is added to the source's /etc/postgresql/16/main/pg_hba.conf, with the IP of the destination:
# TYPE DATABASE USER ADDRESS METHOD
host appdb replicator 172.16.20.22/32 scram-sha-256- A logical replication connection is made to a specific database, so the DATABASE column must be the database name (or all). The special
replicationkeyword matches only physical replication, which is different from the physical setup in the earlier post - Restrict the address to the destination's IP, not a wide subnet
- Use scram-sha-256 rather than md5 or trust
3.5 Apply the changes
Run on: source (pg-publisher), as the OS user with sudo rights. wal_level changed, so restart:
sudo systemctl restart postgresql# Log: /var/log/postgresql/postgresql-16-main.log (source)
2026-11-12 10:42:17.301 UTC [1204] LOG: received fast shutdown request
2026-11-12 10:42:17.314 UTC [1205] LOG: shutting down
2026-11-12 10:42:17.412 UTC [1204] LOG: database system is shut down
2026-11-12 10:42:17.689 UTC [2331] LOG: starting PostgreSQL 16.4 (Ubuntu 16.4-1.pgdg22.04+1) on x86_64-pc-linux-gnu, compiled by gcc (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0, 64-bit
2026-11-12 10:42:17.690 UTC [2331] LOG: listening on IPv4 address "0.0.0.0", port 5432
2026-11-12 10:42:17.714 UTC [2331] LOG: database system is ready to accept connectionsThen confirm, in psql on the source:
SHOW wal_level;
wal_level
-----------
logical
(1 row)If you change only pg_hba.conf later, a reload is enough: SELECT pg_reload_conf();
3.6 Check that every table has a key
Run on: source (pg-publisher), in psql, connected to appdb. UPDATE and DELETE can only be replicated for tables that have a replica identity. List the tables that have no primary key:
SELECT n.nspname AS schema, c.relname AS table
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'p')
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND NOT EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = c.oid AND i.indisprimary)
ORDER BY 1, 2;
schema | table
--------+-----------
public | audit_log
(1 row)For each table returned, choose one fix, in this order of preference:
- Add a primary key
- Use an existing unique, non-partial index on NOT NULL columns:
ALTER TABLE public.audit_log REPLICA IDENTITY USING INDEX audit_log_uidx; - As a last resort,
ALTER TABLE public.audit_log REPLICA IDENTITY FULL;(see the disadvantages below)
Check the result with SELECT relname, relreplident FROM pg_class WHERE relname = 'audit_log'; where d = default (primary key), i = index, f = full, n = nothing.
Disadvantages of REPLICA IDENTITY FULL: with this setting, there is no key, so the source writes the whole old row (every column) to the WAL for each UPDATE and DELETE, and the destination must find the row by comparing all columns.
- More WAL on the source: the old values of all columns are logged, not just a key. This increases WAL volume, disk I/O, network traffic to the destination, and the WAL that the slot has to retain
- Slow apply on the destination: without an index that helps to locate the row, each replicated UPDATE or DELETE does a sequential scan of the destination table. On a large table the apply worker falls behind and the lag grows
- Wide tables make it worse: the more and the larger the columns, the larger the WAL and the more expensive each comparison is
- No real row identity: a table without a key is also harder to compare, repair and de-duplicate later
So treat FULL as a stop-gap for small tables, and add a primary key as soon as you can.
Without any replica identity, the source rejects the statement itself:
ERROR: cannot update table "audit_log" because it does not have a replica identity and publishes updates
HINT: To enable updating the table, set REPLICA IDENTITY using ALTER TABLE.3.7 Create the publication
Run on: source (pg-publisher), in psql, connected to appdb, as the table owner or a superuser. A publication always lives on the source:
CREATE PUBLICATION app_pub FOR TABLE public.customers, public.orders;
CREATE PUBLICATION
SELECT pubname, schemaname, tablename FROM pg_publication_tables WHERE pubname = 'app_pub';
pubname | schemaname | tablename
---------+------------+-----------
app_pub | public | customers
app_pub | public | orders
(2 rows)Other forms:
Creating a publication does not start any replication. The replication slot is created later, by the subscription.
4. Destination (Subscriber) Configuration
Everything in this section is done on the destination server (pg-subscriber, 172.16.20.22), unless a step says otherwise. The destination needs the table definitions first, because logical replication copies rows and never creates tables. The order is: install, create the database, load the schema, tune the variables, then create the subscription.
4.1 Install PostgreSQL and create the database
Run on: destination (pg-subscriber). Install PostgreSQL (the same or a newer major version than the source). Unlike physical replication, the destination keeps its own, normal data directory. Do not empty it. Create an empty database with the same name, in psql as a superuser:
CREATE DATABASE appdb;
CREATE DATABASECreate the roles that own or use the tables on the destination too, because roles are not replicated. Run pg_dumpall --roles-only on the source to produce them, and load the output on the destination.
4.2 Copy the schema from the source
Run on: destination (pg-subscriber), as the postgres OS user. The commands run on the destination but read from the source. First set up .pgpass so they do not prompt for the password of replicator:
sudo -u postgres bash -c 'echo "172.16.20.21:5432:appdb:replicator:Use_A_Strong_Password_Here" >> ~/.pgpass && chmod 0600 ~/.pgpass'Dump the schema only from the source, then load it into the destination. Use the pg_dump of the destination's (newer or equal) version:
sudo -u postgres pg_dump -h 172.16.20.21 -p 5432 -U replicator -d appdb \
--schema-only --no-owner --no-privileges -f /tmp/appdb_schema.sql
sudo -u postgres psql -d appdb -v ON_ERROR_STOP=1 -f /tmp/appdb_schema.sqlThis creates tables, primary keys, indexes, constraints, sequences, views and functions, but no rows. Confirm in psql on the destination that the tables exist and are empty:
\dt public.*
List of relations
Schema | Name | Type | Owner
--------+-----------+-------+----------
public | customers | table | postgres
public | orders | table | postgres
(2 rows)
SELECT (SELECT count(*) FROM customers) AS customers, (SELECT count(*) FROM orders) AS orders;
customers | orders
-----------+--------
0 | 0
(1 row)The tables must be empty before the subscription starts with the default copy_data = true. Otherwise the initial copy fails on duplicate keys.
4.3 Check and edit the variables on the destination
Run on: destination (pg-subscriber). First check the current values in psql:
SELECT name, setting FROM pg_settings
WHERE name IN ('max_logical_replication_workers', 'max_sync_workers_per_subscription',
'max_worker_processes', 'max_replication_slots');
name | setting
-----------------------------------+---------
max_logical_replication_workers | 4
max_replication_slots | 10
max_sync_workers_per_subscription | 2
max_worker_processes | 8
(4 rows)Then edit /etc/postgresql/16/main/postgresql.conf on the destination:
max_logical_replication_workers = 8 # restart required
max_sync_workers_per_subscription = 4 # reload
max_worker_processes = 16 # restart required
max_replication_slots = 10 # restart required (default is already 10)What each variable does, and why it needs to be set:
The defaults work for a small setup with one subscription and a few tables. Raise the values when you replicate many tables or run several subscriptions. Restart the destination after changing a restart-required variable: sudo systemctl restart postgresql.
On PostgreSQL 16, max_parallel_apply_workers_per_subscription (default 2) also draws from max_logical_replication_workers. It is used only when the subscription has streaming = parallel.
4.4 Create the subscription
Run on: destination (pg-subscriber), in psql, connected to appdb, as a superuser (or on PostgreSQL 16 and later, as a member of pg_create_subscription with CREATE on the database). The subscription lives on the destination and connects to the source:
CREATE SUBSCRIPTION app_sub
CONNECTION 'host=172.16.20.21 port=5432 dbname=appdb user=replicator password=Use_A_Strong_Password_Here sslmode=require'
PUBLICATION app_pub;
NOTICE: created replication slot "app_sub" on publisher
CREATE SUBSCRIPTIONWhat happens next, all automatically:
- The destination creates a logical slot named app_sub on the source
- A table synchronization worker starts for each published table and copies its current rows with COPY
- Each worker then catches up on the changes that arrived during the copy and hands the table over to the apply worker
- The apply worker streams all further changes
Useful options of CREATE SUBSCRIPTION ... WITH (...):
On the source you will see the slot being created and the decoding start:
# Log: /var/log/postgresql/postgresql-16-main.log (source)
2026-11-12 11:08:41.233 UTC [2284] LOG: logical decoding found consistent point at 1A/6F0000D8
2026-11-12 11:08:41.233 UTC [2284] DETAIL: There are no running transactions.
2026-11-12 11:08:41.298 UTC [2291] LOG: starting logical decoding for slot "app_sub"
2026-11-12 11:08:41.298 UTC [2291] DETAIL: Streaming transactions committing after 1A/6F000110, reading WAL from 1A/6F0000D8.On the destination:
# Log: /var/log/postgresql/postgresql-16-main.log (destination)
2026-11-12 11:08:41.310 UTC [1950] LOG: logical replication apply worker for subscription "app_sub" has started
2026-11-12 11:08:41.402 UTC [1953] LOG: logical replication table synchronization worker for subscription "app_sub", table "customers" has started
2026-11-12 11:08:41.405 UTC [1954] LOG: logical replication table synchronization worker for subscription "app_sub", table "orders" has started
2026-11-12 11:08:43.871 UTC [1953] LOG: logical replication table synchronization worker for subscription "app_sub", table "customers" has finished
2026-11-12 11:08:44.912 UTC [1954] LOG: logical replication table synchronization worker for subscription "app_sub", table "orders" has finished4.5 Watch the initial synchronization
Run on: destination (pg-subscriber), in psql. Check the state of every table:
SELECT srrelid::regclass AS table_name, srsubstate FROM pg_subscription_rel;
table_name | srsubstate
------------+------------
customers | r
orders | r
(2 rows)Wait until every table shows r. For large tables this can take hours, and the slot on the source retains WAL for the whole time, so watch the disk of the source during this phase.
5. Verifying Replication
Replication is healthy when the source shows a streaming walsender with an active slot, the destination shows a running apply worker, and a test row travels from one side to the other.
5.1 On the source (publisher)
Run on: source (pg-publisher), in psql:
SELECT client_addr, application_name, state, sync_state,
sent_lsn, write_lsn, flush_lsn, replay_lsn, replay_lag
FROM pg_stat_replication;
client_addr | application_name | state | sync_state | sent_lsn | write_lsn | flush_lsn | replay_lsn | replay_lag
---------------+------------------+-----------+------------+-------------+-------------+-------------+-------------+-----------------
172.16.20.22 | app_sub | streaming | async | 1A/70001A60 | 1A/70001A60 | 1A/70001A60 | 1A/70001A60 | 00:00:00.000812
(1 row)Expect state = streaming. The application_name is the name of the subscription. An empty result means the destination is not connected. See the pg_stat_replication view for every column.
SELECT slot_name, plugin, slot_type, database, active, restart_lsn, confirmed_flush_lsn, wal_status
FROM pg_replication_slots;
slot_name | plugin | slot_type | database | active | restart_lsn | confirmed_flush_lsn | wal_status
-----------+----------+-----------+----------+--------+-------------+---------------------+------------
app_sub | pgoutput | logical | appdb | t | 1A/70001A28 | 1A/70001A60 | reserved
(1 row)Expect slot_type = logical, active = t and wal_status = reserved.
5.2 On the destination (subscriber)
Run on: destination (pg-subscriber), in psql, connected to appdb:
SELECT subname, subenabled, subslotname, subpublications FROM pg_subscription;
subname | subenabled | subslotname | subpublications
---------+------------+-------------+-----------------
app_sub | t | app_sub | {app_pub}
(1 row)
SELECT subname, pid, relid, received_lsn, latest_end_lsn FROM pg_stat_subscription;
subname | pid | relid | received_lsn | latest_end_lsn
---------+-------+-------+--------------+----------------
app_sub | 1950 | | 1A/70001A60 | 1A/70001A60
(1 row)The row with an empty relid is the apply worker. Rows with a relid are table synchronization workers, and they exist only during the initial copy. On PostgreSQL 15 and later, also check the error counters:
SELECT subname, apply_error_count, sync_error_count FROM pg_stat_subscription_stats;
subname | apply_error_count | sync_error_count
---------+-------------------+------------------
app_sub | 0 | 0
(1 row)Both must stay at 0. A rising value means the worker keeps failing and retrying (Part 2 covers this).
5.3 End-to-end test
The test assumes customers has the columns id (a serial primary key), name and email.
On the source (pg-publisher):
INSERT INTO customers (name, email) VALUES ('Repl Test', 'repl.test@mydbops.com') RETURNING id;
id
-----
101
(1 row)
INSERT 0 1On the destination (pg-subscriber):
SELECT id, name, email FROM customers WHERE id = 101;
id | name | email
------+-----------+-----------------------
101 | Repl Test | repl.test@mydbops.com
(1 row)Now test UPDATE and DELETE, which depend on the replica identity:
-- on the source (pg-publisher)
UPDATE customers SET name = 'Repl Test 2' WHERE id = 101;
DELETE FROM customers WHERE id = 101;
-- on the destination (pg-subscriber), should return 0 rows
SELECT id FROM customers WHERE id = 101;A row-count and checksum comparison, run on both servers, confirms the whole table matches. It is cheap on small tables and heavy on large ones, so use it on a sample or off-peak:
SELECT count(*), md5(string_agg(id::text, ',' ORDER BY id)) FROM orders;Unlike a physical standby, the destination accepts writes. A row inserted directly on the destination succeeds, but it is not sent back, and it can later collide with a replicated row of the same key. Treat replicated tables as read-only on the destination (Part 2 covers this).
5.4 Measuring lag
Run on: source (pg-publisher). The most reliable measure is the number of WAL bytes the destination has not yet confirmed:
SELECT slot_name,
pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), confirmed_flush_lsn)) AS lag_size
FROM pg_replication_slots
WHERE slot_type = 'logical';
slot_name | lag_size
-----------+----------
app_sub | 0 bytes
(1 row)A small, changing number is normal under load. A number that only grows means the apply worker is slower than the write rate or has stopped. The replay_lag column of pg_stat_replication gives the same information as time, but it is empty when the system has been idle. For dashboards and alerts, see our guide on PostgreSQL observability with Grafana and Prometheus.
6. Common Setup Issues
Most failures during setup are connection, permission or missing-object problems, and each leaves a clear message in the log. The table says on which server to look and fix.
Log lines you will typically see for the failures above (PostgreSQL 16, Ubuntu paths):
# wal_level is not logical (error returned to CREATE SUBSCRIPTION on the destination)
ERROR: could not create replication slot "app_sub": ERROR: logical decoding requires wal_level >= logical
# Missing pg_hba.conf entry for the database (source log)
2026-11-12 11:03:27.481 UTC [2287] FATAL: no pg_hba.conf entry for host "172.16.20.22", user "replicator", database "appdb", SSL encryption
2026-11-12 11:03:27.502 UTC [2288] FATAL: no pg_hba.conf entry for host "172.16.20.22", user "replicator", database "appdb", no encryption
# Wrong password (source log)
2026-11-12 11:06:14.337 UTC [2301] FATAL: password authentication failed for user "replicator"
2026-11-12 11:06:14.337 UTC [2301] DETAIL: Password does not match for user "replicator".
Connection matched file "/etc/postgresql/16/main/pg_hba.conf" line 128: "host appdb replicator 172.16.20.22/32 scram-sha-256"
# Source not reachable (destination log)
2026-11-12 11:14:02.115 UTC [1950] ERROR: could not connect to the publisher: connection to server at "172.16.20.21", port 5432 failed: Connection refused
Is the server running on that host and accepting TCP/IP connections?
# Table missing on the destination (destination log)
2026-11-12 11:18:45.209 UTC [1953] ERROR: logical replication target relation "public.orders" does not exist
# Replication user cannot read the table (destination log)
2026-11-12 11:19:02.644 UTC [1954] ERROR: could not start initial contents copy for table "public.orders": ERROR: permission denied for table orders
# Slot name already used (destination)
ERROR: could not create replication slot "app_sub": ERROR: replication slot "app_sub" already exists
# No free slot or worker
ERROR: could not create replication slot "app_sub": ERROR: all replication slots are in use
HINT: Free one or increase max_replication_slots.
WARNING: out of logical replication worker slots
HINT: You might need to increase max_logical_replication_workers.7. Conclusion
Setting up logical replication from a standalone server takes six steps:
- On the source: set wal_level = logical (restart), create a replication user with SELECT, and add a pg_hba.conf line for the database name
- On the source: make sure every published table has a primary key or another replica identity
- On the source: create the publication with CREATE PUBLICATION
- On the destination: create the database and load the schema with pg_dump --schema-only
- On the destination: create the subscription with CREATE SUBSCRIPTION, and wait until every table reaches state r
- Verify with pg_stat_replication on the source, pg_stat_subscription on the destination, and a real test row
At this point you have a working, verified replication from pg-publisher to pg-subscriber. What it does not yet have is protection against the things logical replication leaves to you: schema changes, sequences, writes on the destination, conflicts and a growing replication slot. Until then, keep regular backups in place, because a replica is not a backup.
Want to go further before Part 2? Read how to run bidirectional logical replication in PostgreSQL 16, how to convert a streaming replica to logical replication with pg_createsubscriber, or what changed in PostgreSQL 18 logical replication.
Need help with PostgreSQL logical replication?
Setting up replication is the easy part. Keeping it healthy, monitored and ready for a cutover is where most teams struggle. With 10+ years of database expertise, 800+ clients and 6000+ servers managed, Mydbops can plan, set up and monitor logical replication, live migrations and major version upgrades for your PostgreSQL databases.
Explore our PostgreSQL consulting services, PostgreSQL managed services and database support services.
.png)


.avif)
.avif)
