2 min read

Zero-downtime migrations on a 400M-row table

Adding a column to a table with 400 million rows locked our checkout for eleven minutes once. This is the playbook we use since then, and it has not failed us in two years.

Rows of servers with blue status lights in a data centre

An ALTER TABLE on a large MySQL table can copy the whole table, hold metadata locks and fill the replication lag for an hour. Online DDL helps, but not for every change. The safe way is to never change a column in place: you expand the schema first, move the data in small steps and contract it at the end.

Expand, migrate, contract

Every risky change becomes three deployments:

  1. Expand: add the new column or table, nullable and without defaults that rewrite rows.
  2. Migrate: write to both places and backfill old rows in batches.
  3. Contract: switch reads, then drop the old column a release later.
php
Schema::table('shipments', function (Blueprint $table) {
    $table->string('carrier_code', 16)->nullable()->after('carrier_id');
});

Backfill in batches

Never update millions of rows in one statement. Walk the primary key in chunks, keep each transaction short and pause between batches so replicas can keep up.

php
Shipment::whereNull('carrier_code')
    ->chunkById(5000, function ($shipments) {
        Shipment::whereKey($shipments->modelKeys())->update([
            'carrier_code' => DB::raw('(select code from carriers where carriers.id = shipments.carrier_id)'),
        ]);

        usleep(200_000); // let the replicas catch up
    });

Tip

Watch Seconds_Behind_Source on your replicas while the backfill runs and stop the job automatically when it grows above a few seconds.

The cut-over

Switch reads behind a feature flag, compare the results of old and new column for a day and only then remove the old code path. Dropping the old column is the last, most boring step, and that is exactly how it should feel.