A PostgreSQL major version upgrade is not something that should be validated only after production has already been changed.
The application may continue to start normally while database behavior changes underneath it. Queries can choose different execution plans, extensions may behave differently, configuration defaults can change, and application code that worked against the previous PostgreSQL version may expose problems after the upgrade.
This is why a production database should be tested before the actual migration.
The goal is not simply to prove that PostgreSQL starts on the new version. The real goal is to determine whether the application, database schema, queries, extensions, jobs, connections, and operational processes continue to work correctly.
A reliable upgrade test should reproduce production conditions as closely as practical without putting the production system at risk.
Why Test Before a PostgreSQL Major Upgrade?
PostgreSQL major upgrades can introduce changes that are not visible through a simple backup and restore test.
A database may contain:
- millions of rows
- large indexes
- materialized views
- custom extensions
- stored procedures
- scheduled jobs
- application-specific SQL
- connection pooling
- replication
- reporting workloads
- background workers
A development database rarely represents all of these conditions.
For example, a query may run in 20 milliseconds against a development database containing 10,000 rows.
The same query against production may involve 100 million rows and choose a very different execution plan after the upgrade.
Testing therefore needs to cover both database compatibility and application behavior.
What Should Be Tested?
A useful PostgreSQL upgrade test should cover several layers.
Production Database
|
+-- Schema
+-- Data
+-- Extensions
+-- Queries
+-- Indexes
+-- Functions
+-- Application
+-- Background Jobs
+-- Monitoring
+-- BackupsEach layer can expose a different problem.
For example:
| Area | What to Check |
|---|---|
| Schema | Tables, indexes, constraints, functions |
| Data | Row counts, important records, data types |
| Extensions | Version and compatibility |
| Queries | Errors and execution plans |
| Application | CRUD operations and transactions |
| Jobs | Background processing and scheduled tasks |
| Connections | Pooling and connection behavior |
| Backups | Backup and restore process |
| Monitoring | Metrics, alerts, and logs |
| Performance | CPU, memory, I/O, latency |
Testing all of these gives a much better picture than checking only whether the database starts.
Start With a Production Inventory
Before creating the test environment, document the current production database.
Collect information such as:
SELECT version();List databases:
SELECT datname
FROM pg_database
WHERE datistemplate = false;List extensions:
SELECT extname, extversion
FROM pg_extension
ORDER BY extname;List schemas:
SELECT schema_name
FROM information_schema.schemata
ORDER BY schema_name;Also identify:
- database size
- largest tables
- largest indexes
- active connections
- long-running queries
- replication configuration
- scheduled jobs
- custom functions
- triggers
- foreign data wrappers
- logical replication objects
The inventory becomes the baseline for the migration test.
Measure the Current Production Baseline
A test environment is much more useful when you know what normal production behavior looks like.
Record important metrics before the upgrade.
Examples include:
Average API latency
Database CPU usage
Database memory usage
Connection count
Transaction rate
Slow query count
Read/write throughput
Replication lag
Cache hit ratio
Disk usageFor important queries, record execution plans as well.
For example:
EXPLAIN (ANALYZE, BUFFERS)
SELECT
customer_id,
created_at,
total_amount
FROM orders
WHERE customer_id = 1001
ORDER BY created_at DESC
LIMIT 50;Save the output.
After upgrading the test database, execute the same query again.
The goal is not to make every execution plan identical.
The goal is to identify meaningful changes.
Create a Realistic Test Environment
The best upgrade test uses a database that resembles production.
A practical setup is:
Production PostgreSQL
|
| Backup / Clone
v
Test PostgreSQL
|
| Upgrade
v
Target PostgreSQL VersionThe test database should contain enough real-world structure and data to expose the problems you care about.
If copying production data is restricted because of privacy or compliance requirements, create a representative dataset with the same characteristics.
For example, if production contains:
200 million orders
15 million customers
3 million active subscriptionstesting against 50,000 synthetic orders will not provide enough confidence for query and index behavior.
Protect Sensitive Production Data
A production copy may contain:
- customer information
- email addresses
- phone numbers
- payment-related data
- internal identifiers
- access information
Do not copy sensitive production data into an environment without considering access controls and data protection requirements.
When practical, anonymize or pseudonymize sensitive fields.
For example:
Production:
[email protected]
Test:
[email protected]The structure and distribution should remain realistic enough for testing while reducing exposure.
Test the Upgrade Path
Do not assume that the final target version is the only thing worth testing.
The actual upgrade method matters.
For example, if the migration will use a dump and restore process, test that exact approach.
If the production environment will use a logical replication migration, test the replication process.
If the organization uses a supported in-place upgrade tool, validate that workflow in the test environment.
The test should answer:
Can we perform the same migration process
without unexpected application or database failures?A successful restore using one method does not automatically prove that another migration method will work.
Test Schema Compatibility
Start by validating the schema.
Compare:
- tables
- columns
- data types
- constraints
- indexes
- sequences
- views
- materialized views
- functions
- procedures
- triggers
- permissions
A useful approach is to generate schema definitions from both environments and compare them.
For example:
pg_dump --schema-only production_db > production-schema.sqland:
pg_dump --schema-only upgraded_db > upgraded-schema.sqlThen compare the resulting files.
The exact differences depend on the upgrade method, so not every difference represents a problem.
The purpose is to identify unexpected changes.
Test PostgreSQL Extensions
Extensions deserve special attention during a major upgrade.
Check the production list:
SELECT extname, extversion
FROM pg_extension
ORDER BY extname;Then verify that the same extensions are available and supported in the target PostgreSQL environment.
Common examples include:
PostGIS
pgcrypto
uuid-ossp
pg_stat_statements
citextThe actual extension list depends on the application.
Do not assume that an extension installed in production will automatically be available in the target environment.
An application may start successfully while a feature that depends on an extension fails later.
Test Application Connections
After upgrading the test database, connect the real application to it.
This is one of the most important parts of the process.
Test:
Application startup
Database connection
Authentication
Connection pooling
Transactions
Reads
Writes
Updates
Deletes
Background jobs
Reports
Scheduled tasksFor a .NET application using Npgsql, for example, the connection configuration should be tested against the upgraded database.
var connectionString =
"Host=postgres-test;Database=orders;Username=app;Password=***";
await using var connection = new NpgsqlConnection(connectionString);
await connection.OpenAsync();
await using var command =
new NpgsqlCommand("SELECT 1", connection);
var result = await command.ExecuteScalarAsync();A successful SELECT 1 only proves connectivity.
It does not prove application compatibility.
Real application operations must be tested.
Test Transactions
Transaction behavior should be included in the upgrade test.
For example:
await using var transaction =
await connection.BeginTransactionAsync();
try
{
// Perform related database operations.
await transaction.CommitAsync();
}
catch
{
await transaction.RollbackAsync();
throw;
}Test scenarios involving:
- commit
- rollback
- concurrent transactions
- deadlocks
- transaction timeouts
- retry behavior
- connection failures
A database upgrade should not change application assumptions about transaction behavior without being detected during testing.
Test Your Important Queries
Do not try to test every query manually.
Instead, identify the queries that matter most to production.
Good candidates include:
- authentication queries
- customer lookup
- order creation
- payment-related queries
- search queries
- dashboard queries
- reporting queries
- batch processing
- queue consumers
- scheduled jobs
Record their baseline behavior.
For example:
EXPLAIN (ANALYZE, BUFFERS)
SELECT *
FROM orders
WHERE customer_id = $1
ORDER BY created_at DESC
LIMIT 20;Then compare the same query on the upgraded database.
Look for changes in:
- execution time
- row estimates
- index usage
- sequential scans
- joins
- sort operations
- buffer usage
- temporary file usage
This is especially important because a query can remain logically correct while becoming slower.
Check Execution Plan Changes
Suppose the old database uses:
Index Scanwhile the upgraded database chooses:
Seq ScanThat is not automatically wrong.
The optimizer may have determined that the sequential scan is cheaper.
The important question is whether the decision makes sense for the actual workload.
For example:
Before:
Index Scan
Execution Time: 15 ms
After:
Seq Scan
Execution Time: 2,400 msThat difference requires investigation.
Potential causes include:
- changed statistics
- stale statistics
- different cost estimates
- changed data distribution
- missing indexes
- changed configuration
- query planner changes
Do not fix a plan difference simply because it looks different. Fix it when the resulting behavior is problematic.
Refresh Statistics
After restoring or migrating a database, statistics may need attention.
Run:
ANALYZE;For a specific table:
ANALYZE orders;Then test important queries again.
A query planner makes decisions based partly on statistics. A test environment with incomplete or stale statistics can produce misleading results.
Test Large Tables
Small databases hide performance problems.
Identify your largest tables:
SELECT
schemaname,
relname,
pg_size_pretty(pg_total_relation_size(relid)) AS total_size
FROM pg_catalog.pg_statio_user_tables
ORDER BY pg_total_relation_size(relid) DESC
LIMIT 20;Pay particular attention to:
- heavily queried tables
- large indexes
- partitioned tables
- frequently updated tables
- tables used in reporting
- tables involved in joins
If production performance depends on table size, the upgrade test should reflect that size.
Test Indexes
Verify that important indexes exist after the migration.
You can inspect indexes using:
SELECT
schemaname,
tablename,
indexname,
indexdef
FROM pg_indexes
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
ORDER BY schemaname, tablename, indexname;Then compare important indexes between the production baseline and upgraded environment.
Do not assume that an index definition alone proves performance.
Run the important queries and inspect their execution plans.
Test Stored Functions and Procedures
Applications sometimes depend heavily on database-side logic.
Test:
- functions
- procedures
- triggers
- generated columns
- views
- materialized views
For example:
SELECT *
FROM calculate_customer_balance(1001);If a function is part of a critical transaction, include that transaction in integration testing.
Database-side code can fail independently of application code.
Test Background Jobs
A web application may work perfectly while background processing is broken.
Test:
Queue consumers
Scheduled jobs
Data synchronization
Email processing
Report generation
Cleanup jobs
ETL processes
Notification workersFor example, if a background worker executes:
SELECT id
FROM jobs
WHERE status = 'pending'
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 10;verify that the complete worker workflow still behaves correctly.
Do not test only the SQL statement. Test the application behavior around it.
Test Connection Pooling
Connection behavior can change under load.
If the application uses a connection pool, test:
- normal connection count
- connection reuse
- maximum pool size
- connection timeout
- command timeout
- connection failures
- application restarts
- database restarts
A simple application test that opens one connection does not represent production traffic.
Run realistic concurrent requests against the upgraded database.
Perform Load Testing
Performance testing becomes much more useful when it resembles actual production traffic.
For example:
100 requests/sec
70% reads
20% updates
10% insertsThe exact numbers should come from production metrics.
Measure:
API latency
Database latency
CPU
Memory
I/O
Connection count
Transactions/sec
Error rate
Lock waitsCompare the old and upgraded environments.
The goal is to identify regressions before production traffic finds them.
Test Failure Scenarios
A migration test should include failure behavior.
For example:
- database connection is interrupted
- transaction fails
- query times out
- connection pool is exhausted
- replication falls behind
- application restarts
- database restarts
- background job fails
Check whether the application:
- retries safely
- avoids duplicate writes
- reports useful errors
- recovers connections
- preserves transaction integrity
An upgrade is not only about successful requests.
Failure behavior matters just as much.
Test Backups and Restore
Before approving the migration, verify that the backup and restore process works with the target version.
A backup is useful only if it can actually be restored.
Test:
Backup
|
v
Restore
|
v
Start PostgreSQL
|
v
Run validation queries
|
v
Start application
|
v
Run smoke testsValidate important objects and data after restoration.
Check:
- table counts
- row counts
- indexes
- extensions
- permissions
- application connectivity
Validate Data After the Upgrade
Data correctness should be tested explicitly.
Do not rely only on the application.
Useful checks include:
SELECT COUNT(*) FROM customers;
SELECT COUNT(*) FROM orders;
SELECT COUNT(*) FROM payments;For important numeric data:
SELECT
COUNT(*) AS order_count,
SUM(total_amount) AS total_amount
FROM orders;For important date ranges:
SELECT
MIN(created_at),
MAX(created_at)
FROM orders;Compare these results against the production baseline.
For very large databases, use representative validation rather than attempting to manually inspect every row.
Test Replication
If production uses replication, include it in the upgrade testing.
Test:
- replica startup
- replication connection
- replication lag
- failover
- read-only behavior
- monitoring
- recovery
If the migration strategy involves replication-based cutover, this becomes even more important.
The test should reproduce the actual topology as closely as practical.
Test Monitoring and Alerts
Database migration can expose gaps in monitoring.
Verify that existing monitoring still detects:
- high CPU
- high connection usage
- slow queries
- replication lag
- disk growth
- failed connections
- lock contention
- backup failures
Do not wait until production to discover that a database metric disappeared after the upgrade.
Run a Production-Like Smoke Test
Before the migration is approved, run a repeatable smoke test.
For example:
1. Application starts
2. Login succeeds
3. Customer can be loaded
4. New order can be created
5. Order can be updated
6. Payment record can be read
7. Background job processes successfully
8. Report loads
9. Important queries remain within target latency
10. No unexpected database errors appearThis gives the team a simple acceptance test for the upgraded environment.
Common Mistakes
| Mistake | Why It Causes Problems | Better Approach |
|---|---|---|
| Testing only PostgreSQL startup | Does not prove application compatibility | Test real application operations |
| Using a tiny database | Hides query and index problems | Use production-like data volume |
| Ignoring extensions | Features may fail after migration | Inventory and test every extension |
| Comparing only row counts | Data can be structurally correct but functionally wrong | Test application behavior |
| Skipping execution plans | Performance regressions may go unnoticed | Compare important queries |
| Testing only happy paths | Recovery problems remain hidden | Test failures and retries |
| Ignoring background jobs | Non-web workloads may break | Include workers and scheduled tasks |
| Forgetting backups | Recovery may fail when needed | Perform a restore test |
| Assuming every plan change is bad | Planner behavior can legitimately change | Compare actual performance |
| Testing a different migration method | Production may fail despite successful testing | Test the real upgrade procedure |
Build an Upgrade Readiness Report
After testing, document the results.
A simple report can contain:
| Area | Result | Notes |
|---|---|---|
| Schema | Passed | No unexpected differences |
| Extensions | Passed | Required extensions available |
| Data validation | Passed | Key counts match |
| API tests | Passed | No application errors |
| Query performance | Passed | No significant regressions |
| Background jobs | Passed | Jobs processed correctly |
| Replication | Passed | Within expected lag |
| Backup restore | Passed | Recovery tested |
| Monitoring | Passed | Alerts operational |
| Load testing | Review | One query needs tuning |
This makes the migration decision measurable.
When the Test Finds a Problem
Do not immediately cancel the upgrade.
Classify the problem first.
Problem
|
+-- Compatibility issue
+-- Performance issue
+-- Configuration issue
+-- Extension issue
+-- Application issue
+-- Migration process issueThen determine whether the problem can be fixed before production.
For example:
Query became slower
|
v
Compare execution plans
|
v
Check statistics
|
v
Check index
|
v
RetestA failed upgrade test is useful because it identifies the problem while there is still time to fix it.
Advantages of Testing Before Migration
| Advantage | Description |
|---|---|
| Lower production risk | Problems are found before cutover |
| Better performance confidence | Important queries can be compared |
| Safer rollback planning | Migration steps are tested beforehand |
| Better application confidence | Real application operations are validated |
| Extension compatibility | Unsupported or problematic extensions are identified |
| Operational readiness | Backups, monitoring, and recovery are tested |
| Faster migration | Known problems can be resolved before the maintenance window |
Disadvantages and Trade-Offs
Testing a production database upgrade requires effort.
| Challenge | Impact |
|---|---|
| Large test databases | Require storage and infrastructure |
| Data anonymization | Adds preparation work |
| Load testing | Requires additional tooling |
| Environment duplication | Can increase infrastructure cost |
| Test maintenance | Production changes may require refreshing the test environment |
| Long-running tests | Large databases can take significant time to validate |
These costs are generally much smaller than discovering an upgrade problem after production traffic has already moved to the new database.
PostgreSQL Upgrade Readiness Checklist
Before upgrading the production database, verify:
- Production database version is documented.
- Target PostgreSQL version is defined.
- Upgrade method has been tested.
- Database size is documented.
- Important tables and indexes are identified.
- Extensions are inventoried.
- Schema has been compared.
- Production-like data is available for testing.
- Sensitive test data is protected.
- Important queries have baseline execution plans.
- Query performance has been compared.
- Application integration tests pass.
- Transactions have been tested.
- Background jobs have been tested.
- Connection pooling has been tested.
- Load testing has been completed.
- Failure scenarios have been tested.
- Replication has been tested where applicable.
- Backup and restore have been validated.
- Monitoring and alerts have been checked.
- Production smoke tests are documented.
- Rollback or recovery procedures are understood.
- Known issues are documented and accepted.
Final Thoughts
A PostgreSQL major version upgrade should be treated as an application and infrastructure change, not just a database maintenance task.
The safest approach is to create a production-like test environment, use the same upgrade method planned for production, validate the schema and extensions, compare important query plans, run realistic application workloads, test background processing, verify backups, and check recovery behavior.
The most valuable result of this testing is not a simple "upgrade succeeded" message.
It is knowing what will change, which parts of the system are affected, and what needs to be fixed before production is touched.
A successful database upgrade is not just a PostgreSQL server running on the new version. It is the application continuing to behave correctly after the database underneath it has changed.


Join the conversation! Your thoughts help the community grow.