Moving a production database to a new server, infrastructure platform, or PostgreSQL version is a challenging task when the application must remain available. A traditional migration usually requires stopping application writes, exporting the database, restoring it into the new environment, and then updating the application's connection string. For a large database, the restoration process alone can take a considerable amount of time.
PostgreSQL logical replication provides another approach. It allows developers to copy existing table data to a new database while continuously transferring changes made on the original database. The application can continue using the original database during most of the migration, while the new database gradually catches up.
Once replication is complete, the team can briefly stop writes, allow the remaining changes to reach the target, validate the data, and switch application traffic.
This approach can reduce downtime significantly, although it is not automatically a zero-downtime operation. The final cutover requires coordination to prevent transactions from being lost or written to the wrong database.
This article explains how to use PostgreSQL logical replication to move a production database with a short cutover window, including configuration, monitoring, validation, and application-level considerations.
Understanding Logical Replication
PostgreSQL logical replication follows a publisher-subscriber model.
The publisher is the original database that contains the application's production data. The subscriber is the new database that receives the replicated changes.
Logical replication works with individual database objects, primarily tables. PostgreSQL initially copies the selected table data and then continuously transfers changes such as INSERT, UPDATE, and DELETE operations.
Consider an application that currently uses the following environment:
<text>Original database: PostgreSQL 14</text>
<text>Target database: PostgreSQL 18</text>
The application continues writing to PostgreSQL 14 while PostgreSQL 18 receives the existing records and subsequent changes.
The migration process looks like this:
Application
|
|
v
Original PostgreSQL
Publisher
|
| Logical Replication
|
v
New PostgreSQL
Subscriber
|
|
Data Validation
|
v
Application Cutover
Logical replication is particularly useful because it supports replication between different major PostgreSQL versions. This makes it suitable for database migrations where the target uses a newer PostgreSQL release.
The subscriber should remain read-only from the application's perspective during the migration. Allowing independent writes to the same replicated tables can introduce conflicts and inconsistent data.
Preparing Both Database Environments
Before enabling replication, prepare the source and target environments.
The source database must have logical replication enabled. Update its postgresql.conf configuration.
wal_level = logical
max_replication_slots = 10
max_wal_senders = 10
These values are examples. Production settings should account for the number of subscriptions, initial table synchronization workers, other replication workloads, and expected write activity.
Changing wal_level requires a PostgreSQL restart. The other settings may also require a restart depending on the parameter.
Next, create a dedicated replication account on the source database.
CREATE ROLE migration_user
WITH LOGIN REPLICATION PASSWORD 'replace_with_secure_password';
Grant the account permission to connect to the application database and read the published tables.
GRANT CONNECT ON DATABASE application_db
TO migration_user;
Connect to application_db and grant the required schema and table permissions.
GRANT USAGE ON SCHEMA public
TO migration_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public
TO migration_user;
Also update pg_hba.conf to allow the target database server to connect using the replication account. Restrict the connection to the target server's address and use an appropriate authentication method.
On the target server, create the destination database.
CREATE DATABASE application_db;
Check that the target has enough storage, memory, and connection capacity to support the initial copy and ongoing replication.
Preparing the Target Schema
Logical replication transfers table data and changes, but it does not automatically copy the complete database schema or DDL operations.
The target must have compatible tables before replication begins.
Use pg_dump to export the source schema.
pg_dump \
--host=source-db \
--username=admin_user \
--dbname=application_db \
--schema-only \
--no-owner \
--no-privileges \
--file=application_schema.sql
Restore the schema on the target.
psql \
--host=target-db \
--username=admin_user \
--dbname=application_db \
--file=application_schema.sql
Review the schema before restoring it. Extensions, permissions, owners, functions, triggers, and environment-specific settings may need separate handling.
Pay particular attention to tables that receive UPDATE and DELETE operations. Logical replication needs a way to identify the affected rows on the subscriber. A primary key is normally the preferred solution.
For example:
ALTER TABLE orders
ADD PRIMARY KEY (id);
If a suitable primary key cannot be used, another replica identity strategy may be necessary.
Do not assume that copying the schema is sufficient. Database roles, scheduled jobs, large objects, and other application dependencies must also be included in the migration plan.
Creating a Publication on the Source Database
A publication defines which tables and operations the source database sends to subscribers.
Suppose the application contains three important tables:
- customers
- orders
- order_items
Create a publication containing these tables.
CREATE PUBLICATION application_migration_pub
FOR TABLE
customers,
orders,
order_items
WITH (
publish = 'insert, update, delete, truncate'
);
The publication now identifies the tables whose changes should be transferred.
Before proceeding, confirm that the required tables appear in the publication.
SELECT
pubname,
schemaname,
tablename
FROM pg_publication_tables
WHERE pubname = 'application_migration_pub';
If the application has many tables, review them carefully rather than publishing everything automatically. Temporary tables, environment-specific configuration, and data that should not move may need to be excluded.
Also check whether all published tables have suitable replica identities. A table without a primary key may need additional configuration before UPDATE and DELETE operations can be replicated reliably.
Creating a Subscription on the Target Database
After preparing the publication and target schema, create a subscription on the new database.
CREATE SUBSCRIPTION application_migration_sub
CONNECTION
'host=source-db port=5432 dbname=application_db user=migration_user password=replace_with_secure_password'
PUBLICATION application_migration_pub
WITH (
copy_data = true,
create_slot = true,
enabled = true
);
The subscription connects to the publisher and starts the initial synchronization.
With copy_data enabled, PostgreSQL copies the existing rows from the published tables. Changes made on the source during the initial copy are also captured and applied to the subscriber.
This is what makes the migration useful for production systems. The application can continue operating against the original database while the target receives the existing data and ongoing changes.
Protect the replication credentials. Avoid storing passwords in source control, deployment scripts, or application logs. Use an appropriate secret-management solution for production.
For large databases, the initial copy may take time. Monitor storage consumption, network usage, source database performance, and replication progress throughout this stage.
Monitoring Replication Progress
Creating a subscription does not mean that the target is immediately ready.
Some tables may still be undergoing initial synchronization, while others may already be receiving changes. Replication can also fall behind if the source produces changes faster than the target can apply them.
On the subscriber, inspect replication activity.
SELECT
subname,
pid,
relid,
received_lsn,
latest_end_lsn,
latest_end_time
FROM pg_stat_subscription;
This view helps identify active subscription workers and the latest replication positions they have received.
On the publisher, inspect replication slots.
SELECT
slot_name,
active,
restart_lsn,
confirmed_flush_lsn
FROM pg_replication_slots;
An inactive replication slot can cause PostgreSQL to retain WAL files that are still required by the subscriber. If the subscriber remains disconnected, retained WAL can consume significant disk space.
For a closer look at replication delay, compare the source's current WAL position with the subscriber's confirmed position.
SELECT
slot_name,
pg_wal_lsn_diff(
pg_current_wal_lsn(),
confirmed_flush_lsn
) AS pending_wal_bytes
FROM pg_replication_slots
WHERE slot_type = 'logical';
This provides an approximate measure of outstanding WAL data for each logical slot. It should not be treated as an exact measure of how many transactions remain unapplied, because replication feedback, in-flight transactions, and acknowledgement timing also matter.
A healthy migration should show completed initial synchronization, active replication workers, no unresolved errors, and a consistently small replication delay.
Handling Schema Changes During Migration
One important limitation of logical replication is that DDL changes are not automatically transferred.
For example, suppose the application adds a new column to the source database.
ALTER TABLE customers
ADD COLUMN customer_category VARCHAR(50);
The same compatible change must be applied to the target database.
ALTER TABLE customers
ADD COLUMN customer_category VARCHAR(50);
For additive changes, applying the compatible schema change to the subscriber before the publisher can prevent incoming rows from failing because the target does not recognize the new column.
The migration team should coordinate schema changes throughout the replication period.
Avoid making incompatible changes to published tables while replication is active. A source table that begins producing data the target cannot accept may cause the subscription to stop.
Keep a record of schema changes and verify that both environments remain compatible before allowing replication to continue.
Managing Sequences and Other Database Objects
Sequences require special attention during a database move.
For versions before PostgreSQL 19, normal logical replication does not continuously replicate sequence state. The table rows containing generated identifiers are replicated, but the sequence itself may not reflect the latest value on the target.
For example, an orders table may contain records with IDs up to 250000, while the target sequence still has a much lower value.
Before switching application writes to the target, synchronize the sequence.
SELECT setval(
'orders_id_seq',
COALESCE((SELECT MAX(id) FROM orders), 1),
EXISTS (SELECT 1 FROM orders)
);
Repeat this for every relevant sequence, using the actual sequence associated with each column.
PostgreSQL 19 supports sequence publication and synchronization through logical replication. However, the publisher must also run PostgreSQL 19 or later for sequence replication. When migrating from an older publisher, do not assume that sequence state will be continuously synchronized automatically.
Other objects also require separate handling. Large objects are not replicated through normal logical replication. Database roles, permissions, extensions, scheduled jobs, and application-specific configuration should be reviewed independently.
Planning the Final Database Cutover
The final cutover is the most important stage of the migration.
The goal is to stop new writes on the source, allow the subscriber to apply all remaining changes, verify the target, and then redirect the application.
A practical cutover process includes the following steps.
- Confirm that all published tables have completed their initial synchronization.
- Announce the maintenance window and prepare the application for a controlled write pause.
- Stop application writes, background workers, scheduled jobs, and external integrations that can modify the source.
- Allow existing transactions to complete and confirm that no new source writes are being created.
- Wait for the subscriber to apply all outstanding changes.
- Synchronize sequences and validate important data.
- Update the application's database connection configuration to point to the target.
- Start application traffic and monitor critical operations.
Do not use a small replication lag value as the only condition for cutover. The important requirement is that all committed source transactions that must be migrated have been applied to the subscriber.
The application should also have a clear mechanism to prevent new writes during this period. Stopping only the web application is not sufficient if background workers, scheduled tasks, or external services can still access the source database.
Switching a .NET Application to the New Database
Applications using Npgsql can usually switch database environments through connection configuration.
For example, an ASP.NET Core application may define its connection string in configuration.
{
"ConnectionStrings": {
"ApplicationDatabase": "Host=target-db;Port=5432;Database=application_db;Username=app_user;Password=replace_me"
}
}
Register the Npgsql data source through dependency injection.
using Npgsql;
var builder = WebApplication.CreateBuilder(args);
var connectionString =
builder.Configuration.GetConnectionString(
"ApplicationDatabase");
builder.Services.AddSingleton(
NpgsqlDataSource.Create(connectionString!));
var app = builder.Build();
app.Run();
In production, provide credentials through a secure configuration provider rather than committing them to appsettings.json.
After switching the connection string, ensure that old connection pools and application instances are not continuing to write to the source. Restart or recycle application instances when necessary, and verify the active database endpoint.
Run smoke tests for important workflows such as customer creation, order placement, payment processing, and inventory updates.
Do not allow both databases to accept application writes during the transition. Logical replication is not an automatic bidirectional synchronization mechanism.
Validation and Rollback Planning
Before declaring the migration complete, validate more than whether the application can connect.
Compare important table counts and verify representative records.
SELECT COUNT(*) FROM customers;
SELECT COUNT(*) FROM orders;
SELECT COUNT(*) FROM order_items;
Run the same queries against both databases and investigate unexpected differences.
For critical tables, validate selected key ranges or use application-specific checksums. Row counts alone cannot prove that every record is correct.
Test application transactions, indexes, constraints, permissions, stored procedures, and extension-dependent features.
A rollback plan is also essential. Before cutover, the source remains authoritative and can normally continue serving the application if the migration is cancelled.
After the target begins accepting new writes, the situation changes. Those new transactions are not automatically transferred back to the original publisher. Returning to the old database would require a reverse synchronization strategy or another recovery procedure.
Define the rollback decision point before the cutover. Keep the old database available until the new environment has passed the agreed validation period, but do not assume that switching the connection string back is safe after new writes have occurred.
Summary
PostgreSQL logical replication provides a practical way to move a production database while minimizing application downtime. It copies existing table data and continuously transfers changes from the publisher to the subscriber, allowing the new environment to be prepared while the original application remains active.
A successful migration requires more than creating a publication and subscription. Developers must prepare the target schema, configure replication permissions, monitor synchronization, coordinate DDL changes, synchronize sequence state where necessary, and validate the target before switching application traffic.
For .NET applications using Npgsql, the final database switch can often be handled through connection configuration without changing repository or business logic.
The most important part is the cutover process. Stop all source writes, wait for replication to catch up, verify the target, and only then allow the application to write to the new database. With a tested migration plan, representative validation, and a clear rollback strategy, teams can move large PostgreSQL databases with a short and controlled interruption rather than a lengthy application outage.
Join the conversation! Your thoughts help the community grow.