Home›Operate›Migration playbooks
Course · ArchitectureLesson 27 of 330 read
Designs · migrations

Migration playbooks

How do I change the design without an outage?

You will learn: step by step plans for four common changes, how to check each one worked, and the way back if it did not.

Most designs change after launch. These four changes come up in almost every growing system. Each plan ends with the way back, because a migration without one is a bet.

Migration

Add change data capture

Change data capture streams every committed change out of the database, so search indexes, caches and warehouses can follow it without polling or scanning the primary.

Change data capture, in four steps

Teal: the source of truth. Orange: the thing to watch.

1Turn on the change streamSource databasewal_level = logical, orbinlog_format = ROWA replication slot or a binlogposition2Snapshot, then streamExisting rows: one consistentsnapshotCDC tool (Debezium or managed)Then every new change, in commitorder3Consumers apply by keyA queue or Kafka topicSearchindexWarehouseCache4Watch the lagA stopped consumerThe slot keeps WAL, the diskfillsAlert on lag, cap withmax_slot_wal_keep_size
  1. Turn on the change streamPostgreSQL: wal_level = logical (needs a restart) and a replication slot per consumer. MySQL: binlog_format = ROW and binlog_row_image = FULL, with GTIDs on. MongoDB: change streams, which need a replica set.
  2. Take the initial snapshotThe tool (Debezium or a managed equivalent) copies the existing rows, then switches to the stream at a consistent point.
  3. Make the consumer idempotentThe same change can arrive twice after a restart. Apply changes by primary key so that applying one twice does no harm.
  4. Watch the slot or binlog positionA stopped consumer makes PostgreSQL keep WAL for its slot, and the disk fills. Alert on slot lag, and set max_slot_wal_keep_size as a safety limit. When the cap is hit the slot is invalidated and the consumer needs a new snapshot, so alert well before the cap.
  5. Plan for schema changesAdding a column is usually fine. Renaming or dropping one breaks consumers unless they are updated first.

How I check it worked

The way back. Drop the replication slot or stop reading the binlog. The source database is unchanged, so turning CDC off is safe, as long as the slot is dropped and does not keep holding WAL.

Migration

Split one database into two

One database often holds several domains (orders, users, catalog). Splitting one out gives it its own scaling, its own failure domain and its own team.

Splitting one database into two

The old tables stay read-only until you are sure.

1BeforeApplicationOne database: orders andusers2Stop cross-domainjoinsOrders codeUsers through an API, nota joinStill one database3CopyOld databaseLogical replication or CDCNew users database,following4Switch in a shortfreezeStop writes to userstablesWait for the copy to catchupPoint the application atthe new database5AfterOrdersdatabaseUsersdatabaseOld users tables: read-only, for the way back
  1. Stop the cross-domain joins firstIn code, before any data moves. The new service reads the other domain through an API or a copy, not through a join.
  2. Copy the tables with logical replication or CDCThe new database follows the old one while the application still writes to the old one.
  3. Avoid writing to both from the applicationTwo commits in two databases can disagree after a failure. If both must be updated for a while, use an outbox and one direction of copying.
  4. Switch writes in a short freezeStop writes to the moved tables, wait for the copy to catch up, point the application at the new database, resume.
  5. Keep the old tables read-only for a whileThey are the fallback, and they answer questions about what moved.

How I check it worked

The way back. Until the old tables are dropped, switch writes back and copy the new rows in the other direction. Decide in advance how long this window stays open.

Migration

Move from MySQL to PostgreSQL

The engines speak similar SQL, so most of the work is in the details that differ.

MySQL to PostgreSQL

Rehearse steps 2 to 4 on a copy, and time them.

1Convert the schemaMySQL schemaMap types by hand: booleans,timestamps, unsigned, collationsPostgreSQL schema, reviewed2Clean and loadFix zero dates and invalid UTF-8pgloader, one-time loadPostgreSQL with the data3Keep in syncMySQL still takes the writesCDC or AWS DMSPostgreSQL follows4Cut overFreeze, final sync, switchApplication on PostgreSQLReverse sync to MySQL, the wayback
  1. Convert the schema by hand, then review itTINYINT(1) to boolean, DATETIME to timestamptz (first decide, and write down, which zone the stored values were in; if they were UTC, convert as UTC, otherwise shift them), AUTO_INCREMENT to identity, UNSIGNED columns to the next larger type. Case-insensitive comparisons from MySQL collations need citext or indexes on lower(column).
  2. Clean the data that PostgreSQL rejectsZero dates such as 0000-00-00, invalid UTF-8, and values that only fit because of an old SQL mode.
  3. Load and keep in syncpgloader for a one-time load, or a CDC tool or AWS DMS to keep PostgreSQL following MySQL until cutover.
  4. Change the application SQLBacktick quoting, LIMIT x, y, ON DUPLICATE KEY UPDATE (becomes ON CONFLICT), and GROUP BY queries that MySQL accepted without listing every column.
  5. Rehearse the cutoverTime a full run on a copy, including the final sync and the switch.

How I check it worked

The way back. Keep MySQL receiving the changes from PostgreSQL for a while after cutover, if your tooling supports reverse sync. If not, the way back is a restore, so rehearse it.

Migration

Add a cache in front of the database

A cache helps when the same data is read far more often than it changes. Added carelessly, it serves stale data and can take the database down when it empties.

Adding a cache, safely

Four situations the design has to handle before launch.

1Read: cache-asideApplicationCache: missDatabaseStore the result with a TTL2Write: invalidate aftercommitApplicationDatabase COMMITThen delete the cache key3A hot key expiresMany requests miss at onceOne request refills itOthers wait, or get the stalevalue4Cold cache after a restartCache emptyEvery read goes to the databaseSize the database for it, or warmthe cache first
  1. Cache-asideRead from the cache. On a miss, read the database and store the result with a TTL.
  2. Invalidate after commitOn a write, delete the cache key after the transaction commits, not before, or a reader can refill it with the old value.
  3. Add jitter to TTLsKeys created together expire together. A random few percent on each TTL spreads the refills.
  4. Protect against stampedesWhen a hot key expires, let one request refill it while others wait or get the stale value.
  5. Plan for a cold cacheAfter a restart, every read goes to the database. Size the database to survive that, or warm the cache before taking traffic.

How I check it worked

The way back. Turn the cache off with a flag. If the database cannot take the load without it, the cache has become part of capacity, and the design should say so.

Connected

Real failures behind this design

These incidents are why the choices below matter. Each one is written up with its numbers and sources.

Your turn

You are moving a 2 TB MySQL database to a new cluster with under a minute of write downtime. Outline the steps.

Write your answer down first. Then open mine.

Show my answer

Copy: a physical copy, such as XtraBackup or a cloned replica, restored on the new cluster. Note its GTID position.

Catch up: make the new cluster a replica of the old one from that position. Let it catch up, then compare the data with checksums (pt-table-checksum or similar). Send some read traffic to it and compare answers.

Cut over: set the old primary super_read_only, wait until the new one has applied every GTID, then switch the application through the proxy or DNS you lowered the TTL on beforehand. Writes are paused only for those seconds. If any superuser application connection exists, revoke its write grants first, since read_only does not stop a superuser.

Keep a way back: replicate from the new cluster to the old one for a while, so rolling back is another switch, not a restore.

Part 4 of 4 · Operate · 15 pagesAll pages

How do I run it in production? What to check when it is slow or broken, where it runs and what it costs, how big it must be, pooling, backups, security, upgrades and other changes made safely.