Skip to content
AE DIGITAL
Digital SystemsBy 7 min read

Zero-downtime ecommerce database migrations: expand-contract, backfill and rollback

A practical way to evolve schemas while orders and checkout stay live: additive changes, parallel compatibility, controlled backfills and evidence-led contraction.

Modular data blocks move along two compatible paths while a controlled flow completes the transition

The schema changes while the store keeps writing

An ecommerce database is shared by checkout, catalogue, orders, inventory, promotions and integrations that run at different speeds. A seemingly small change, such as splitting an address, adding a constraint or replacing an identifier type, can collide with live queries, replicas, asynchronous workers and application versions that do not disappear simultaneously. A safe migration is therefore not a clever SQL statement. It is a period during which every deployed component understands enough of the old and new shape to keep commercial invariants intact.

Zero downtime does not mean zero risk, waiting or cost. It means designing each stage so that traffic can continue within observable limits and an anomaly can stop the process before an irreversible loss. An operation described as online may still consume CPU, I/O and temporary space, wait for locks or raise tail latency. Begin with business invariants: no missing order, no negative inventory introduced by the transition and no ambiguous read between representations.

Separate expand, migrate and contract

Expand introduces a compatible shape

Parallel change has three movements. Expand adds columns, tables, indexes or interfaces without removing what the current release needs. The application becomes capable of coexisting with both shapes. A new column will often start nullable or with semantics that avoid an immediate rewrite of every row. Indexes and constraints use the least intrusive method the engine offers, after that method has been tested against the production version and a representative workload.

Migrate moves writes, history and reads

During migrate, the software begins producing the new representation, transfers historical rows and gradually points reads to the new path. Dual writing is not a magic switch. It needs a declared source of truth, a response to partial success and a reconciliation rule. A single application path that updates both forms in the same local transaction is often easier to reason about than two unrelated writers. Failures that prevent convergence must be durable and visible.

Contract removes only proven dead dependencies

Contract begins after queries, jobs, exports and rollback no longer depend on the former shape. The team removes compatibility code, duplicate writes, obsolete columns and indexes. This is the destructive stage and should not share a deployment with expand. Keeping it separate creates a genuine observation window and prevents an application rollback from targeting a schema that has already vanished.

Assess DDL and locking on the actual engine

PostgreSQL can build an index with CONCURRENTLY while allowing inserts, updates and deletes. That convenience has a cost: the operation performs two table scans, waits for relevant transactions and cannot run inside a transaction block. A failed build may leave an invalid index that operators must detect and handle. Capacity, duration, waits and final validity therefore matter as much as the keyword concurrently.

For supported constraints, PostgreSQL can add the definition as NOT VALID. New writes are checked while the historical scan is deferred. VALIDATE CONSTRAINT performs that verification later, with its locking behaviour assessed separately. This splits risk usefully, provided the organisation does not leave a constraint indefinitely unvalidated. Defaults, type changes and table rewrites also depend on the exact operation and server version.

MySQL InnoDB online DDL support varies by operation, algorithm and requested lock. LOCK=NONE can permit concurrent reads and writes for supported changes, but it does not promise negligible cost. A command may rebuild the table, produce substantial temporary work or wait for metadata locks. The correct gate is an execution plan and impact test on the same engine family, version, scale and traffic profile as production.

Run the backfill as a production workload

A backfill that touches millions of rows does not belong inside a synchronous schema migration. Run it as a separate, resumable and idempotent process. Select stable ranges, update only rows that still lack the new representation and store a verifiable cursor. Batches cap lock duration, log volume and replica pressure. Pauses between batches give interactive traffic room to recover.

GitLab documents batched background migrations to avoid one long-running operation. An initial batch size is not a permanent promise. Throughput, query latency, replica lag and I/O should determine when to slow or stop. Every batch must tolerate repetition without corrupting the result. Rows changed while the transfer runs need an explicit rule, such as active dual writing or a conditional update that refuses to overwrite newer data.

  1. Measure the population and define an independent completeness query.
  2. Test a small batch with query plans, timeouts and lock observation.
  3. Run below a rate limit with automatic stops for critical signals.
  4. Reconcile samples and aggregates between old and new representations.
  5. Persist the cursor, failures and exclusions for an auditable restart.

Require technical and commercial gates before switching reads

A completion percentage does not prove correctness. Gates cover completeness, uniqueness, constraints, counts and semantic differences. Compare results from both read paths on real requests or effect-free duplicated traffic. Segment by storefront, currency, order type and edge case. Every mismatch needs an explanation; a broad average must not hide a handful of commercially important orders.

Watch p95 and p99 latency, application and database errors, CPU, I/O, temporary space, lock waits, connections and replica lag. Detect old-column usage through application telemetry, query fingerprints, scheduled jobs and export pipelines. Define stop thresholds and decision ownership before moving the primary path. The new representation must support ordinary traffic and a reasonable peak without assuming that the backfill finishes instantly.

Roll back the application without destroying the bridge

During additive stages, the safest rollback sends reads and behaviour back to the previous path while leaving new database objects in place. Evidence remains available, engineers can correct the application and nobody needs to recreate a dropped column during an incident. If dual writes have diverged, reconcile before resuming. Flipping a flag without deciding which side is authoritative can spread the discrepancy.

Rolling back a backfill does not always mean clearing every new value. Some values may have received legitimate writes after the migration began, and a bulk deletion could lose them. Prefer a stoppable process, record provenance where it is necessary and design a specific compensating action. Schedule contract only when the application rollback window is closed, observation finds no old-shape access and backup restoration has been tested in a compatible environment.

Rehearse with realistic data and concurrency

A tiny copy will not reveal scan duration, log growth or contention. A useful rehearsal reflects data distribution, volume, indexes, replicas and concurrent queries, using protected or representative synthetic data. Simulate mixed application versions, an interrupted backfill, a slow replica and an application rollback. Operators should be able to recognise an invalid index, an unvalidated constraint and a stalled batch queue.

The runbook lists preconditions, approved commands, dashboards, thresholds, owners and points of no return. It distinguishes stopping, which preserves evidence, from compensating, which changes data. A rehearsal should measure detection and decision quality, not only how quickly a script completes. If the procedure depends on a single expert remembering an undocumented command, it is not ready for a high-traffic release.

Build a reversible delivery sequence

The sequence starts with dependency inventory and invariants, then moves through expand, compatible code, controlled dual production, backfill, verification, read switch and eventually contract. Each step owns a gate and leaves evidence. Avoid destructive migrations during application startup: they tie deployment health, DDL duration and rollback to one event that is difficult to control.

To design a sequence aligned with checkout, orders, replicas and asynchronous processes, explore our ecommerce systems services. If you need to assess a concrete migration from lock behaviour through reconciliation, contact AE Digital Agency for a technical review before the release window.

Frequently asked questions

What does expand-contract mean in a database migration?

It means adding a compatible new representation, moving data and traffic while both forms coexist, then removing the old form only after verification and the rollback window.

Does CREATE INDEX CONCURRENTLY have no impact on PostgreSQL?

No. It allows concurrent DML, but requires two scans, may wait for transactions, uses extra resources and cannot run inside a transaction block.

Why should a backfill run in batches?

Bounded, resumable batches limit locks, log volume and replica pressure, adapt to live traffic and isolate rows that require investigation.

When is it safe to drop an old column?

After applications, jobs, exports and rollback no longer use it, business invariants pass, and the agreed observation window has ended.

Sources

  1. Parallel Change — Martin Fowler
  2. CREATE INDEX — PostgreSQL Global Development Group
  3. ALTER TABLE — PostgreSQL Global Development Group
  4. Online DDL Operations — Oracle MySQL
  5. Batched background migrations — GitLab
  6. Avoiding downtime in migrations — GitLab

Related articles

Tell us what isn't working.

We reply within one business day with a first opinion and, if it makes sense, a quote.

Write to us