Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

Zero-downtime database migrations: how to change production schemas safely

A zero-downtime schema change is not about finding one magic ALTER TABLE command. It is a process of preserving compatibility between old and new application versions, controlling locks and operation cost, migrating existing data, and delaying destructive changes until old code is no longer serving traffic. In practice, the safest approach is to split the change into several phases, commonly described as expand, migrate, switch and contract.

Published Written by Reading time 22 min read
On this page Contents: quick navigation between sections

Zero downtime is a compatibility problem, not one ALTER TABLE

During a rolling deployment, at least two application versions can serve traffic at the same time. A migration is safe only when the schema remains compatible with code that is still running.

GitLab documents many changes that must be split across releases because older processes may still expect a column, table or previous default value. [9]

At large scale, Stripe used a staged online-migration pattern with dual writes, read-path switching, write-path switching and only then removal of the old data model. [11]

Expand-contract: the core zero-downtime pattern

PhaseActionExit condition
ExpandAdd new columns, tables or indexes without removing the old modelOld and new application versions both work
MigrateBackfill or dual-write existing dataData is complete and consistency is monitored
SwitchMove reads and writes to the new modelThe full rollout uses the new structure
ContractRemove old columns, tables or compatibility codeRollback to old code is no longer required

In the expand phase, add new structure without removing the old one. Old application versions should continue to work while new versions can start using the expanded schema.

In migrate or backfill, existing data is copied or populated. In switch, reads and writes move to the new model. Contract removes the old structure only after no active code depends on it. [9][11]

The key rule is simple: destructive change should be the final phase, not the first.

Application rollout and schema rollout must be designed together

A safe sequence usually means a compatible schema change first, application rollout second, data migration next and cleanup last. GitLab separates regular migrations from post-deployment migrations to avoid changes that are incompatible with processes still serving requests. [9][10]

Making a column NOT NULL, dropping a column or renaming it can be technically fast and still break an older application build.

Rollback should be designed before deployment. If the old code expects a column that has already been dropped, rolling back the application will not restore compatibility.

PostgreSQL notes that a table lock can wait for conflicting locks to be released and, once acquired, is held until the end of the transaction. This is another reason to avoid long transactions around DDL. [4]

Adding columns in PostgreSQL: fast does not always mean safe

PostgreSQL 18 documents that adding a column with a non-volatile constant DEFAULT does not require rewriting all existing rows. The value is stored in metadata and returned when rows are read, so the operation can be very fast even on a large table. [1][2]

A volatile DEFAULT, a stored generated column, an identity column or some constrained domain cases can still force a rewrite of the table and indexes. [2]

Always evaluate the exact DDL definition rather than assuming every ADD COLUMN is cheap.

Constraints: separate rule creation from validation of old data

PostgreSQL can add CHECK or foreign-key constraints as NOT VALID, skipping the initial full scan of existing rows. New INSERT and UPDATE operations are still checked. [2]

VALIDATE CONSTRAINT can then verify historical rows in a separate step. PostgreSQL documents this pattern as a lower-impact way to add a foreign key. [2]

This fits expand-contract well: enforce the rule on new writes first, repair old data next, then validate the whole table.

PostgreSQL indexes: CREATE INDEX CONCURRENTLY has trade-offs

A normal CREATE INDEX blocks writes to the table until the build finishes. CREATE INDEX CONCURRENTLY does not take locks that prevent normal INSERT, UPDATE and DELETE. [3]

The concurrent mode does more work, including multiple scans and waits for relevant transactions, so it usually takes longer and consumes more resources. [3]

If the build fails, PostgreSQL can leave an index marked INVALID. It then needs to be dropped or rebuilt. CREATE INDEX CONCURRENTLY also cannot run inside a transaction block. [3]

Backfilling large tables: migrate data in batches

A single massive UPDATE can create high I/O, long transactions and replication pressure. GitLab uses batched background migrations for large tables instead of full backfills inside the deployment migration. [9][10]

Stripe separated large-scale copying from live traffic and kept old and new representations in sync until the final cutover. [11]

A good backfill should be restartable, checkpointed or range-based, observable and throttleable without rolling back the whole release.

Renaming a column is an application change, not cosmetic DDL

A direct rename immediately breaks code that still uses the old column name. GitLab treats renaming columns as a multi-step zero-downtime procedure. [9]

A general pattern is to add a new column, dual-write, backfill, switch reads, then remove the old column. Stripe describes the same staged principle in large online data migrations. [11]

A direct rename can be fine in a controlled maintenance window, but should not be assumed safe during rolling deployment.

DROP COLUMN and DROP TABLE belong at the end

GitLab separates column removal across releases because active processes can still cache the schema or reference the old field. [9]

For tables, the recommended sequence is to remove application usage first and only in a later release remove foreign keys and the table itself. [9]

Destructive DDL reduces rollback options. If storage allows, cleanup should happen after a period of stable observation.

MySQL 8.4: INSTANT, INPLACE and COPY mean different things

MechanismWhat can be fastHow blocking can be reducedMain caveat
PostgreSQLADD COLUMN with suitable constant DEFAULT without rewriteCREATE INDEX CONCURRENTLY, NOT VALID + VALIDATEConcurrent builds cost more and can leave INVALID indexes
MySQL 8.4 InnoDBALGORITHM=INSTANT for supported changesINPLACE/INSTANT and LOCK=NONE where supportedMetadata locks, rebuilds and replication lag remain possible
gh-ostCopy into ghost table away from the main tableThrottling and controlled atomic cutoverImportant limitations, including foreign keys

MySQL 8.4 can perform ALTER TABLE with INSTANT, INPLACE or COPY. INSTANT mainly updates metadata, INPLACE can avoid the traditional full copy but may still rebuild the table, while COPY creates a new copy and moves rows. [5]

If ALGORITHM is omitted, MySQL prefers INSTANT, then INPLACE, and can fall back to COPY when required. [5]

On large tables, explicitly requiring an acceptable algorithm can prevent an unexpected fallback to a much more expensive operation.

MySQL online DDL does not mean zero locks or zero cost

MySQL documents that even INSTANT and INPLACE operations may briefly need an exclusive metadata lock. INPLACE can also rebuild a table while still permitting concurrent DML. [5][6][7]

Long-running online DDL can create replication lag, and rollback of a failed operation can be expensive. MySQL also notes there is no general pause or CPU/I/O throttle mechanism for large table-rebuilding online DDL operations. [8]

LOCK=NONE can be used to require concurrent reads and writes and fail the operation if that concurrency level is not available. [6]

gh-ost: when native ALTER TABLE is not enough

gh-ost is GitHub's online schema migration tool for MySQL. It copies rows to a ghost table, follows changes through the binary log, supports throttling and performs a controlled cutover. [12][13]

The default cutover is an atomic, short blocking swap between the original and ghost tables. If the required lock cannot be obtained in time, cutover can abort and be retried. [13]

gh-ost has important constraints. Its documentation lists, among other things, no support for foreign keys on the migrated table and a requirement for a primary key or another shared unique key. [14]

Rolling back code and rolling back data are different problems

If a migration only adds a column or table, it is often possible to roll back application code without rolling back the schema. That is one of the main benefits of expand.

After dual writes or backfill begin, rollback must account for which representation contains the latest valid data. Stripe kept both models synchronized until reads and writes were fully switched. [11]

After destructive contract, rollback becomes much harder. Cleanup should therefore be a separate deployment after a stabilization period.

What to monitor during a migration

At minimum monitor query latency, lock waits, CPU, I/O, storage usage, application error rate and replication lag. MySQL explicitly warns that long online DDL can increase replication lag. [8]

For backfills, track throughput, errors, backlog and impact on normal workload. GitLab runs large data migrations in the background and exposes progress monitoring. [9][10]

With tools such as gh-ost, use throttling and postpone cutover when the system is under high load. [12][13]

A practical zero-downtime migration plan

ChangeRisk during rolling deploymentSafer pattern
Add nullable columnUsually low, but engine and definition matterAdditive first, enable usage later
Add indexCan block writes or increase I/OConcurrent/online mode plus monitoring
Add constraintLarge table scan and locksSeparate creation and validation where supported
Rename columnOld code loses the field immediatelyNew column, dual write, switch, cleanup
DROP COLUMN/TABLERemoves easy rollbackDelete only after old code is fully detached
Change typePossible table rewrite and incompatibilityNew column, backfill, switch

First classify the change as additive, data migration or destructive. Then verify the exact lock level and execution method in the database version you actually run, because PostgreSQL and MySQL have different semantics. [2][5]

The plan should preserve old/new application compatibility, make backfill observable, test on representative data volume, define throttle and abort conditions, and keep cleanup separate. [9][11][12]

Zero downtime does not mean zero impact. The goal is correctness and availability with acceptable latency and resource cost.

  • Expand first, contract last.
  • Do not combine new-code rollout with destructive DDL in the same step.
  • Backfill large tables in batches outside the deployment critical path.
  • In PostgreSQL, use CREATE INDEX CONCURRENTLY when blocking writes is unacceptable, and inspect index state after failure.
  • For supported PostgreSQL constraints, consider NOT VALID followed by VALIDATE CONSTRAINT.
  • In MySQL, control ALGORITHM and LOCK explicitly when fallback to a more expensive mode is unacceptable.
  • Define abort, throttle and rollback conditions before starting.
  • Run DROP COLUMN or DROP TABLE only after full rollout, backfill and an observation period.

The safest production migration is multi-stage. First expand the schema in a way that old application versions can still tolerate, then backfill data and switch reads and writes, and only after full rollout and observation remove old columns, indexes or tables. PostgreSQL and MySQL provide mechanisms that reduce blocking, but they do not eliminate I/O cost, lock contention, replication lag or application-level risk. Zero downtime comes from compatibility, small steps, observability and the ability to pause or abort the process, not from an online DDL label alone.

Database Migrations Zero Downtime PostgreSQL MySQL Schema Migration Expand Contract Backfill Online DDL gh-ost Production Database

Frequently asked questions

Does zero-downtime migration mean the database takes no locks?

No. Even operations described as online can take brief locks or create extra I/O. MySQL documents brief exclusive metadata locks for some INSTANT and INPLACE operations. [5][6]

Can PostgreSQL safely add a column with DEFAULT?

A non-volatile constant DEFAULT can avoid a full table rewrite. Volatile defaults and some other definitions can still require one. [1][2]

Does CREATE INDEX CONCURRENTLY never block the application?

It does not block normal INSERT, UPDATE and DELETE, but it takes longer, does more work and can leave an INVALID index after failure. [3]

Can a foreign key be added without immediately scanning the whole table?

In PostgreSQL, NOT VALID can defer validation, followed later by VALIDATE CONSTRAINT. New writes are checked after the constraint is added. [2]

Why is column rename risky during rolling deployment?

Older application instances still refer to the old name. GitLab therefore uses staged procedures for renames. [9]

How should millions of rows be backfilled?

Use batched background processing outside the critical deployment path, with monitoring and throttling. GitLab and Stripe both document staged approaches. [9][10][11]

What does ALGORITHM=INSTANT mean in MySQL?

For supported operations, MySQL changes mainly metadata without modifying table data, though a brief metadata lock may still be needed. [5]

Does ALGORITHM=INPLACE mean no table rebuild?

No. MySQL documents INPLACE operations that still rebuild the table. [5][7]

Can MySQL online DDL cause replication lag?

Yes. MySQL explicitly warns that long-running online DDL can cause replication lag. [8]

When does gh-ost make sense?

For large MySQL tables when you need more control over copying, throttling and cutover than direct ALTER TABLE provides, while respecting its limitations. [12][13][14]

Does rolling back application code require rolling back the migration?

Not always. Additive schema can often remain in place while code rolls back. Destructive changes can remove that option.

Should DROP COLUMN happen in the same deployment as the code switch?

Usually not during rolling deployment. It is safer after full rollout and confirmation that no active code uses the column. [9]

Sources and references

  1. PostgreSQL 18 Documentation, Modifying Tables↩1↩2
  2. PostgreSQL 18 Documentation, ALTER TABLE↩1↩2↩3↩4↩5↩6↩7
  3. PostgreSQL 18 Documentation, CREATE INDEX↩1↩2↩3↩4
  4. PostgreSQL 18 Documentation, LOCK↩
  5. MySQL 8.4 Reference Manual, ALTER TABLE Statement↩1↩2↩3↩4↩5↩6↩7
  6. MySQL 8.4 Reference Manual, InnoDB Online DDL↩1↩2↩3
  7. MySQL 8.4 Reference Manual, Online DDL Operations↩1↩2
  8. MySQL 8.4 Reference Manual, Online DDL Limitations↩1↩2↩3
  9. GitLab Docs, Avoiding downtime in migrations↩1↩2↩3↩4↩5↩6↩7↩8↩9↩10↩11↩12
  10. GitLab Docs, Zero-downtime upgrades↩1↩2↩3↩4
  11. Stripe Engineering, Online migrations at scale↩1↩2↩3↩4↩5↩6↩7
  12. GitHub, gh-ost↩1↩2↩3↩4
  13. GitHub, gh-ost cut-over design↩1↩2↩3↩4
  14. GitHub, gh-ost requirements and limitations↩1↩2

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning