Summary#
Real systems change their data while serving traffic: renaming a column, splitting a table, moving to a new database, resharding. Doing this without downtime follows a few patterns. Expand and contract makes every schema change backward compatible: add the new shape, migrate code and data, then remove the old shape. Online schema change tools (gh-ost, pt-online-schema-change, Postgres concurrent operations) alter big tables without long locks. To move data between stores, keep the target in sync either with dual writes from the application or, more safely, a backfill plus change data capture (CDC). Verify with shadow reads, then cut over gradually with a tested rollback path. For events and messages, evolve schemas with Avro/Protobuf compatibility rules.
Why It Exists#
A naive migration is "stop the app, run the script, start the app". For a 2 TB table, a blocking ALTER TABLE or a copy can take hours, and many businesses cannot be down for minutes. Worse, application code is deployed gradually: during a rolling deploy, old and new versions run side by side, so the database must work with both. Data migrations are also among the riskiest changes: a bug can corrupt data that cannot be restored without loss. Zero-downtime migration techniques turn one risky big step into several small, reversible ones. This page builds on Partitioning and Sharding.
How It Works#
Expand and contract#
Expand and contract (also called parallel change) splits a breaking change into backward-compatible steps. Example: rename users.fullname to users.display_name.
- Expand: add
display_name(nullable). Old code ignores it. - Write both: deploy code that writes both columns and still reads
fullname. - Backfill: copy
fullnameintodisplay_namefor existing rows, in small batches. - Read new: deploy code that reads
display_name(falling back if null during transition). - Stop writing old: deploy code that writes only
display_name. - Contract: drop
fullnameonce nothing reads it (check query logs).
Each step is deployable and reversible on its own, and at every point both the previous and the current code version work. The same rules make schema migrations safe in CI/CD: never rename or drop in one step, add columns as nullable or with a default, and backfill separately from the schema change. See Deployment and CI/CD.
-- Backfill in batches to avoid long locks and replica lag
UPDATE users SET display_name = fullname
WHERE id > :last_id AND id <= :last_id + 5000 AND display_name IS NULL;
-- repeat with the next :last_id; sleep briefly between batches if replicas lagExpand and contract, in depth#
Why compatibility is not optional. In a rolling deploy, some servers run version N of the code while others run N-1, for minutes or hours. If a deploy fails and you roll back, N-1 runs against whatever schema N left behind. Queued jobs, cached query plans and long-lived workers may be older still. So the rule is: the schema at every moment must work with every code version that might be running. Expand and contract is just a procedure that guarantees it.
A catalogue of common changes.
| Change | Safe recipe |
|---|---|
| Add a nullable column | One step. Old code ignores it. |
| Add a column with a default | One step where the database makes it metadata-only (PostgreSQL 11+ for constant defaults, MySQL 8 INSTANT). Otherwise add it nullable, backfill, then set the default. |
| Rename a column | Add new, write both, backfill, read new, stop writing old, drop old. |
| Change a column's type | Same as rename: a new column of the new type, converted during backfill. Converting in place usually rewrites the table under a heavy lock. |
| Make a column NOT NULL | Backfill. Then in PostgreSQL, add CHECK (col IS NOT NULL) NOT VALID, VALIDATE CONSTRAINT (which scans without blocking writes), and SET NOT NULL. From version 12, that last step uses the validated check and skips its own scan. |
| Add a foreign key | Add it NOT VALID, then VALIDATE CONSTRAINT separately. |
| Add a unique constraint | CREATE UNIQUE INDEX CONCURRENTLY, then attach it with ADD CONSTRAINT ... USING INDEX. |
| Split a table | New table, dual-write or CDC into it, backfill, move reads, move writes, drop old columns. |
| Drop a column | Remove all code references first, deploy, wait, then drop. Some ORMs select every column and break if one disappears, so check. |
The lock queue trap. In PostgreSQL, most ALTER TABLE forms need an ACCESS EXCLUSIVE lock, even if only for a millisecond. If a long-running query holds a weaker lock on the table, the ALTER waits. Every new query on that table then queues behind the ALTER, so a "metadata-only" change can freeze the table for as long as the slow query runs. The fix is to set a short lock_timeout (for example SET lock_timeout = '2s') on the migration session and retry with backoff if it times out. MySQL has the equivalent metadata-lock problem, controlled by lock_wait_timeout.
Separate schema deploys from code deploys. Run migrations as their own pipeline step, before the code that needs them (for expansions) and after the code stops using the old shape (for contractions). Tools such as Flyway, Liquibase, Rails and Django migrations, and Atlas track which migrations have run. But they do not make a migration safe. A reviewer, or a linter such as squawk for PostgreSQL, must check each one for locking and rewrites.
Backfill arithmetic. Copying 500 million rows in batches of 5,000 is 100,000 batches. If each batch takes 50 ms and you sleep 50 ms between batches to let replicas keep up, the backfill takes 100,000 × 0.1 s = 10,000 s, about 2.8 hours. Doubling the batch size roughly halves the time but doubles lock durations and replica-lag spikes. Good backfill jobs adapt: they speed up when replica lag and p99 latency are low, and back off when they rise. Iterate by primary key ranges (WHERE id > :last_id ORDER BY id LIMIT 5000), not OFFSET, which rescans skipped rows and gets slower as it goes.
Reading during the transition. Between "write both" and "backfill done", some rows have the new column filled and some do not. Code that reads the new column must fall back (COALESCE(display_name, fullname)) until the backfill finishes and is verified. Only then remove the fallback.
Expand and contract outside SQL. The same pattern applies to API fields, cache key formats, message formats and file layouts. Make the new form readable before anyone writes it, write both while readers move, then stop writing the old form and finally remove support for reading it.
Online schema change tools#
Some schema changes rewrite or lock the table. For large tables, use tools that make the change online:
- gh-ost (GitHub, MySQL): creates a shadow table with the new schema, copies rows in chunks, and applies ongoing changes by reading the binlog, then swaps the tables with a brief lock. Throttles itself on replica lag and can be paused.
- pt-online-schema-change (Percona, MySQL): similar, but uses triggers on the original table to capture changes.
- MySQL 8 instant and in-place DDL: many operations (adding a column at the end, for example) are metadata-only.
- PostgreSQL:
ADD COLUMNwith a constant default is metadata-only since version 11;CREATE INDEX CONCURRENTLYbuilds indexes without blocking writes; add constraints asNOT VALID, thenVALIDATE CONSTRAINTseparately. Set a lowlock_timeoutso a migration waiting for a lock does not block all traffic behind it. Tools like pg-osc and pgroll automate patterns. - Vitess and PlanetScale run online schema changes as a managed workflow.
Online schema change tools, in depth#
How gh-ost works.
- Create a ghost table with the original structure and apply the ALTER to it. It is empty, so this is instant.
- Connect to a replica (or the primary) as if it were a replica, and read the row-based binlog, capturing every insert, update and delete on the original table.
- Copy existing rows into the ghost table in primary-key chunks (
INSERT IGNORE ... SELECT ... WHERE id BETWEEN a AND b), while also applying binlog events to it. Binlog events win over copied rows because they are newer, which is why the copy usesINSERT IGNORE, never overwriting. - Throttle based on replica lag, load metrics or a flag file, so the copy can be paused at any time.
- Cut over when the ghost table has caught up: briefly lock the original table, apply the last events, and atomically rename the original to
_oldand the ghost to the original name. Writes block for a second or so.
Because it uses the binlog instead of triggers, gh-ost adds no work to each write on the primary. It also has limitations, notably that it does not support tables with foreign keys.
How pt-online-schema-change works. It also builds a new table and copies chunks, but captures concurrent changes with AFTER INSERT/UPDATE/DELETE triggers on the original table that write each change into the new table. Triggers run inside every write transaction, adding latency and lock contention on busy tables. In return, pt-osc handles foreign keys, with several strategies for re-pointing child tables.
Native online DDL. MySQL 8.0 can add columns with ALGORITHM=INSTANT (a metadata change, with later versions removing the restriction that the column go last). ALGORITHM=INPLACE builds indexes without blocking writes, though replicas apply the DDL serially, so a long in-place build can still lag replicas by the same duration. PostgreSQL's rules of thumb:
- Metadata-only: adding a nullable column, adding a column with a constant default (version 11+), dropping a column (the space is reclaimed later), and raising a
varcharlimit. - Full rewrite under
ACCESS EXCLUSIVE: most type changes, and adding a column with a volatile default such asrandom(). CREATE INDEX CONCURRENTLYdoes two table scans and waits for old transactions. If it fails, it leaves anINVALIDindex that must be dropped.REINDEX CONCURRENTLY(version 12+) rebuilds bloated indexes online.
Versioned-schema tools. pgroll (PostgreSQL) automates expand and contract by serving both the old and the new schema at once. Each version is a set of views in its own schema, with triggers keeping the old and new columns in sync. Old application instances connect to the old version and new ones to the new, and the migration is completed or rolled back as a single command.
Distributed databases. In a cluster with hundreds of nodes, you cannot change the schema everywhere at the same instant, so different nodes will briefly run different versions. Google's F1 and CockroachDB solve this with schema changes that pass through intermediate states, each compatible with its neighbours (see the deep dive below). Vitess and PlanetScale run gh-ost-style or VReplication-based online DDL across every shard, with a single command to monitor, cut over, or revert a change. PlanetScale's revert keeps the old table in sync for a period after cutover, so a bad ALTER can be undone without losing data.
Choosing. Use native instant or concurrent DDL when the operation supports it. It is the simplest and fastest option. Use gh-ost (or Vitess online DDL) for large MySQL tables when the change would rewrite the table, and pt-osc when foreign keys are involved. In PostgreSQL, design the change as expand and contract with CONCURRENTLY and NOT VALID, and reach for pgroll or pg-osc when a rewrite is unavoidable. Always rehearse on a production-sized copy to measure duration and replica lag.
Moving data: dual writes vs CDC backfill#
To move data to a new store (new database, new shard layout, new schema), the target must catch up with existing data and keep up with ongoing writes.
Dual writes: the application writes to both old and new stores.
- Simple to start, but the two writes are not atomic. If the second write fails or the process crashes between them, the stores diverge silently. Ordering can differ under concurrency.
- Requires a backfill for old data anyway, and reconciliation jobs to fix drift.
Backfill plus CDC: copy a consistent snapshot to the target, then stream every change from the source's log (binlog, WAL) to the target.
- The database log is the single source of ordered truth, so the target converges exactly.
- No application changes during the copy; tools such as Debezium, AWS DMS, Vitess VReplication and gh-ost-like copiers do this.
- Needs transformation logic if schemas differ, and monitoring of lag.
Prefer CDC when the source supports it. If you must dual-write, make the old store the source of truth, write to the new store asynchronously through an outbox, and run continuous reconciliation. See Change Data Capture.
Dual writes vs CDC, in depth#
The two ways dual writes go wrong. First, partial failure. The application writes to the old store, then crashes or times out before writing to the new one. The new store silently misses the change. Retries help, but there is always a window. Second, reordering under concurrency:
Both requests succeeded, but the stores disagree, because the two writes in each request are not ordered as a unit. Locks or version checks on the new store (only write if the version is newer than what is stored) fix reordering, but not partial failure.
Why CDC converges. The source database's log (MySQL binlog, PostgreSQL WAL through logical decoding, the MongoDB oplog, DynamoDB Streams) already contains every committed change, exactly once, in commit order. A CDC pipeline reads it from a recorded position, so after a crash it resumes from the last applied position, and applying changes idempotently (upserts keyed by primary key) makes replays harmless. The target therefore converges to the source's state. It may lag by seconds, but it will not drift.
Snapshot plus stream, and where they meet. The pipeline must start streaming exactly at the point the snapshot reflects. Two approaches:
- Snapshot at a position. Open a consistent snapshot (a repeatable-read transaction in PostgreSQL, or
FLUSH TABLES WITH READ LOCKbriefly in MySQL to read the binlog position), copy everything, then stream from that position. It is simple, but a long snapshot holds back log cleanup on the source. - Incremental, watermark-based snapshots. Copy the table in chunks while streaming continues, and use low and high watermark markers in the log to resolve which copied rows are superseded by streamed changes. This is the DBLog approach (Netflix), adopted by Debezium's incremental snapshots. It can be paused, resumed, and re-run for a single table.
CDC carries state, not intent. A CDC event says "row 42 changed from these values to those". It does not say why. For a migration this is exactly what you want: the target needs a faithful copy. But if a consumer needs business meaning (send an email because the order shipped, as opposed to a support agent fixing a typo in the address), raw CDC forces it to reverse-engineer intent from column diffs. In that case, publish explicit domain events through an outbox. See Distributed Transactions and Change Data Capture.
When migration is driven by load. Sometimes the trigger is not a new schema but a workload the current store cannot carry. Estimate before deciding. A view-counting system receiving 70 billion events a day averages about 700,000 writes per second, more than an order of magnitude beyond the roughly 10,000 writes per second a well-tuned relational node handles. Yet the state is small: about 4 billion videos at 16 bytes each (ID plus count) is about 64 GB. That combination of huge write rate and small state points to a migration toward stream aggregation and an in-memory or LSM-based store, rather than a bigger relational box. Similarly, a ride-hailing service that writes every driver's location straight into its main database every few seconds, and runs proximity queries over those rows, will saturate it. Moving that hot, ephemeral data to a purpose-built geospatial store (for example Redis geo commands) is a data migration of a workload. You can move it with the same discipline: run both paths, compare, and cut over gradually.
Making dual writes safer when you must. Some sources have no usable CDC (a third-party SaaS, a legacy store). Then:
- Keep one store as the source of truth, and treat the other as a derived copy.
- Write the copy asynchronously from an outbox or queue in the same transaction as the source write, never inline from the request.
- Use version numbers on the target so reordered updates cannot regress it.
- Run continuous reconciliation that compares the two and repairs the target.
Stripe's published approach to large online migrations follows a related four-phase sequence: dual-write to old and new, move reads to the new store, move writes to the new store, then remove the old data. Each phase is verified before the next one starts.
Shadow reads and verification#
Before trusting the new store, prove it returns the same answers:
- Shadow reads (dark reads): for a sample of requests, read from both stores, return the old result to the user, and log any mismatch. Fix bugs until mismatches are near zero.
- Data checks: row counts per partition, checksums of ranges (for example a hash of each 10,000-row chunk), and full diff jobs for critical tables.
- Shadow writes: for new services, send real traffic to the new path and compare outputs without exposing them.
- Performance testing: shadow traffic also shows whether the new store handles production load and latency.
GitHub's Scientist library popularised the "run old and new, compare, return old" pattern for code paths; the same idea works for data stores.
Verification, in depth#
Chunked checksums. Comparing billions of rows one by one is too slow, so compare chunks instead. For each primary-key range (say 10,000 rows), compute a hash of the concatenated row values on both sides, for example md5(string_agg(row_text, ',' ORDER BY id)) in PostgreSQL or BIT_XOR(CRC32(CONCAT_WS(...))) in MySQL. Matching hashes mean the chunk matches. Mismatched chunks are re-compared row by row. Tools that do this include pt-table-checksum (MySQL replicas), Vitess VDiff, TiDB's sync-diff-inspector, and AWS DMS data validation.
Comparing a moving target. Both stores change during the comparison. Options:
- Compare at the same log position: pause applying CDC to the target, record the source position, and compare a snapshot of the source at that position with the target. VDiff stops replication briefly to line up positions.
- Compare and recheck: on a mismatch, wait for the CDC lag to pass and compare that chunk again. Only report chunks that still mismatch after a recheck.
Normalise before you compare. Many "mismatches" are representation differences, not data differences:
- Timestamp precision (microseconds versus milliseconds) and time zones.
- Floating point formatting, and decimal scale (
10.5versus10.50). - Collation and case (
ÄversusAplus a combining mark), and trailing spaces. NULLversus empty string, and default values filled differently.- JSON key order, and whitespace.
Write the normalisation rules down. They double as a list of semantic differences between the two databases that the application may also trip on.
Shadow reads in practice. For a sample of live requests, read from both stores and compare. Return the old store's result, so users are never exposed to the new path.
- Do the shadow read asynchronously (fire and forget, or after responding), so it never adds to user latency.
- Sample a fraction of traffic (1 to 10%) to limit load on the new store, and raise the fraction as confidence grows.
- Log mismatches with enough context (key, both values, request type) to debug, and track the mismatch rate as a metric.
- Exclude reads of keys written in the last few seconds, because CDC lag makes them differ legitimately, or compare them only after the lag has passed.
How many clean samples are enough? If you compare n random reads and find zero mismatches, a quick rule (the "rule of three") says that you can be about 95% confident the true mismatch rate is below 3/n. To claim a rate below 0.01% (1 in 10,000), you need about 30,000 consecutive clean comparisons. To claim 1 in a million, about 3 million. This tells you how long to run shadow reads before cutting over: at 100 sampled reads per second, 3 million samples take about 8 hours.
Verify behaviour, not only data. A new store with identical rows can still answer queries differently because of different default sort orders, string comparison rules, pagination semantics, or isolation level. Shadow reads at the API level (compare the full response, not the rows) catch these. GitHub's Scientist library popularised this "run both, compare, return the old result" approach for code paths.
Cutover and rollback#
Cut over in stages, with a way back at each:
- Reads first: gradually move read traffic to the new store (1%, 10%, 50%, 100%) using a feature flag, watching errors and latency.
- Writes: switch the source of truth. Common approaches: a brief write freeze (seconds) while CDC drains to zero lag, then flip routing; or per-partition cutover (one tenant or shard at a time).
- Reverse replication for rollback: after cutover, stream changes from the new store back to the old one, so you can switch back without losing writes made after cutover.
- Keep the old store for days or weeks, then decommission it after a quiet period.
cutover(partition p):
set_mode(p, READ_ONLY) # writes briefly rejected or queued
wait_until(cdc_lag(p) == 0) # target fully caught up
verify_checksums(p)
routing.set(p, NEW) # versioned routing table
start_reverse_replication(p, NEW -> OLD)
set_mode(p, READ_WRITE) # typical total: seconds
# rollback: set_mode RO, routing.set(p, OLD), resume forward CDCCutover and rollback, in depth#
A migration as a state machine. Every migration of a dataset, partition or tenant moves through the same states. Making them explicit, and stored in a control table, lets automation and humans see exactly where each piece is:
Choosing the unit of cutover.
| Strategy | How it works | Good for | Risk |
|---|---|---|---|
| Big bang | Everything switches at once | Small datasets, simple systems | One failure affects everyone |
| Per tenant or partition | Move one customer or logical shard at a time | Multi-tenant SaaS, sharded data | More bookkeeping |
| Percentage of traffic | Route x% of requests to the new store | Read paths, stateless lookups | Writes for one key must not split across stores |
| Read first, then write | All reads move, then writes move | Most migrations | Read path proven before writes are at stake |
For writes, the unit must be a set of keys that never need atomic changes across units. Otherwise a transaction would span both stores.
The write freeze, quantified. Switching the source of truth for a partition needs a moment when no writes are in flight. Make the partition read-only, wait for CDC lag to reach zero (usually under a second if lag was already small), verify a final checksum for small partitions, flip the routing entry, and re-enable writes. Clients retry rejected writes with backoff, so users see a pause of a few seconds, not errors. Keep each partition small enough that this freeze stays short. That is one more argument for many small logical shards.
Details that bite at cutover.
- Sequences and auto-increment IDs. The new database's sequences must start above the old maximum, with a safety gap. Otherwise new rows collide with migrated ones. Better still, use IDs generated outside the database.
- Caches. Caches keyed by the old store's data may hold values that the new store has since changed. Flush or version the cache keys at cutover.
- Connection routing. Applications with hard-coded connection strings, or DNS cached for too long, keep writing to the old store. Route through a proxy or a routing table the application reads dynamically, and set the old store to read-only so stray writes fail loudly instead of silently diverging.
- Background jobs and batch processes. Cron jobs, ETL and reporting queries often have their own connection settings, and are forgotten until they write to the wrong place.
- Triggers, stored procedures and constraints. Logic that lived in the old database must exist in the new one, or move into the application, before cutover.
Rollback with reverse replication. Once writes go to the new store, start CDC from the new store back to the old one. If the new store misbehaves, freeze writes again, let the reverse stream drain, flip routing back and resume. No post-cutover writes are lost. Two cautions: make sure the forward stream is stopped, or each change will echo back and forth; and keep the old store's schema compatible with what the reverse stream sends. Decide in advance the point of no return, after which rollback is no longer supported, such as when the old store is decommissioned or a new feature starts using data only the new store can hold.
Decommissioning. After a quiet period (days to weeks, set by how long latent bugs take to appear, such as month-end jobs), stop the reverse stream, take a final backup of the old store, keep it for a defined retention period, then delete it. Remove old code paths, flags and connection settings, so nobody accidentally depends on the old store again.
Schema evolution with Avro and Protobuf#
Data also lives in messages, events and files that outlive the code that wrote them. Producers and consumers upgrade at different times, so schemas must evolve compatibly:
- Backward compatible: new readers can read data written with the old schema (add fields with defaults; consumers upgraded first).
- Forward compatible: old readers can read data written with the new schema (they ignore unknown fields; producers upgraded first).
- Full compatibility: both.
Protobuf rules: never reuse or change a field number; add new fields freely (old readers skip them); mark removed fields as reserved; avoid changing types. Avro rules: readers resolve differences between writer and reader schemas by name; new fields need defaults; a schema registry (Confluent, Apicurio, AWS Glue) stores versions and rejects incompatible changes at publish time.
// Protobuf: evolving an event safely
message OrderPlaced {
string order_id = 1;
int64 amount_cents = 2;
reserved 3; // was 'currency_code' (string); never reuse 3
string currency = 4; // new field; old readers ignore it
}See API Design for versioning of public APIs.
Schema evolution, in depth#
How Avro resolves schemas. Avro data is written without field names or tags. Values are encoded in schema order. A reader therefore needs the writer's schema to decode the bytes, and then resolves it against its own reader's schema: fields are matched by name (or alias), fields the reader does not know are skipped, and fields the reader expects but the writer did not write take the reader's default. If a missing field has no default, decoding fails, which is why "new fields need defaults" is the central Avro rule. In Kafka, each message carries a small schema ID, and consumers fetch the writer's schema from the schema registry by that ID.
Registry compatibility modes. Confluent Schema Registry checks every new schema version against older ones before accepting it:
| Mode | New schema must be able to... | Upgrade order |
|---|---|---|
BACKWARD (the default) | Read data written with the previous version | Consumers first |
BACKWARD_TRANSITIVE | Read data written with all previous versions | Consumers first |
FORWARD | Be readable by consumers using the previous version | Producers first |
FULL | Both of the above with the previous version | Either order |
NONE | Nothing is checked | Coordinated by hand |
Use a transitive mode for topics with long retention or for replaying history. Consumers reading data from a year ago need compatibility with schemas from a year ago, not just the last version.
How Protobuf stays compatible. Protobuf encodes each field with its field number and a wire type, so readers skip numbers they do not recognise. That gives forward compatibility. Readers use defaults for missing numbers, which gives backward compatibility. The rules follow from the encoding:
- Never change or reuse a field number. Mark removed numbers and names
reserved. - Some type changes are wire-compatible (
int32,int64,uint32,uint64andboolshare a varint encoding), but values may be truncated. Treat type changes as a new field. - In proto3, scalar fields without
optionalcannot distinguish "unset" from the zero value. Useoptionalor wrapper types when absence matters. - For enums, make the zero value
UNSPECIFIED, and have readers handle unknown values, because a new producer may send a value an old consumer has never seen.
JSON is harder. JSON payloads carry field names but no enforced types, and consumers often fail on unexpected fields or nulls. If you use JSON for events, publish a JSON Schema in a registry, make consumers tolerant (ignore unknown fields, treat missing fields as absent), and still follow add-only evolution.
Event stores and upcasting. In an event-sourced system, old events live forever and must still be readable. Rather than rewriting history, upcasters convert an old event version into the current one as it is read: OrderPlaced v1 becomes v2 by adding a default currency, for example. Sometimes a one-off "copy and transform" migration into a new event stream is cleaner. See Event Sourcing and CQRS.
Data lake tables. Columnar files (Parquet, ORC) embed their schema. Table formats track it at the table level. Apache Iceberg assigns every column a permanent ID, so renames and reorders are metadata-only and safe, and old files are read correctly by ID rather than by name or position. Adding columns is cheap. Changing a column's type is limited to safe widenings, such as int to long or float to double.
Contracts between teams. When another team consumes your events, a schema change is an API change. Add compatibility checks in CI (the registry's compatibility API, or buf breaking for Protobuf) so incompatible changes fail before merge, and announce deprecations with a removal date, as you would for a public API.
Resharding migration example#
A chat service has messages in 8 Postgres shards by hash(conversation_id) % 8 and needs 32 shards. Plan:
- Introduce logical shards: map 1,024 logical shards onto physical nodes, so future moves never rehash. Old shard i holds logical shards where
ls % 8 == i. - Provision 24 new clusters.
- For each logical shard to move: snapshot its rows from the old shard into the new cluster, then apply CDC changes filtered to that logical shard.
- Verify counts and checksums per logical shard; shadow-read a sample of conversations.
- Cut over each logical shard with the brief read-only switch above; update the versioned shard map in etcd; routers refresh.
- Reverse-replicate for a week for rollback; then delete moved rows from old shards.
Moving one logical shard at a time keeps each step small (a few GB), limits the blast radius and lets you pause at any point. Vitess automates this exact workflow (VReplication with Reshard and SwitchTraffic).
Resharding, in depth#
The numbers for the 8-to-32 example. Say the 8 shards hold 4 TB in total, 500 GB each, and we move 768 of the 1,024 logical shards (three quarters) to the 24 new clusters, about 3 TB.
- Each logical shard is about 4 GB. Copying at a throttled 50 MB/s takes about 80 seconds per logical shard, plus catch-up.
- Running 8 moves in parallel (one per source shard, to spread the load), 768 moves take 96 rounds of perhaps 3 to 5 minutes each, including verification and cutover. That is 5 to 8 hours of pure work, which in practice spans a week or more of supervised batches during low-traffic hours.
- Each cutover freezes writes for one logical shard (about 0.1% of conversations) for a few seconds, so almost no user ever notices.
The per-shard workflow.
Vitess as a reference implementation. Vitess exposes this as a workflow: Reshard (or MoveTables for moving tables between keyspaces) creates VReplication streams from source to target shards. VDiff compares them. SwitchTraffic moves reads and then writes, with a brief write pause. ReverseTraffic switches back, using the reverse streams that SwitchTraffic creates. Complete removes the source data and the streams. Each verb maps to a state in the diagram above. Even if you are not using Vitess, it is a good checklist for a home-grown tool.
Routing during the move. Routers must agree on which cluster owns each logical shard. Keep the shard map in a strongly consistent store (etcd, ZooKeeper, or a small database), version it, and have routers watch for changes. During the freeze window, the router for the moving shard either queues writes briefly or rejects them with a retryable error. A router with a stale map that writes to the old shard after cutover is the dangerous case. Making the old shard reject writes for moved logical shards turns that into a visible error instead of silent divergence.
Cleaning up. Deleting the moved rows from old shards is a large delete job. Run it in batches, like a backfill. With table-per-logical-shard layouts, it is just DROP TABLE, which is instant. This is one reason Notion and others place each logical shard in its own schema or table set. See Partitioning and Sharding.
Moving between database products. Migrating MySQL to PostgreSQL, or a relational store to DynamoDB, adds translation work on top of the same copy, stream, verify and cut over steps:
- Map types carefully: MySQL
TINYINT(1)used as boolean, unsigned integers, andDATETIMEwithout a time zone, versus PostgreSQL'sboolean, signed integers andtimestamptz. - Behaviour differences: default collations and case sensitivity,
NULLsorting order, and transaction isolation defaults (MySQL InnoDB defaults to repeatable read, PostgreSQL to read committed). - For a relational to key-value move, redesign around access patterns first. The migration is mostly a data modelling project. See Data Modeling.
AWS DMS, Debezium plus a sink connector, and vendor tools handle the copying. The verification and the behavioural testing remain your job.
Splitting a monolith's database#
A common large migration is moving from one shared database, where every module reads every table, to one database per service. The data movement uses the techniques above. The hard part is untangling ownership and coupling.
Step 1: find out who touches what. Use query logs, pg_stat_statements or the performance schema to map which code paths read and write each table. Tables usually fall into three groups. Some are clearly owned by one domain (orders, payments). Some are shared reference data (countries, currencies). A few are genuinely entangled, like a users table with 80 columns that every module writes to.
Step 2: give each table one owner, logically, before moving it physically. Route all writes to a table through the owning module's code (its API, even if still in-process), and forbid other modules from writing to it directly. This is the first, and often the longest, step. Database permissions help enforce it: give each module its own database role, and grant write access only to the owner.
Step 3: replace cross-domain joins. A query like SELECT ... FROM orders JOIN users ... cannot survive the split. The options are:
- Call the owner's API and join in the application. This is simple, but adds latency and a runtime dependency.
- Keep a local read model. The orders service keeps a small copy of the user fields it needs (name, email), updated from the user service's events or CDC. This is fast and resilient, but eventually consistent.
- Move the query to a reporting store that receives data from all services through CDC, which is often right for analytics and admin screens.
Step 4: replace cross-domain transactions and foreign keys. A transaction that wrote to orders and inventory together now spans two services. Rework it as a saga with an outbox, or redraw the boundary so both tables belong to one service. Foreign keys across services become references validated by the application, with periodic reconciliation for orphans. See Distributed Transactions.
Step 5: move the tables. Only now, physically move each owned table group to the service's own database with snapshot plus CDC, verify, and cut over. Because steps 2 to 4 removed every other caller, the cutover affects one service's connection settings.
The strangler fig shape. This is incremental by design. Extract one domain at a time, starting with the least entangled one, and leave the monolith database shrinking around the new services rather than attempting a single rewrite. Teams that try to split everything at once tend to end up with a distributed monolith: services that still cannot be deployed or scaled independently because they share hidden data dependencies.
Major version upgrades and engine moves#
Upgrading a database's major version (PostgreSQL 13 to 16, MySQL 5.7 to 8.0) is a data migration too, even though the data does not change shape.
In-place upgrade. PostgreSQL's pg_upgrade with --link rewrites the system catalogs and reuses the data files through hard links, so even large databases upgrade in minutes. But the database is offline during the upgrade, statistics must be rebuilt (ANALYZE) before performance returns to normal, and rollback means restoring a backup. It suits databases that can take a short maintenance window.
Blue-green through replication. For near-zero downtime, build a new cluster on the new version and keep it in sync with logical replication (PostgreSQL) or a replica on the new version (MySQL replicates from older to newer versions within supported ranges). Then cut over with the usual brief write freeze. Managed services package this: Amazon RDS Blue/Green Deployments create a synchronised "green" copy and switch over in about a minute. The cautions are the same as any migration. Logical replication in PostgreSQL does not replicate DDL or sequence values, so freeze schema changes during the migration and set sequences at cutover. And tables without a primary key need a replica identity before they can replicate updates.
Test the queries, not just the data. Major versions change the planner, defaults and behaviour. MySQL 8.0 changed the default character set to utf8mb4 and the default authentication plugin, and removed the query cache. Planner changes can make a few important queries much slower or much faster. Capture a sample of production queries, replay them against the new version with production-sized data, and compare latency and plans before switching. Shadow reads at the query level, as described above, are the most reliable way to do this under real load.
Engine moves inside one product. Moving MySQL tables from MyISAM to InnoDB, or changing a PostgreSQL table's partitioning, follows the same playbook: build the new form beside the old, keep it in sync, verify, and swap with a brief lock. Online schema change tools do this for a single table. Logical replication does it for whole databases.
Planning and rehearsing a migration#
Write the plan as a runbook. A good migration document lists, for every step:
- What changes, and the exact command or flag flip.
- How you will know it worked: the dashboards, queries and expected values.
- How long it should take, measured in rehearsal.
- How to undo it, and up to what point undo is possible.
- Who executes it, who approves it, and who must be told.
Reviewers should be able to see at a glance which steps are reversible and which are the point of no return.
Rehearse on production-shaped data. Restore a recent production backup into an isolated environment and run the whole migration end to end, including the cutover and the rollback. Rehearsals uncover the things design reviews miss: an ALTER that takes 40 minutes instead of 4, a table without a primary key that CDC cannot replicate, a column with invalid UTF-8 that the new database rejects, a backfill that lags replicas by an hour at full speed. Record the durations. They become the schedule and the alert thresholds for the real run.
Define go and no-go criteria in advance. For example: "Proceed to write cutover only if CDC lag has stayed under 1 second for 24 hours, the shadow-read mismatch rate has been 0 over at least 30,000 samples, and p99 read latency on the new store is within 10% of the old." Writing criteria down before starting stops the natural pressure to push on when a migration is nearly done.
Observe everything during the run. Watch the source's load, replica lag, CDC lag, error rates by endpoint, latency percentiles on both stores, and the migration's own progress (chunks copied, chunks verified, partitions cut over). Put them on one dashboard. Have the abort command ready, and make sure everyone on the call knows who can say "stop".
Build dry-run modes into migration tools. Every copier, verifier and cutover script should support a mode that reports what it would do (which chunks, how many rows, which routing entries) without changing anything. Running the dry run immediately before the real step catches wrong targets, stale configuration and typos in partition lists, which are the cheapest bugs to fix and among the most expensive to discover live.
Communicate. Tell dependent teams, support and, if needed, customers about the timeline and any expected brief pauses. Large migrations often involve freezing other schema changes on the affected tables, so other teams' plans depend on yours.
Budget for the long tail. The first 90% of a migration often takes a fraction of the time. The remaining 10% (odd tables, forgotten jobs, a customer with unusual data, the last reader of the old column) takes the rest. Keep an inventory of what remains, with owners, and track it to zero before declaring the old system gone.
When to Use It#
- Any schema change on a production database that is serving traffic.
- Moving between databases (MySQL to Postgres, self-hosted to managed, SQL to a key-value store).
- Resharding, splitting a monolith's database into service databases, or moving to new regions.
- Evolving event and message formats consumed by other teams.
When NOT to Use It#
- Small tables and internal tools where a few seconds of maintenance is acceptable; a simple migration is fine.
- Do not build custom dual-write migrations when your database or a tool (Vitess, DMS, Debezium) supports the move.
- Do not migrate stores just to follow fashion; the risk is real.
How to Implement It#
- Plan steps as expand and contract; each one deployable and reversible.
- Use online tools for large tables; set lock timeouts; run during low traffic.
- Prefer snapshot plus CDC over dual writes; monitor lag.
- Verify with counts, checksums and shadow reads until mismatches reach zero.
- Cut over gradually behind feature flags, partition by partition, with reverse replication.
- Rehearse on a production-sized copy; write the rollback plan before starting.
- Contract only after the old path has been idle for a safe period.
| Technology | Fits when |
|---|---|
| gh-ost, pt-online-schema-change | Online ALTERs on large MySQL tables |
pgroll, pg-osc, CREATE INDEX CONCURRENTLY | Online changes in PostgreSQL |
| Debezium, AWS DMS | Snapshot plus CDC between databases |
| Vitess VReplication | Resharding and moving tables in MySQL |
| Confluent Schema Registry | Enforcing Avro/Protobuf/JSON Schema compatibility |
Trade-offs#
| Choice | Gain | Cost | Pick when |
|---|---|---|---|
| Big-bang with downtime | Simple | Outage; risky rollback | Small data, maintenance window OK |
| Expand and contract | Zero downtime, reversible steps | Several deploys, temporary duplicate data | Every production schema change |
| Dual writes | No extra infrastructure | Silent divergence, needs reconciliation | Source has no CDC |
| Snapshot + CDC | Exact convergence, no app changes | CDC tooling and monitoring | Moving data between stores |
| Gradual cutover with reverse replication | Safe rollback | More moving parts | Critical data |
| gh-ost (binlog-based) | No trigger overhead on writes | No foreign keys, needs row-based binlog | Large, busy MySQL tables |
| pt-online-schema-change (triggers) | Handles foreign keys | Trigger cost on every write | MySQL tables with foreign keys |
| Per-tenant or per-logical-shard cutover | Small blast radius, short freezes | Bookkeeping and routing state | Sharded or multi-tenant data |
| Upcasting old events | No rewrite of history | Upcaster code kept forever | Event-sourced stores |
Common Pitfalls#
- Renaming or dropping a column in one step while old code is still running.
- A single huge
UPDATEbackfill that locks the table and lags replicas. - Dual writes without reconciliation, discovering drift months later.
- Cutting over without a tested rollback that preserves post-cutover writes.
- Reusing Protobuf field numbers or adding Avro fields without defaults.
- Running an
ALTER TABLEwithoutlock_timeout, so it queues behind a slow query and blocks every query behind it. - Using
OFFSETpagination in backfills, which gets slower with every batch. - Forgetting to advance sequences in the new database, so new IDs collide with migrated ones.
- Leaving the old store writable after cutover, so stray jobs write to it silently.
- Comparing stores without normalising timestamps, decimals and collations, and drowning in false mismatches.
Real-World Examples#
GitHub built and open-sourced gh-ost to run online schema migrations on its large MySQL tables, using the binlog instead of triggers to reduce load on the primary.
Stripe has described migrating large amounts of data online with a pattern of dual writing, changing reads, changing writes and removing old data, verifying each step.
Google's F1 team published its online, asynchronous schema change protocol (VLDB 2013), which lets F1 change schemas across thousands of servers without downtime. Netflix described DBLog, its watermark-based CDC framework that interleaves table snapshots with live log events, and Debezium's incremental snapshots follow the same idea.
Canva moved more than 25 billion media records from MySQL to DynamoDB live by sending only "media X changed" messages through SQS and letting a worker copy the current row, with newest-first backfill and a flag to send reads back; Tumblr moved MySQL leaders between data centers with only seconds of read-only time using local ProxySQL and automation. Both are studied in More Company Architectures.
In the Interview#
Handling migrations in an interview#
Recognise the prompt. Questions such as "you need to add a field", "the table has grown to 10 TB", "you're moving from MySQL to Cassandra" or "how would you reshard?" are migration questions. The interviewer wants to hear that you can change a live system without downtime or data loss.
A crisp structure. Answer in four beats:
- Compatibility: "Every step must work with old and new code running together, so I'll use expand and contract."
- Data movement: "Snapshot plus CDC into the new store, not dual writes from the app, because the log is ordered and resumable."
- Verification: "Chunked checksums, then sampled asynchronous shadow reads until the mismatch rate is zero over tens of thousands of samples."
- Cutover and rollback: "Per tenant or per logical shard, a few seconds of write freeze, routing flip, and reverse replication so I can roll back without losing writes."
Add one number. For example: "500 million rows at 5,000 per batch with throttling is about 3 hours of backfill." Or: "Each logical shard is about 4 GB, so a move takes a couple of minutes." A number shows you have thought about duration and load.
Follow-ups to expect.
- "What if the backfill overwrites a newer live write?" Use version checks on apply, or copy each chunk before applying its stream, as in the deep dive.
- "How do you change an event format other teams consume?" Register the new schema under a backward-compatible mode, add only optional fields, upgrade consumers first, and never reuse Protobuf field numbers.
- "How long do you keep the old store?" Through at least one full business cycle, such as a month-end, with reverse replication running. Then back it up and decommission.
Deep Dive: Consistent snapshots, idempotent backfills and long-running migrationsShow
Consistent snapshot with a position. CDC must start exactly where the snapshot ends. Debezium and similar tools record the log position (GTID or LSN) at the moment of a consistent snapshot, or use watermark-based incremental snapshots (from Netflix's DBLog design) that interleave chunk copies with live changes without a global lock.
Idempotent, resumable backfills. Backfills crash. Make them resumable from a checkpoint (last_id), idempotent (upserts, WHERE display_name IS NULL) and throttled by replica lag and p99 latency. Run them as tracked jobs, not ad hoc scripts.
Conflicts between backfill and live writes. If the backfill copies an old value after CDC applied a newer one, the target regresses. Fix: apply changes with version checks (only overwrite if newer), or apply CDC after the snapshot of each chunk.
Migrations that take months. Large migrations (moving a core table between systems) often run for months. Track progress per partition, keep dashboards of mismatch rates, and treat the old system as read-only reference until decommissioning.
Deep Dive: Online schema change in a distributed database (the F1 protocol)Show
The problem. In a distributed database with many servers, a schema change cannot reach every server at the same instant. If server 1 already knows about a new index and server 2 does not, server 2 may insert a row without its index entry. A later read through the index on server 1 will miss the row. The index is now corrupt, even though both servers behaved correctly for their own schema.
The insight. In Online, Asynchronous Schema Change in F1 (Rae, Rollins, Shute, Sodhi and Vingralek, VLDB 2013), Google showed that you can avoid this if (1) at most two adjacent schema versions are in use at any time, and (2) every pair of adjacent versions is mutually compatible. F1 enforces (1) with leases: a server must reload the schema within a lease period, or stop serving. A new version is published only after every server must have picked up the previous one. Then (2) is achieved by passing through intermediate states.
The states for adding an index.
- Absent: nobody knows about the index.
- Delete-only: servers delete index entries when rows are deleted, but never add them, and never read the index. A server in this state and one in "absent" cannot corrupt anything: there are no entries to orphan.
- Write-only: servers maintain index entries on every insert, update and delete, but queries do not read the index yet. Alongside a delete-only server, any entry that this server writes is cleaned up correctly by both when the row is deleted.
- Backfill: with every server now in write-only, a background job adds index entries for pre-existing rows. New writes are already covered.
- Public: queries may read the index. All entries exist, and every server maintains them.
Skipping "delete-only" breaks the protocol: a write-only server could add an entry that an absent-state server, which knows nothing of the index, leaves behind when it deletes the row, creating a dangling entry.
The same idea elsewhere. CockroachDB adopted this approach for its online schema changes, stepping descriptors through delete-only and write-only states with a lease on each version. Expand and contract at the application level is the same theorem with code deploys as the "servers": at most two adjacent code versions run at once (N and N-1), and each schema step is compatible with both. Dropping a column is the reverse sequence: stop reading (public to write-only), stop writing (write-only to delete-only), then remove (absent).
Why this matters beyond F1. It gives a precise test for any migration plan: list the versions of code and schema that can coexist at each step, and check that every pair is compatible. If any step requires two non-adjacent versions to work together, such as code that reads a column that older code never writes, the plan has a hole.
Key Takeaways#
- Split breaking schema changes into expand, migrate, contract steps that each work with old and new code.
- Use online schema change tools and batched backfills for large tables; set lock timeouts.
- Keep a new store in sync with snapshot plus CDC rather than application dual writes.
- Verify with counts, checksums and shadow reads; cut over gradually with reverse replication for rollback.
- Evolve Avro and Protobuf schemas under compatibility rules, and reshard by moving logical shards one at a time.
- At every step, the schema must work with every code version that might be running.
- Set
lock_timeouton migrations, backfill in throttled primary-key batches, and useCONCURRENTLYandNOT VALIDin PostgreSQL. - Use the database log (CDC) to keep a new store in sync. CDC copies state, while outbox events carry intent.
- Prove correctness with normalised chunk checksums and enough clean shadow reads (about 3/n confidence), then cut over in small units.
- Evolve message schemas under registry-enforced compatibility. Never reuse Protobuf field numbers, and always give new Avro fields defaults.