Database migrations: how to change a schema safely while a service is running
A database migration is a recorded, repeatable change that moves a schema or its data from one state to another. When applications are deployed continuously, or old and new versions run at the same time, splitting a destructive change into stages can reduce risk. It does not guarantee “zero downtime”: table size, locks, data conversion, deployment order, and recovery plans all matter.
This article focuses on schema and related data changes in a live relational database. Moving a database to another server or cloud, restoring from backup, and analytical ETL are separate tasks. PostgreSQL details are scoped to version 18; Django and Prisma documentation are used as product-specific examples of migration practice.
What does a migration file record?
A migration file represents database changes as an ordered history with dependencies. Adding a column, changing a constraint, and transforming existing values are different kinds of work. A framework can use the history to track which changes have been applied in development, staging, and production. Django explains that it computes state from migration files rather than comparing only the current models with the database. It cannot automatically discover an unrecorded manual change, so the recorded history can drift from the actual schema. Django migrations
Migrations can contain both schema changes and data changes. Schema changes affect columns, tables, indexes, and constraints. A data migration transforms existing rows or fills values according to a new rule. These operations can have different run times and failure modes, so plan their order and retry behavior instead of combining them blindly in one large script.
Why split a change into stages?
Production applications do not all change at the same instant. Instances may be upgraded gradually, and workers or long-running requests may continue using old code. A new version can fail if it reads a column that has not been created; old code can fail if a new constraint rejects values it still writes. The database change and code deployment need a compatibility window in which both old and new versions can work.
A common approach is expand and contract. First add the new structure while keeping the old one (expand), populate the data, switch the application to the new structure, then remove the old structure only after confirming that no code still uses it (contract). Prisma’s guidance follows this sequence: retain the old field, add a new one, migrate the data, switch the application, and remove the old field in a later deployment. This can lower interruption risk, but it adds work to design and verify compatibility between deployments. Prisma: data migration guide
Example: replacing a published boolean with a status
Suppose, as an illustrative example, a posts table has a true/false column named published, and you want to replace it with a status column that can represent several states. Renaming or dropping the old column first could break an older application. The following sequence is designed to tolerate a period when both code versions coexist:
**Expand:** Add `status` while keeping `published`. Do not make the new column unconditionally required before every row has a valid value. Confirm that this step does not break reads or writes from the old version.
**Deploy compatible code:** Have the application write the new status and, while old instances or workers remain, update the old column too where needed. Decide how long code that reads the old column and code that reads the new one may coexist.
**Backfill:** Convert existing rows in small batches. For example, map `published = true` to `Published` and the other value to `Draft`. Updating a large table in one transaction can cause long locks, large logs, or replication lag. A resumable job that records progress may be safer; choose batch size by observing actual load.
**Verify:** Check that `status` is populated, old and new values agree, and rows created during the backfill are covered. While both columns are written, verify that the code follows the rule and reads return the intended result.
**Switch:** Deploy the application so every instance reads the new column. If necessary, keep writing both columns during one deployment, and use logs or deployed-version information to confirm that nothing still reads the old one.
**Contract:** Remove `published` in a separate migration only after old code and workers are gone and the old column is no longer needed for recovery. Dropping it is destructive; a rollback may not be able to reconstruct its values.
This is an illustrative example. If the real model has more than two states or has transition rules, first decide how each old row maps to the new meaning rather than treating a boolean as a simple replacement. Prisma’s example likewise adds a new field, backfills it from published, switches the code, and removes the old field later. Prisma data migration guide
What should you consider for backfills and schema changes?
A backfill transforms existing rows to populate a new column or format. With little data, it may be practical to run it inside a migration. On a large table, one long transaction can increase lock duration, log volume, replica lag, and retry costs. Django documents both batching large data changes and race conditions that can occur when new rows arrive during a transformation. Django: writing database migrations
Give a batch job a restart point. It might save the last processed primary key or select only rows still needing conversion, such as status IS NULL. Consider idempotency so rerunning a batch does not duplicate or damage results, and define how to tell how far a failed run got. Writes that continue during backfill also need to be reconciled. During expansion, the application might update both formats, or you might run a final pass to find missed rows.
DDL (data definition language) operations have different effects. Adding a column may be quick, but defaults or type changes can require a full table rewrite. Building an index can take a long time on a large table. PostgreSQL 18 documents that many ALTER TABLE forms acquire strong locks by default, and some constraint validation requires a table scan and can block updates. One option is to add a constraint as NOT VALID and validate existing rows separately. CREATE INDEX CONCURRENTLY is designed to avoid blocking writes, but has additional work and restrictions; check the documentation for the exact database version. PostgreSQL 18: ALTER TABLE, PostgreSQL 18: CREATE INDEX
Review more than SQL syntax: expected scans and rewrites, lock modes and waits, free disk space, replication lag, transaction size, and how to cancel and resume the work. A quick run against a small development database does not establish the impact on a production table.
How do you verify before and after deployment?
Before production, apply the migration in staging with data volume and distribution close to reality. Check that both old and new application versions work with the changed schema. If there is a backfill, observe throughput, lock waits, replication lag, and restart behavior after errors. Do not merely create a backup; restore it in a separate environment to confirm that the recovery procedure works.
During deployment, monitor:
The target database, execution order, and applied-migration history or status.
Lock waits, connection pool exhaustion, error rate, database CPU, disk and logs, and replica lag.
Backfill progress, failed batches, and data invariants after conversion (for example, whether the new column has missing values).
Whether any old code or workers remain, and whether the application is using the expected schema.
If a migration fails, do not immediately edit the file and try to rerun an already recorded change. Compare the actual schema with the migration history and determine whether only part of the work completed. Then decide whether rollback, a corrective migration, or a retry is safe. Reversing a schema change does not necessarily restore deleted or transformed data. Delay destructive steps such as dropping a column until the path back to old code is closed.
A pre-deployment checklist
**Write down the change and compatibility window.** State whether it changes schema or data, whether old and new applications will run together, and when the old structure will be removed.
**Assess impact.** Use documentation for the actual database version to check large-table scans or rewrites, locks, constraints, indexes, disk, and replicas.
**Split the work into stages.** Separate expansion, compatible-code deployment, backfill, verification, read switch, and contraction; define prerequisites for each.
**Version and review the migration.** Inspect generated SQL or the operation plan. Avoid manual production changes that separate the recorded history from the real schema.
**Apply and recover in a representative environment.** Measure duration, locks, and data checks in staging; rehearse a restore or resume procedure.
**Roll out gradually.** Observe migration state and application compatibility. If something goes wrong, stop before the next stage and recover from a state you can inspect.
**Contract last.** Remove old schema only after confirming that no instance reads or writes it and data validation is complete.
A good database migration is more than SQL that creates a new schema. It coordinates versioned history, compatibility during deployment, large data changes, lock and replication effects, and recovery from failure. Separate especially destructive or meaning-changing steps and verify them carefully. A safe process comes from knowing what each code version sees at every stage, not just from memorizing product-specific syntax.
Scope and sources
[Django documentation: Migrations](https://docs.djangoproject.com/en/5.2/topics/migrations/)
[Django documentation: Writing database migrations](https://docs.djangoproject.com/en/5.2/howto/writing-migrations/)
[Prisma documentation: expand-and-contract data migration](https://www.prisma.io/docs/guides/database/data-migration)
[Prisma documentation: applying a migration](https://www.prisma.io/docs/orm/migrations/applying-a-migration)
[PostgreSQL 18: ALTER TABLE](https://www.postgresql.org/docs/18/sql-altertable.html)
[PostgreSQL 18: CREATE INDEX](https://www.postgresql.org/docs/18/sql-createindex.html)
The official documentation was checked on 2026-11-23. This article is limited to schema changes in a live relational database; it does not cover moving a database server or ETL. The expand-and-contract example adapts Prisma’s published to status scenario as an illustrative assumption. PostgreSQL locking and DDL behavior is scoped to version 18; Django and Prisma procedures are presented only as examples for those tools. No migration, performance test, backup restoration, or production deployment is claimed to have been performed.