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.
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:
- Expand: add the new column or table, nullable and without defaults that rewrite rows.
- Migrate: write to both places and backfill old rows in batches.
- Contract: switch reads, then drop the old column a release later.
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.
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_Sourceon 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.