Change the schema without downtime
Adding a column or changing a type locks a huge table.
Say it like this
I change the schema in expand-then-contract steps, each backward compatible, so old and new code run side by side and the table is never locked.
Basic solution
Expand-then-contract: add the new column nullable, backfill in batches, switch reads, then drop the old one.
Expand, dual write, backfill, switch reads, contract
Each step is a separate deploy and is backward compatible with the one before it. The old column is dropped only after no code reads it and backups have rolled over.
How it works
- Expand: add the new column or table in a form the database can apply without rewriting rows. ADD COLUMN new_col text NULL changes only the table's metadata on Postgres and MySQL 8, so it completes in milliseconds no matter how large the table is.
- Deploy code that writes every change in both the old shape and the new shape (dual write) while still reading only the old shape. From now on, every new row is correct in both.
- Backfill the rows that existed before the change: a job walks the table by primary key in batches (UPDATE ... WHERE id BETWEEN a AND b LIMIT 5,000), copying old-shape data into the new column, and pauses whenever replication lag rises above a threshold.
- Deploy code that reads the new shape. For a while it also reads the old shape and compares the two (a shadow read), logging a metric on any mismatch, so you can prove the backfill is complete before depending on it.
- Stop writing the old shape. Contract: in a later release, after any backup that predates the change has aged out of the restore window, drop the old column or table.
Rules that keep it safe
- Every step must be reversible without a migration: rolling back the code must work against the current schema.
- Never do a step that takes an exclusive lock for longer than a few seconds; create indexes CONCURRENTLY (the database builds the index without blocking writes) and add constraints NOT VALID then VALIDATE (new rows are checked immediately, existing rows in a separate non-blocking pass).
Worked example
Chat app: splitting a text column into message body plus attachments
- messages table: 20B rows, 8 TB, on sharded Postgres. ALTER TABLE ... ALTER COLUMN would rewrite every row and lock each shard for hours.
- Expand: ALTER TABLE messages ADD COLUMN attachments jsonb NULL. Metadata only, runs in milliseconds per shard.
- Dual write: the chat service writes both body (old format with inline attachment markers) and attachments (new column) for every new message. New messages: 1M/s across shards; the extra column adds about 40 bytes each, 40 MB/s.
- Backfill: a job walks each shard by primary key in batches of 5,000, parsing old bodies into the new column. 20B rows / 5,000 = 4M batches; at 2 to 3 batches/s per shard across 64 shards (about 160 a second in all) that is about 20 minutes of wall time per billion rows, roughly 7 hours total, paused whenever replica lag exceeds 2 seconds.
- Shadow read: for 2% of reads, compute attachments from both representations and log a mismatch metric. Zero mismatches for a day means the backfill is complete.
- Contract: a release later, stop writing the old markers; two releases later, strip them from body in another batched job. Rollback at any point only needs a code revert.
Variants and when each wins
Online schema change tools (gh-ost, pt-online-schema-change)
- The tool builds a shadow copy of the table with the new shape, replays ongoing changes into it (gh-ost from the binary log, pt-online-schema-change through triggers), then swaps the names. It wins for type changes MySQL cannot do in place; it needs disk for the copy and a brief lock at the swap.
Native online DDL
- Postgres and MySQL 8 apply many ALTER statements as metadata changes or with concurrent index builds. It wins when it applies, because nothing else is involved; check each operation, since some still rewrite the table.
Versioned rows or schemaless columns
- Each row carries a schema_version, or flexible fields live in a JSONB column. It wins for additive changes because no migration is needed, at the cost of complexity in every reader.
Blue-green database
- A new database with the new schema is created, changes are replicated into it, and traffic is cut over. It wins for rare, large reshapes, because it is clean; it is expensive for anything else.
Default to native online DDL with expand-then-contract; reach for gh-ost on MySQL type changes; keep JSONB for genuinely variable fields, not as a way to avoid thinking about schema.
Failure modes
Lock the table
- Every write hangs for minutes and the service pages. It happens because the ALTER rewrites every row, or because an older database version rewrites the table to add a NOT NULL column with a default. Add the column as nullable, backfill in batches, then add the constraint as NOT VALID and VALIDATE it separately.
Old code hits the new schema
- Errors appear immediately after a deploy, or after a rollback. It happens because a step was not backward compatible, such as dropping a column the previous release still reads. Make one shape change per release, and drop a column only two releases after its last reader is gone.
Backfill floods replication
- Replicas fall minutes behind and read-your-writes breaks for users. It happens because the backfill ran as a single giant UPDATE that generated gigabytes of replication log at once. Use small batches, sleep between them, and pause when lag grows.
Dual-write drift
- Shadow reads keep reporting mismatches that never converge to zero. It happens because some code path still writes only the old shape. Route every write through one function that writes both shapes, count mismatches, and block the cutover until they reach zero.
Index built in the critical path
- Writes are blocked for the duration of an index build. It happens because the index was created without CONCURRENTLY, which takes a lock that excludes writes. Build indexes concurrently, and where supported build them on a replica first.
Interviewer follow-ups
Answer out loud before you open each one.
Why can adding a column with a default be dangerous?
On Postgres before version 11 and on older MySQL versions it rewrites every row to store the default, holding an exclusive lock for the duration. Add the column nullable, backfill in batches, then set the default for new rows only.
How do you rename a column without downtime?
You do not rename in place. Add the new column, dual write, backfill, switch reads, stop writing the old one, drop it later. A rename is an expand-then-contract of five small steps, not one ALTER.
How long should the old column stay after the cutover?
At least until the previous code release can no longer be rolled back to, and until a backup taken before the change has aged out of the restore window. Two releases is a common rule.
How do you migrate a sharded database where shards finish at different times?
Every step must be safe with a mix of migrated and unmigrated shards, so the code reads the new shape when present and falls back otherwise. Track per-shard progress in a table and only contract once every shard has completed.
Connections
- Pairs with
- Deploy without downtime · Spread reads across replicas · Ship dark, release gradually · Batch small operations
- Pulls against
- Commit across two stores