Changing a database schema in production is not simply a matter of running a few SQL statements. Old and new application versions may run at the same time, long-running queries may still be active, and schema commands can acquire locks that affect user traffic. Safe schema evolution therefore depends on replacing one sharp cutover with several backward-compatible steps.
This guide explains the expand-migrate-contract approach, using PostgreSQL examples. The general pattern applies to other relational databases, but lock behavior, DDL features, and online index options vary by database engine and version.
Why schema changes cause outages
A schema change released together with new application code creates two common failure modes. The first is a compatibility failure: an older application instance tries to read or write a column that does not exist yet, or expects a constraint or data format that has already changed. The second is an operational failure: the DDL statement waits for a conflicting transaction or blocks new work while it runs.
PostgreSQL documents that different ALTER TABLE subcommands can require different lock levels, and many forms acquire ACCESS EXCLUSIVE by default. When multiple subcommands are combined, the strictest required lock applies. That makes it important to evaluate a migration against real table size, traffic patterns, open transactions, and deployment behavior rather than judging it only by SQL length.
The expand-migrate-contract pattern
The pattern divides a potentially incompatible change into three phases:
- Expand: Add the new structure while keeping the old application version functional.
- Migrate: Move application behavior and existing data to the new structure.
- Contract: Remove the old structure after all consumers have stopped using it.
This is also called parallel change. GitLab’s multi-version compatibility guidance describes the same three-stage model for breaking changes, including database migrations. The key idea is that the phases should be separated across deployment milestones so that old and new software can coexist without requiring a synchronized global cutover.
Example: renaming a column safely
Suppose a customers table has a column named name, and you want to replace it with the clearer name display_name. Renaming it immediately can break older application instances. A safer sequence looks like this.
1. Add the new column
ALTER TABLE customers ADD COLUMN display_name text;This may be backward-compatible from the application’s perspective, but it still needs operational controls. Run it first in a staging environment with production-like data, set appropriate statement and lock timeouts, and schedule it during a period when the system can tolerate some additional risk.
2. Backfill in small batches
Updating a large table in one transaction can create long-running work, generate substantial write-ahead logging, and make failure recovery more expensive. Instead, process bounded ranges or limited batches:
UPDATE customers
SET display_name = name
WHERE id > :last_id
AND id <= :next_id
AND display_name IS NULL;Record progress after each successful batch. A restartable backfill does not need to begin from zero after a connection failure or process restart. Batch size should be chosen using measurements: larger batches may finish faster but create more load and longer transactions.
3. Deploy code that understands both versions
During the transition, the application can write both columns for new or modified records. Reads can prefer the new column and fall back to the old one:
SELECT COALESCE(display_name, name) AS customer_name
FROM customers;Dual writes are not automatically safe. They create a consistency risk, so the write path should be centralized, metrics should compare both values, and the team should document which field is considered authoritative during the migration.
4. Remove the old column only after verification
Before the contract phase, verify that all application instances, background workers, reporting queries, administrative tools, and maintenance scripts no longer depend on the old column. Delayed mobile clients and scheduled jobs are frequently overlooked consumers.
Drop the old column as a separate, explicitly reviewed operation. It is harder to reverse than adding a nullable column, so it should happen only after the new path has operated successfully for a suitable observation period and a recovery plan has been tested.
Use online index creation deliberately
Building an index on a large table can take considerable time. PostgreSQL documentation explains that a regular CREATE INDEX can block writes while the index is built. CREATE INDEX CONCURRENTLY is designed to allow inserts, updates, and deletes to continue, but it performs more work, can take longer, and adds CPU and I/O load.
CREATE INDEX CONCURRENTLY idx_customers_display_name
ON customers (display_name);Concurrent index creation cannot run inside a transaction block. If it fails, PostgreSQL may leave an invalid index that must be inspected and usually removed before retrying. Only one concurrent index build can run on a table at a time, and schema changes to that table may still be restricted during the operation. Therefore, “concurrent” does not mean “free”; monitor latency, disk capacity, replication lag, and lock waits while it runs.
Separate constraint creation from validation
Adding a new CHECK or foreign-key constraint may require validating existing rows. On a large table, that validation can take time and affect concurrent updates. Where supported and appropriate, add the constraint as NOT VALID, then validate it in a later step:
ALTER TABLE orders
ADD CONSTRAINT orders_total_nonnegative
CHECK (total_amount >= 0) NOT VALID;
ALTER TABLE orders
VALIDATE CONSTRAINT orders_total_nonnegative;Deferring validation does not remove the need for correctness checks. Find existing violating rows before deployment, test the behavior of new and updated rows on the target database version, and plan validation as a monitored operation rather than an invisible background detail.
Observability and rollback planning
- Track migration duration, processed rows, remaining rows, and retry counts.
- Monitor database latency, error rate, connection-pool saturation, disk usage, and replication lag.
- Inspect PostgreSQL’s
pg_locksview and active sessions when a migration waits. - Define stop conditions, such as a sustained latency increase or lock wait above an agreed threshold.
- Design rollback as more than rerunning a previous migration: include application rollback, disabling dual writes, and resuming a partial backfill.
For destructive contract steps, backups and restore tests are essential. Having a backup policy does not prove that the data can be restored within the service’s recovery objectives.
A practical review checklist
- Document whether the change is compatible with the previous application version.
- Identify the lock level, table scans, transaction duration, and expected resource usage.
- Make large data transformations incremental and restartable.
- Measure consistency between old and new representations.
- Separate schema changes from application deployment when possible.
- Test indexes, constraints, and backfills with production-like data.
- Delay destructive cleanup until all consumers are confirmed to be migrated.
Zero-downtime schema evolution does not come from a single magic SQL command. It comes from compatibility, small reversible steps, explicit observation, and a tested recovery path. Expand-migrate-contract turns a risky schema rewrite into a sequence of controlled changes, especially when multiple application versions must coexist during deployment.
0 Comments