Home›Operate›Run it well 12: migrations
Course · ArchitectureLesson 27 of 330 read
Run it well · Chapter 8

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.

Start with a story

Cutover night

You are moving the shop database from an old PostgreSQL 12 server to a new PostgreSQL 16 cluster. It is 1.2 TB. The business will give you 10 minutes of downtime, not the 3 hours a dump and restore would take (derived from a rough restore rate, not measured).

So you do not copy the database during the window. You copy it weeks before, keep the copy in sync with logical replication, and use the window only to switch. Here is the night, step by step.

Connected

Real failures behind this design

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

The plan

Copy early, stay in sync, switch fast

Weeks before. Create the schema on the new cluster from a schema-only dump. Then publish on the old server and subscribe on the new one. The subscription copies every table, then streams changes as they happen.

-- old server (wal_level = logical)
CREATE PUBLICATION mig FOR ALL TABLES;

-- new server, after: pg_dump --schema-only shop | psql -h new shop
CREATE SUBSCRIPTION mig
  CONNECTION 'host=old.db dbname=shop user=replicator password=...'
  PUBLICATION mig;

The gotchas, before the night, not during it. Logical replication does not copy schema changes, so freeze DDL until the switch. It does not copy sequence values, so you set them by hand at cutover. A table with no primary key cannot replicate updates or deletes unless you set REPLICA IDENTITY FULL, which makes every change on it look up the row by every column. Find those tables early.

-- tables with no primary key: fix these before you rely on logical replication SELECT c.oid::regclass AS table_name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog', 'information_schema') AND NOT EXISTS (SELECT 1 FROM pg_constraint p WHERE p.conrelid = c.oid AND p.contype = 'p');

The night. Put the app in maintenance mode so writes stop. Wait until the subscription has applied everything (compare pg_current_wal_lsn() on the old server with latest_end_lsn in pg_stat_subscription on the new one). Copy the sequence values across. Compare row counts on the big tables. Point the app at the new cluster, run the smoke tests, and open writes.

-- on the old server: generate the setval calls for every sequence
SELECT format('SELECT setval(%L, %s, true);', schemaname || '.' || sequencename, last_value)
FROM pg_sequences WHERE last_value IS NOT NULL;
-- run the output on the new server

The way back. Before you open writes on the new cluster, decide how you would return. The common answer is a reverse subscription, from new to old, created at the switch. Then if something is wrong at 2 AM, the old server already has every order placed since.

Does this work for MySQL to Aurora, or between engines?

The shape is the same: full copy, then change data capture, then a short switch. For MySQL into Aurora or RDS, a replica of your server that you promote is the simplest version. Between engines, AWS DMS or Debezium does the full load and the change stream. The rest of this chapter covers those moves and the ways they fail.

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.

Next · chapter 13UpgradesMajor versions, planned and reversible← Chapter 11: Security
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.

One database decision a weekA short email each week: one real decision, the trade-off, and the command to check it. Unsubscribe in one click.

Part 4 of 4 · Operate · 21 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.