Product engineering

Make Database Migrations Compatible with Rolling Deployments

Plan rolling database migrations through compatible expansion, transitional writes, controlled backfill, validation and delayed contraction.

A rolling deployment creates a period in which old and new application instances share the same database. A migration that works after every instance is upgraded may still break that transitional period. Designing compatibility across versions is therefore part of the release, not an optional concern to revisit if deployment fails.

PostgreSQL’s documentation on altering tables describes supported schema changes and their behavior. Exact locking and execution costs depend on the operation and database version. This guide focuses on the application-level sequence around those changes; consult the documentation for the database you actually run before choosing production commands.

Map the versions that can coexist

List the application versions, workers and scheduled jobs that may access the schema during rollout. The web deployment is not necessarily the only consumer. A reporting job or an older administrative tool can preserve an assumption long after the main service changes.

For a fictional customer-management application, suppose the team wants to replace a single display-name field with separate given-name and family-name fields. An older worker may still read or write the original field. The migration needs to account for that consumer before removing or changing the representation.

Record the deployment order and the maximum expected overlap. If rollback can restore an older application, include that version in the compatibility review. A migration is not safe merely because the happy-path rollout completes quickly when nothing goes wrong.

Separate structure from meaning

A schema change can be mechanically additive and still change application behavior. A new default, constraint or trigger may affect old writes. A renamed field can also hide a semantic change that a simple copy will not preserve.

In the name example, splitting one string into two fields is not a reliable universal transformation. Some names do not fit the proposed model, and the original value may contain formatting the application needs to preserve. The data model requires product reasoning before any migration sequence can make it correct.

Document the intended meaning of each representation and how incomplete or ambiguous records will behave. Do not let the migration script invent information merely to populate required fields. A nullable or explicitly unresolved state may be more honest than a fabricated conversion.

Expand the schema before requiring the new fields

Where appropriate, introduce new fields or structures in a form that old code can tolerate. Deploy the structural change separately from making the new representation mandatory. This creates room to verify compatibility and populate data without forcing every step into one release event.

Check the effect on existing queries and writes. Some clients use broad selection patterns or positional assumptions that an added field can disturb. The fact that an operation is called additive does not exempt it from testing against real consumers.

Review the database-specific cost of the expansion. A change may require a lock or a table scan depending on the operation and version. Estimate the effect using representative evidence and choose an execution approach appropriate to the production workload.

Deploy code that understands the transition

The transitional application may need to read both representations or write them consistently. Define the rule explicitly: which value is authoritative, when fallback is allowed and how discrepancies are detected. Avoid scattering inconsistent fallback logic across several handlers.

If using dual writes, consider partial failure and transaction boundaries. Two writes in the same database transaction have different failure properties from a database update followed by an external call. The design must match the actual storage architecture.

Keep the transition bounded. Assign an owner and a removal condition for compatibility code. It is useful because it supports a migration; leaving it indefinitely can make future behavior harder to understand and multiply the number of states the application must handle.

Backfill in controlled, observable batches

A backfill should identify its progress and be safe to resume. Use stable selection criteria and record which records have been processed or which range is complete. A script that restarts from the beginning after interruption may create unnecessary load or repeat transformations incorrectly.

Choose batch size and pacing based on measured impact. Watch database load, locks, replication behavior and application latency as relevant to the environment. A backfill is competing with production work even if it runs outside the main application process.

Treat ambiguous or invalid records separately. Record an exception with enough context for review rather than silently coercing it into a convenient value. The migration’s completion report should distinguish successfully transformed data from accepted limitations and unresolved cases.

Protect against writes during the backfill

Data can change while a long backfill runs. Decide how the backfill interacts with current application writes. A stale transformation must not overwrite a newer value without an intentional rule.

Possible approaches depend on the database and model: version checks, conditional updates, transactional reads or a controlled write path may be relevant. Evaluate the mechanism in the actual environment instead of assuming that processing records in order prevents races.

Test a record updated at the same time as the backfill. Confirm the resulting state and any retry behavior. This is a more meaningful check than running the migration only against a static copy where no application activity occurs.

Validate data relationships, not just row counts

A completed script and matching counts do not prove semantic correctness. Compare the relationships the application relies on, including null handling, uniqueness and referential integrity where applicable. Use targeted samples and aggregate checks appropriate to the transformation.

For the customer-name change, verify that the original display value remains available where needed and that unresolved cases are represented honestly. A count showing every row has two strings would be actively misleading if the strings were produced by an invalid splitting rule.

Keep the validation query or procedure with the migration record. Future operators should be able to repeat it and understand what it proves. Record the time and dataset scope, because new writes can change the state after the initial check.

Switch reads only after the evidence is ready

Moving the read path to the new representation is a separate decision. Confirm that the necessary data exists, current writes maintain it and the application handles documented exceptions. Consider a limited rollout or comparison mode when it can reveal discrepancies safely.

If comparing old and new outputs, define what constitutes a meaningful difference. Some formatting differences may be expected, while changed authorization or business outcomes may be unacceptable. Avoid logging sensitive record contents simply to make comparisons easy.

Keep a clear recovery option during this stage. Returning reads to the old representation is useful only if it remains current and compatible. A stale old field is not a reliable fallback just because it still exists in the schema.

Add stronger constraints at the right time

A new non-null or uniqueness requirement should follow evidence that the data and current write paths satisfy it. Applying the constraint too early can break older consumers or block legitimate unresolved cases.

Review how the database validates the constraint and what operational effect the change may have. Some systems support staged validation mechanisms; others require a different sequence. Follow version-specific documentation and test the procedure under representative conditions.

Keep product meaning ahead of convenience. A constraint should encode a true invariant of the application, not merely make a query easier. If the real domain permits an exception, the schema needs a deliberate representation rather than a placeholder that pretends the invariant holds.

Contract only after old consumers are gone

Remove obsolete fields, tables or compatibility code after confirming that no supported consumer depends on them. Check background jobs, exports, dashboards and rollback procedures as well as the main application. Repository search is useful, but runtime evidence and ownership review may reveal consumers outside the repository.

Plan destructive cleanup as its own change. Preserve the recovery information required by the organization’s policies and document what can no longer be reversed after removal. Do not hide the loss of a recovery path inside an unrelated deployment.

Update documentation, schema descriptions and operational checks to reflect the final model. The migration is not complete while runbooks and examples continue teaching the old representation to new engineers.

Rehearse interruption and mixed-version behavior

Test old code against the expanded schema, new code before and after backfill, and the permitted rollback combination. Include interrupted backfills and concurrent writes. These are the states that make a rolling migration different from a one-time development database update.

Record timing and limitations of the rehearsal. A small environment can verify logic without establishing production execution time. Keep those claims separate and obtain additional evidence where scale or locking is consequential.

A compatible migration is a sequence of supported states. By making expansion, transitional writes, backfill, read switching and contraction explicit, the team can deploy gradually without relying on every component changing at the same instant.

Continue reading

Test a Third-Party Integration Without Depending on Production

Design an Export Job That Does Not Exhaust Memory