Before planning the migration, decide which PostgreSQL version should receive the application.
PostgreSQL 14 reached the end of its support period in November 2026. Continuing to run it means missing future community security fixes and bug fixes. PostgreSQL 15, 16, 17, 18, and 19 provide supported upgrade targets, but the best choice depends on application compatibility, extension availability, operational experience, and the expected lifetime of the deployment.
For an established production application, PostgreSQL 18 may be a sensible target when the team wants a mature release with an established operational history. PostgreSQL 19 is another option when the application and its extensions have been tested against it and the team is comfortable adopting the latest major release.
Do not select a target version only because it is the newest. Check the compatibility of database extensions, drivers, backup tools, monitoring agents, connection poolers, and managed database services.
A useful initial checklist includes:
Area | What to verify |
Application driver | Npgsql version and PostgreSQL compatibility |
Extensions | Availability and supported versions on the target |
Database schema | Data types, indexes, constraints, and functions |
Authentication | Roles, passwords, and authentication configuration |
Replication | Logical replication support and required permissions |
Operations | Backup, restore, monitoring, and recovery procedures |
Infrastructure | Disk space, memory, CPU, and connection limits |
This assessment should happen before copying production data. Discovering that an important extension is unavailable after the migration has started can create unnecessary delays.
Choosing a Migration Strategy
There are two common approaches for moving a PostgreSQL database to another major version: a direct upgrade and a replication-based migration.
The direct approach is appropriate when the database can tolerate a maintenance window. Tools such as pg_upgrade can upgrade an existing database cluster without requiring a complete logical export and import. A dump-and-restore migration is another option, particularly when the team wants to rebuild the target database cleanly.
A replication-based migration is useful when the application must remain available while most of the data is copied.
Approach | Downtime | Suitable scenario | Main consideration |
pg_upgrade | Requires a planned outage | Existing cluster upgrade | Both versions and upgrade prerequisites must be compatible |
pg_dump and restore | Depends on database size and restore time | Smaller databases or clean rebuilds | Large datasets can take considerable time |
Logical replication | Short final cutover window | Large databases with continuous writes | Schema and sequence synchronization require additional work |
For a migration from PostgreSQL 14 to a newer major version, logical replication provides a practical way to prepare the target while the original application continues operating.
The important distinction is that logical replication transfers table changes, not an entire PostgreSQL installation. Database objects and operational settings still need separate handling.
Preparing the Source and Target Databases
Assume the existing database is running PostgreSQL 14 and the new environment is running PostgreSQL 18 or 19.
Use separate environments for the source and target. The source remains responsible for application writes during the migration, while the target receives replicated changes.
Before enabling replication, review the database configuration and confirm that the target has enough storage capacity. The target may temporarily require additional space for the initial data copy, indexes, and incoming changes.
On the source server, configure logical replication.
wal_level = logical
max_replication_slots = 10
max_wal_senders = 10
The values shown are examples, not universal production settings. Calculate the required slots and senders based on the number of subscriptions and other replication workloads.
Changing wal_level requires a PostgreSQL restart. Other settings may also require a restart depending on the parameter.
Create a dedicated replication account rather than using the application's normal database account.
CREATE ROLE migration_user
WITH LOGIN REPLICATION PASSWORD 'replace_with_a_secure_password';
Grant the account access to the database and the tables that must be published.
GRANT CONNECT ON DATABASE application_db
TO migration_user;
Connect to the application database 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 configure pg_hba.conf on the source server to allow the target server to connect using the replication account. Restrict the entry to the target server's address and use an appropriate authentication method, such as SCRAM.
After changing the configuration, reload PostgreSQL where applicable.
Creating the Target Schema
Logical replication does not automatically replicate database schema definitions or DDL commands. Tables, indexes, constraints, functions, triggers, and other required objects must be created separately.
One way to prepare the target is to export the source schema using pg_dump.
pg_dump \
--host=source-db \
--username=admin_user \
--dbname=application_db \
--schema-only \
--no-owner \
--no-privileges \
--file=application_schema.sql
Restore the schema into the target database.
psql \
--host=target-db \
--username=admin_user \
--dbname=application_db \
--file=application_schema.sql
Review the generated SQL before applying it. Database owners, grants, extensions, and environment-specific configuration may need separate handling.
Do not blindly restore every object if the target has already been prepared by infrastructure automation or a managed database service.
Pay special attention to extension versions, custom types, functions, collations, and objects that depend on operating-system libraries.
The target schema must be compatible with the rows that will arrive through replication. If the source changes a table in a way that the target cannot accept, replication can stop with an error.
For that reason, freeze unrelated schema changes during the migration or introduce compatible changes in a coordinated order.
Creating a Publication on PostgreSQL 14
A publication identifies which tables and operations should be sent to subscribers.
For example, the application may need to replicate customers, orders, and order items.
CREATE PUBLICATION application_migration_pub
FOR TABLE
customers,
orders,
order_items
WITH (publish = 'insert, update, delete, truncate');
Choose the tables deliberately. Replicating every table may be unnecessary if some tables contain temporary data, local configuration, or information that should not move to the new environment.
Before creating the publication, check whether tables that receive UPDATE or DELETE operations have a suitable replica identity. A primary key is normally the preferred choice.
SELECT
schemaname,
tablename,
indexname
FROM pg_indexes
WHERE schemaname = 'public'
ORDER BY tablename;
A table without a suitable replica identity may require a different configuration.
For a table without a primary key, REPLICA IDENTITY FULL can be considered, but it can increase the amount of information needed to identify changed rows.
ALTER TABLE order_items
REPLICA IDENTITY FULL;
Use this only after understanding its performance and storage implications.
Creating a Subscription on the New Database
Once the target schema and source publication are ready, create a subscription on the target PostgreSQL server.
CREATE SUBSCRIPTION application_migration_sub
CONNECTION
'host=source-db port=5432 dbname=application_db user=migration_user password=replace_with_a_secure_password'
PUBLICATION application_migration_pub
WITH (
copy_data = true,
create_slot = true,
enabled = true
);
With copy_data enabled, PostgreSQL initially copies the existing rows from the published tables. After the initial copy, new changes are continuously transferred from the source.
This means the original application can continue writing to PostgreSQL 14 while the target catches up.
In production, protect connection credentials appropriately. Avoid leaving passwords in shell history, source control, or deployment logs. Use your organization's secret-management process and restrict access to replication credentials.
You can inspect subscription progress on the target.
SELECT
subname,
pid,
received_lsn,
latest_end_lsn,
latest_end_time
FROM pg_stat_subscription;
On the source, inspect replication slot activity.
SELECT
slot_name,
active,
restart_lsn,
confirmed_flush_lsn
FROM pg_replication_slots;
These views help identify whether replication is active and whether the source is retaining WAL for a subscriber that is falling behind.
Monitoring Replication Lag and Data Consistency
An active subscription does not automatically mean that the target is ready for cutover.
The initial table copy may still be running, or the subscriber may be processing changes more slowly than the application generates them.
Monitor replication throughout the migration. Check for errors in PostgreSQL logs, inactive replication slots, growing WAL retention, and tables that have not completed their initial synchronization.
Logical replication also has important limitations that must be included in the migration plan.
First, schema changes are not automatically transferred. If a new column is added to the source, the target may need the compatible schema change before rows containing that column arrive.
Second, sequence values are not continuously replicated. Although the values stored in serial or identity columns are copied with table rows, the sequence state itself must be synchronized separately before the target begins accepting writes.
Third, large objects are not replicated through the normal logical replication process. Applications using PostgreSQL large objects need a separate migration strategy.
Other objects, including roles, database-level settings, extensions, and scheduled jobs managed outside PostgreSQL, also require separate attention.
For important tables, compare row counts and perform additional application-level validation. Row counts alone are not a complete proof of consistency, but they can reveal obvious migration problems.
For example:
SELECT COUNT(*) FROM customers;
SELECT COUNT(*) FROM orders;
SELECT COUNT(*) FROM order_items;
Run equivalent queries on both databases and investigate differences. For critical datasets, use key-range checks or checksums designed for the application's data model.
Planning the Final Cutover
The final cutover is the most sensitive part of the migration.
The objective is to stop new writes to PostgreSQL 14, allow the subscriber to apply all remaining changes, synchronize sequences, and then direct the application to the new database.
A practical cutover process looks like this:
Announce the maintenance window and confirm that the target has completed its initial table synchronization.
Put the application into maintenance mode or temporarily disable operations that write to the database.
Stop background workers, scheduled jobs, and external integrations that can still modify the source database.
Confirm that no application process can create additional writes on PostgreSQL 14.
Wait for the subscriber to apply all remaining changes and verify replication status.
Synchronize sequence values on the target.
Run final data checks and essential application smoke tests.
Update the application's database connection configuration to use the target.
Start application traffic and monitor errors, latency, and database activity.
Sequence synchronization deserves special attention. For a simple sequence-backed ID column, the target sequence can be adjusted using the maximum existing value.
SELECT setval(
'orders_id_seq',
COALESCE((SELECT MAX(id) FROM orders), 1),
EXISTS (SELECT 1 FROM orders)
);
This is an example for a sequence named orders_id_seq. Repeat the process for every relevant sequence, using the actual sequence associated with each column.
Do not perform sequence synchronization while writes are still being accepted on the source. A late source insert could otherwise create an identifier that is not reflected in the target sequence state.
Also verify that no application or integration is writing to the target before cutover. Logical replication is designed for a publisher-to-subscriber flow, not an automatic two-way merge. Allowing independent writes to the same replicated tables can create conflicts or inconsistent data.
Once the application starts writing to the target, returning to the old source is no longer a simple connection-string change. A rollback plan must account for writes made after cutover. If the team needs a rapid reverse migration, it must design and test a suitable reverse data synchronization strategy before the migration.
Updating a .NET Application Without Changing Its Business Logic
For an ASP.NET Core application using Npgsql, the database migration can often be handled through configuration rather than changes to repository methods.
For example, keep the connection string outside the source code.
{
"ConnectionStrings": {
"ApplicationDatabase": "Host=target-db;Port=5432;Database=application_db;Username=app_user;Password=replace_me"
}
}
Register the 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();
The production connection string should be supplied through a secure configuration provider rather than committed to appsettings.json.
Before switching production traffic, test the application against the target version. Verify parameterized queries, transactions, prepared statements, connection pooling, timeout behavior, date and time handling, and any PostgreSQL-specific SQL used by the application.
Also check whether the Npgsql version supports the target PostgreSQL release and whether the application depends on behavior that changed between database versions.
The migration should not be considered complete merely because the application can open a connection. Critical workflows such as creating an order, updating inventory, processing a payment, and generating reports must also be tested.
Common Migration Mistakes
One frequent mistake is assuming that logical replication copies the complete database environment. It does not. Schema objects, sequence state, roles, and several other database-level resources need separate preparation.
Another mistake is allowing schema changes to continue without a migration plan. A column added to the source but not the target can cause replication errors when new rows arrive.
Teams also underestimate WAL retention. If a subscriber becomes inactive, its replication slot can prevent old WAL segments from being removed. This can consume significant disk space on the source. Monitor replication slots and disk usage throughout the migration.
A further mistake is treating a successful connection test as proof that the application is compatible. Differences in extensions, query behavior, data types, collations, and driver versions can appear only when real application workflows execute.
Finally, avoid keeping the old database as an assumed rollback option after the new database starts accepting writes. Once new transactions exist only on the target, the old database is no longer an equivalent copy.
Summary
Moving a PostgreSQL 14 application to a supported major version does not have to require a long application outage. A staged migration using logical replication can copy existing data and continuously transfer changes while the original application remains active.
The process requires more than creating a publication and subscription. Developers must prepare the target schema, verify extensions and application compatibility, monitor replication lag, synchronize sequences, and coordinate a controlled cutover.
For .NET applications using Npgsql, database connection configuration can usually be switched independently of repository and business logic. However, the complete application must be tested against the target database before production traffic is moved.
The safest migration is one that has been rehearsed with representative data, includes a verified backup and recovery plan, and defines exactly when writes stop on the source and begin on the target. This approach reduces migration risk while giving the team a clear path away from an unsupported PostgreSQL installation.
Join the conversation! Your thoughts help the community grow.