TB-sized live MySQL to Aurora Serverless v2, with a ~1-minute write lock

A field report from a real production migration: the runbook, the configs, the failure modes, and the decisions we'd make again — including the one that almost cost us silent data loss.

TL;DR

We migrated a production self-managed MySQL on EC2 (~1TB, active OLTP, FK-heavy schema) to Aurora MySQL Serverless v2 in a different VPC, with a hard 15-minute cutover budget.

The only production-side write lock was a ~1-minute FLUSH TABLES WITH READ LOCK — held for the full duration of the aws ec2 create-snapshot API call, not just the network round-trip. (More on why this matters and why our first attempt nearly broke silently, below.) The full dump and load ran on a disposable EBS-snapshot worker, completely off the production path. DMS picked up CDC from the exact native binlog coordinate the snapshot was taken at, and we cut over once apply lag was zero.

This post is the runbook with the commands, configs, transformation rules, and the failure modes that actually came up in the run.

---

Part 1: Why we keep ending up on this stack

The pattern this migration targets — persistent ECS services in front of Aurora Serverless v2 — is what we default to for new workloads at DataOrc. It's running across 10+ AWS accounts and 32+ services as of this writing. Before the migration runbook, it's worth saying why this combination is the one we keep choosing, because the migration runbook only makes sense if the destination does.

"Serverless" here is the database, not the application runtime. The applications are long-running container services on ECS, scaled horizontally, with warm process state where that helps. Lambda is fine for event-driven glue but not what we run our request-serving services on. The combination is:

- ECS for persistent application services. Predictable deployment, rollback, observability, and per-container scaling. Easier to reason about under sustained load than a function-execution model. - Aurora MySQL/PostgreSQL Serverless v2 for the database layer. Elastic ACU range that tracks the workload instead of sitting at the peak shape 24/7. - Disciplined connection management. Bounded application pools, optional RDS Proxy, benchmarked under spike conditions. - Parameter group tuning that doesn't trust defaults. This matters more on serverless, not less.

What spiky workloads do to provisioned databases

The workloads that pushed us toward this stack share a shape: long quiet periods, then sharp spikes — partner integration windows, batch jobs, campaign traffic, scheduled aggregations. Peak might be a few thousand writes per second for an hour; median might be a tenth of that.

On Aurora Provisioned, you size for the peak. You pay for db.r6g.4xlarge all day to survive the 7pm batch run, then you also pay for it overnight while nothing is happening. On Serverless v2, the ACU range lets the database track the actual workload:

| Window | minacu | maxacu | | --- | --- | --- | | quiet hours | 0.5 | 2 | | business hours | 0.5 | 8 | | peak batch / spike | 0.5 | 16 |

We benchmark every new workload before committing. Two cases where v2 is not the right answer:

- Flat predictable workloads. A service that holds steady at 4 ACU all day is cheaper on Provisioned + Reserved Instance than on v2. - Very high steady-state ACU. v2 pricing crosses over Provisioned somewhere in the mid-teens of sustained ACU.

Aurora Serverless v1 proved the direction but had real limitations for OLTP — pause/resume latency, capacity-change disruption, smaller feature surface. v2 is where the model became usable for production workloads with continuous writes.

Connection management is a first-class concern

The thing serverless does not remove is the need to think about connections. It arguably makes it more important: ACU can scale, but maxconnections doesn't track ACU at runtime, and an application autoscaler that launches 50 new tasks during a spike can produce a connection storm that the database refuses faster than capacity comes online.

For every workload, we benchmark and document:

- application task count × per-task pool size = peak concurrent connections - maxconnections on the parameter group with headroom for admin and replication sessions - p95/p99 latency under scale-out - behavior when a task scales in (do connections drain cleanly, or do they linger as idle?) - failover recovery time during a writer change

For high-churn-connection workloads, RDS Proxy is a useful intermediary. For workloads with disciplined application-side pooling, it's overhead. Pick per workload, not as a default.

Tuning what RDS won't tune for you

The other thing serverless does not remove is the need to tune the database for your workload. Parameter group defaults are conservative — they have to be, because RDS doesn't know your query mix. For PostgreSQL workloads doing heavy analytical reads alongside OLTP writes, the parameters we routinely benchmark and tune include maxconnections, sharedbuffers, workmem, maxparallelworkerspergather, autovacuum settings on write-heavy tables, checkpoint/WAL behavior, idle transaction timeouts, and statement timeouts.

A concrete example: for one analytical-read PostgreSQL workload after benchmarking, we settled on:

-- On the cluster parameter group
max_parallel_workers_per_gather = 12
max_parallel_workers             = 12
max_worker_processes             = 12

12 isn't a universal number. It's what the benchmarking on that workload landed on, given the instance ACU range, query mix, and concurrency. The point is that "we use serverless" is not a substitute for "we tuned the database." Both have to be true. The MySQL example you'll see later in this post — bumping sortbuffersize to 4MB on the Aurora parameter group before the post-load index rebuilds — is the same discipline applied to a different engine.

Resilience defaults that don't need rebuilding per app

Aurora's storage layer is distributed across AZs by default. Point-in-time recovery is on by construction through the backup retention window. The writer endpoint abstracts failover from the application. None of these eliminate the need for application-level retries or correct cutover discipline, but they remove a class of reliability work that individual application teams shouldn't be reinventing.

This is the part of the stack that gets called "boring" and that's a compliment. The first dozen times you set up a database for a new service, you do all this from scratch. After you've done it 30 times, you stop. The migration runbook below is what makes "stop" possible for legacy systems: a tested, repeatable path from a self-managed legacy MySQL into the same stack everything else runs on.

---

Part 2: Migrating a live EC2 MySQL to Aurora Serverless v2

The migration runbook that follows is the specific path we used for one workload moving onto the stack described above. The same pattern works for any self-managed MySQL on EC2 with similar constraints: ~1TB scale, FK-heavy schema, active OLTP, hard cutover budget.

The constraint that shaped every decision

Production was a single self-managed MySQL on EC2, ~1TB, with the application server sitting in the same older VPC. We needed to move it into a newer VPC-backed stack on Aurora Serverless v2, with ≤15 minutes of cutover downtime and zero data loss.

There are three obvious ways to do this, and we rejected two.

What we didn't do, and why

1. mysqldump from production. Single-threaded, locks held for the duration of consistent dumps, days long for 1TB, and the dump I/O lands on the database your users are hitting. Not an option. 2. DMS full-load + CDC sourced from production. This works and we've used it on smaller workloads. But DMS full-load reads rows from the source continuously throughout the dump phase — on a busy 1TB OLTP system that's hours of sustained read pressure on the primary, plus the well-known DMS full-load quirks (LOB handling, batch ordering, FK ordering during initial load). For this workload, "tax the primary while we're trying to move off it" was exactly what we wanted to avoid. 3. Native MySQL replica → promote. Workable in theory. In practice the source VPC had no clean replication path to the new account/VPC, and the initial replica seed still has to read every byte from the primary. We'd have traded one set of problems for another.

What we did, and why

EBS snapshot of source data volume          (writes blocked ~1 minute)
        ↓
Restore on disposable EC2 worker             (cloned MySQL, off the prod path)
        ↓
mydumper from the clone                      (16 threads, compressed, parallel)
        ↓
myloader into Aurora Serverless v2          (Aurora scales ACU for the load)
        ↓
DMS CDC from production binlog               (start position = snapshot position)
        ↓
Apply lag → zero → application cutover       (~10 min window in our run)

The pattern works because we separated the bytes from the deltas. The 1TB of historical data comes from a frozen point-in-time clone that production never sees. The ongoing changes come from production's binlog, starting at the exact same point-in-time. Stitching them together gives you an Aurora target that converges to the source without ever touching the source for the bulk work.

That separation is the entire reason the production hit was ~1 minute of blocked writes instead of hours.

---

ACU sizing for this migration

Part 1 covers why we default to Serverless v2 for spiky workloads. For this migration specifically, the source MySQL had exactly the spike profile that makes v2 a good fit — long quiet periods punctuated by partner-integration and batch windows. The sizing we landed on:

| Phase | minacu | maxacu | | --- | --- | --- | | steady-state | 0.5 | 8 | | during myloader | 0.5 | 16 (temporary, via modify-db-cluster) | | post-cutover | 0.5 | 8 (reverted) |

The temporary bump to max 16 during the myloader phase mattered: see Phase 4 for why the load is the most ACU-hungry moment in the whole migration and what happens if you don't give it room.

---

Phase 0 — Source preflight

You cannot start CDC against a binlog position that doesn't exist anymore. Almost every migration that fails halfway fails here.

-- On the source production MySQL, before touching anything else.
SHOW VARIABLES LIKE 'log_bin';                  -- must be ON
SHOW VARIABLES LIKE 'binlog_format';            -- must be ROW
SHOW VARIABLES LIKE 'binlog_row_image';         -- must be FULL
SHOW VARIABLES LIKE 'server_id';                -- must be set and stable
SHOW VARIABLES LIKE 'binlog_expire_logs_seconds';
SHOW VARIABLES LIKE 'gtid_mode';                -- ran with GTID OFF; DMS handles both

Then extend binlog retention. The default on a busy server can purge binlogs faster than you can dump, load, and start CDC. Set it to 14 days, persist across restart:

SHOW VARIABLES LIKE 'binlog_expire_logs_seconds';
SET PERSIST binlog_expire_logs_seconds = 1209600;   -- 14 days
FLUSH BINARY LOGS;
SHOW BINARY LOGS;

Create the DMS replication user on the source, scoped to what DMS actually needs:

CREATE USER 'dms_repl'@'%' IDENTIFIED BY '<secret>';
GRANT REPLICATION CLIENT, REPLICATION SLAVE ON *.* TO 'dms_repl'@'%';
GRANT SELECT ON `<database>`.* TO 'dms_repl'@'%';
FLUSH PRIVILEGES;

Sanity-check disk headroom on the source for binlog growth during the migration window. A migration that runs out of disk on the source is the kind of weekend nobody asked for.

The playbook doesn't care that it's talking through a tunnel. It does care that it can run preflight SHOW VARIABLES queries before anything destructive runs.

---

Phase 1 — The ~1-minute write lock (and why it isn't 10ms)

This is the only thing that touches production. Everything else runs off a clone. This is also the step where almost every blog post on the internet — including an earlier draft of this one — gets it dangerously wrong.

What the docs imply vs. what actually happens

The AWS docs say snapshots are "point-in-time" and "the snapshot is created immediately." The naïve reading is: call aws ec2 create-snapshot, get a snapshot ID back in ~10ms over HTTP, release your database lock, move on. We almost shipped exactly that.

Read the docs more carefully:

> To ensure consistent and complete snapshots, we recommend that you pause writes to the volume before you create the snapshot… You can remount and resume writes once the snapshot enters the pending state. > — AWS EBS docs, Create Amazon EBS snapshots

"Enters the pending state" is the load-bearing phrase. The HTTP call returning quickly does not mean the snapshot's point-in-time has been established. On a busy 1TB volume with sustained write traffic, the actual transition to pending state — where AWS commits to "this is the volume state captured" — takes meaningful wall-clock time. We observed ~45–60 seconds in our run, and AWS itself ships its Data Lifecycle Manager application-consistent template with AUTOTHAWDURATIONSECS="60" as the default safety window — which is a strong implicit acknowledgement that "snapshot start" is not instantaneous.

If you release FTWRL when create-snapshot returns a snapshot ID over HTTP but before the snapshot has entered pending state, any writes that happen in that gap can leak into the snapshot after the binlog position you captured. Result: the snapshot disagrees with the binlog coordinate. DMS starts CDC from a position whose preceding writes are partially-in / partially-out of the Aurora full-load. You'll see it as random integrity failures during CDC apply — duplicate-key errors for rows that "shouldn't exist yet", FK violations against parent rows that "aren't there", row counts that disagree by a small fluctuating number. By the time you debug it, you've wasted the full-load and have to start over.

This is a silent failure mode. There is no error. The snapshot looks fine. The CDC task starts cleanly. The data is wrong.

The correct sequence

Hold the FTWRL for the entire duration of the create-snapshot API call, then verify the snapshot is at least in pending state before releasing:

-- Single connection, held open until snapshot has transitioned to pending.
-- Writes are blocked for this entire window. Reads still work.
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;       -- capture File and Position
-- now (in another process): aws ec2 create-snapshot ...
-- block until create-snapshot returns AND snapshot state is at least 'pending'
UNLOCK TABLES;

The "read lock" naming is MySQL's perspective — the lock-holder can read, everyone else is blocked from writing. From the application's perspective it's a write lock: writes queue, transactions stall, anything mid-write waits. For our workload, the application was configured to fail fast on connection timeouts rather than queue, so the ~1-minute window meant ~1 minute of write-path 5xx responses, which we'd announced as a maintenance window.

The shell that drives it:

# Open the MySQL session that holds FTWRL for the full snapshot window.
mysql -h "$SOURCE_HOST" -u root -p"$ROOT_PW" <<SQL &
  FLUSH TABLES WITH READ LOCK;
  SELECT SLEEP(300);          -- hold the session open up to 5 min, killed below
SQL
FTWRL_PID=$!
# Capture binlog coordinate while writes are blocked
BINLOG_INFO=$(mysql -h "$SOURCE_HOST" -u root -p"$ROOT_PW" \
  -e 'SHOW MASTER STATUS\G')
echo "$BINLOG_INFO" | tee /tmp/binlog-position.txt

Fire the snapshot. This call returns a snapshot ID quickly,

CRITICAL: wait until the snapshot is at least in pending state with

Now safe to release the lock.

In our run, this loop ran for roughly 45–60 seconds before progress moved off 0%. That's the duration writes were actually blocked on production. Not 10ms.

What about `aws ec2 wait snapshot-completed`?

Don't use it for the lock-release decision. snapshot-completed waits for full S3 upload, which on a 1TB volume can be hours. You only need the point-in-time committed, not the data fully uploaded. The progress-off-0% heuristic above is what you actually want — once AWS has started reporting non-zero progress, the source-of-truth manifest for the snapshot has been established and subsequent writes won't appear in it.

The artifact that matters

The binlog coordinate captured during the lock window:

File:     binlog.054166
Position: 157

That tuple is what DMS will use later as the CDC start point. Lose it and you start over.

(Pos: 157 looks suspiciously small because the dump began just after a binlog rotation — that's a fresh file with only the format-description event in it so far. Normal, not a bug.)

The approval gate

The Ansible play that drives this gates execution behind both an execute=true flag and a literal safety phrase. In dry-run mode (the default) it does read-only checks plus the AWS create-snapshot --dry-run permission validation:

ansible-playbook -i inventory.yml playbooks/snapshot-source-volume.yml \
  -e snapshot_execute=true \
  -e 'snapshot_safety_ack=I approve FTWRL and EBS snapshot for <project> production MySQL'

The approval phrase names the operation (FTWRL and EBS snapshot) and the environment (<project> production MySQL). If the phrase doesn't match, the playbook runs as dry-run. This is deliberately not a boolean — it forces the operator to type the consequence.

---

Phase 2 — Disposable snapshot worker

The EBS snapshot is restored as a new volume and attached to a fresh EC2 worker. This worker is disposable. It exists for the duration of the migration and is terminated after cutover.

Non-negotiable safety rules:

- Never restore the snapshot onto the live source instance. - Never use the bastion as the migration worker. - The worker runs in a private subnet with no public IP. - MySQL on the worker binds to 127.0.0.1 only. - Security group on the worker allows MySQL only from the worker itself.

One thing to know if your source snapshot is a root volume (not a separate data volume): the restored disk has a partition table, so on Nitro instances you'll be mounting something like /dev/nvme1n1p1, not /dev/nvme1n1. lsblk after attach tells you:

$ lsblk
NAME         MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
nvme0n1      259:0    0    20G  0 disk
└─nvme0n1p1  259:1    0    20G  0 part /
nvme1n1      259:2    0  1024G  0 disk
└─nvme1n1p1  259:3    0  1024G  0 part           ← mount this one

Bring-up on the worker:

# Attach the restored volume
sudo mkdir -p /mnt/source_data
sudo mount /dev/nvme1n1p1 /mnt/source_data
# Point MySQL at the cloned datadir
sudo systemctl stop mysql
sudo sed -i 's|^datadir.*|datadir=/mnt/source_data/mysql|' /etc/mysql/my.cnf

Lock it down

sudo systemctl start mysql

Sanity check

If MySQL refuses to start, it's almost always one of: stale auto.cnf (delete it, it regenerates), permissions on the datadir (chown -R mysql:mysql /mnt/sourcedata/mysql), or a stale tc.log (remove it). InnoDB recovery on a snapshot-restored datadir is normal and takes a minute or two on a 1TB volume.

---

Phase 3 — Full dump with mydumper

mydumper is parallel, chunked, and writes a metadata file with the exact binlog coordinate at dump start. That metadata file is the linchpin of the whole strategy.

mydumper \
  --host=127.0.0.1 \
  --user=root --password="$ROOT_PW" \
  --database=<database> \
  --threads=16 \
  --chunk-filesize=256 \
  --compress \
  --trx-consistency-only \
  --triggers --events --routines \
  --outputdir=/data/full_dump \
  --logfile=/data/mydumper.log \
  --verbose=3

A few choices worth calling out:

- --threads=16: matched to vCPU count on the worker. Going higher didn't help — we were I/O bound on the EBS gp3 volume, not CPU bound. - --chunk-filesize=256: 256MB chunks. Larger chunks reduce file count but make individual myloader retries slower. 256MB was a good middle. - --trx-consistency-only: don't take global locks. We're on a frozen clone, nothing is writing, but it's the right default anyway. - --compress: cuts disk footprint 3–4x on text-heavy schemas. CPU cost is negligible compared to I/O.

The metadata file you care about:

$ cat /data/full_dump/metadata
Started dump at: 2026-XX-XX HH:MM:SS
SHOW MASTER STATUS:
        Log: binlog.054166
        Pos: 157
        GTID:
Finished dump at: 2026-XX-XX HH:MM:SS

Cross-check this against the binlog coordinate captured during Phase 1. They should match. If they don't, something restarted MySQL on the worker between snapshot restore and dump start — investigate before continuing.

Validate the dump completed cleanly:

grep -iE 'error|fatal|warning' /data/mydumper.log | grep -v 'Connection ID'
ls /data/full_dump | wc -l                      # roughly tables × chunks
du -sh /data/full_dump                          # sanity vs source size

---

Phase 4 — Loading into Aurora

Pre-create the database and grants on the Aurora target. myloader will create tables but it won't create the database.

-- On the Aurora writer endpoint
CREATE DATABASE <database> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'app_rw'@'%' IDENTIFIED BY '<secret>';
GRANT SELECT, INSERT, UPDATE, DELETE, EXECUTE ON `<database>`.* TO 'app_rw'@'%';

CREATE USER 'dmstarget'@'%' IDENTIFIED BY '<secret>'; GRANT ALL ON <database>. TO 'dmstarget'@'%';

FLUSH PRIVILEGES;

Then load. This runs from the snapshot worker against the Aurora writer:

myloader \
  --host=<aurora-writer-endpoint> \
  --user=admin --password="$ADMIN_PW" \
  --database=<database> \
  --threads=16 \
  --overwrite-tables \
  --directory=/data/full_dump \
  --logfile=/data/myloader.log \
  --verbose=3

This is where Serverless v2 earns its keep. The ACU graph during load looked roughly like:

ACU
 16 ┤        ╭─────────────────╮
 12 ┤      ╭─╯                 ╰╮
  8 ┤    ╭─╯                    ╰─╮
  4 ┤  ╭─╯                        ╰──╮
  1 ┤──╯                              ╰────
    └────────────────────────────────────── time
      load starts                load ends

If we'd been on Provisioned and sized for the steady state, the load would have either taken much longer or required a manual instance class change with downtime. Auto-scale during the load was the difference between a clean overnight load and a scheduling problem.

Things to watch during the load:

- Abortedconnects on Aurora — should stay near zero. - Innodbrowlocktimeavg — spikes here usually mean you've created indexes the load is contending on. - ACU ceiling — set max ACU higher than you think you need for the load phase, then lower it post-cutover.

For the largest tables, drop non-PK indexes before the load and recreate after. Saves hours:

-- Before load
ALTER TABLE events DROP INDEX idx_events_user_id, DROP INDEX idx_events_created_at;
-- After load
ALTER TABLE events
  ADD INDEX idx_events_user_id (user_id),
  ADD INDEX idx_events_created_at (created_at),
  ALGORITHM=INPLACE, LOCK=NONE;

Bump sortbuffersize to 4MB on the Aurora cluster parameter group before the index rebuilds run. The default is too small for sorting through large tables during ADD INDEX — leaving it at the default causes the rebuilds to spill to disk and run dramatically slower than they should:

-- On the Aurora cluster parameter group:
sort_buffer_size = 4194304    -- 4 MB
-- Verify after the cluster picks it up:
SHOW VARIABLES LIKE 'sort_buffer_size';

sortbuffersize is per-session, so setting it on the parameter group is what you want — it applies to every new connection, including the myloader threads and the ALTER TABLE sessions doing the index recreates. Don't go wild with it: it's allocated per-session, and a too-large value across thousands of application connections will eat memory you'd rather give to the buffer pool. 4MB was the right balance for this workload.

---

Phase 5 — DMS CDC, starting at the exact snapshot position

DMS is not doing the full load in this flow. It's CDC-only, replicating live changes from production into Aurora, starting at the binlog coordinate from the metadata file.

Source endpoint (production MySQL):

{
  "EndpointType": "source",
  "EngineName": "mysql",
  "ServerName": "<source-mysql-host>",
  "Port": 3306,
  "Username": "dms_repl",
  "DatabaseName": "<database>",
  "ExtraConnectionAttributes":
    "eventsPollInterval=1;targetDbType=SPECIFIC_DATABASE;parallelLoadThreads=0"
}

Target endpoint (Aurora writer). Note the empty ExtraConnectionAttributes — see the charset fix below for why explicitly clearing it matters:

{
  "EndpointType": "target",
  "EngineName": "aurora",
  "ServerName": "<aurora-writer-endpoint>",
  "Port": 3306,
  "Username": "dms_target",
  "DatabaseName": "<database>",
  "ExtraConnectionAttributes": "",
  "MySQLSettings": {
    "AfterConnectScript": "SET character_set_client=utf8mb4, character_set_connection=utf8mb4, character_set_results=utf8mb4, collation_connection=utf8mb4_unicode_ci, foreign_key_checks=0"
  }
}

Task settings — the ones that mattered:

{
  "TargetMetadata": {
    "SupportLobs": true,
    "FullLobMode": false,
    "LimitedSizeLobMode": true,
    "LobMaxSize": 64,
    "BatchApplyEnabled": false
  },
  "ChangeProcessingTuning": {
    "BatchApplyPreserveTransaction": true,
    "MinTransactionSize": 1000,
    "CommitTimeout": 1
  },
  "Logging": {
    "EnableLogging": true,
    "LogComponents": [
      {"Id": "SOURCE_CAPTURE",  "Severity": "LOGGER_SEVERITY_DEFAULT"},
      {"Id": "TARGET_APPLY",    "Severity": "LOGGER_SEVERITY_DETAILED_DEBUG"},
      {"Id": "DATA_STRUCTURE",  "Severity": "LOGGER_SEVERITY_DEFAULT"}
    ]
  }
}

CDC start position from the mydumper metadata, in DMS's native format:

binlog.054166:157

Before starting the task, verify the source still has that binlog. If it doesn't, stop — re-snapshot and re-load. Don't start CDC from a later binlog position:

SHOW BINARY LOGS;
-- File should be in the list. If the lowest file > binlog.054166, you're done.

Watch lag converge:

- CDCLatencySource — time between change happening on source and DMS reading it. - CDCLatencyTarget — time between DMS reading and Aurora applying.

Both should trend to single-digit seconds within an hour for a healthy workload.

---

The five problems that actually came up

This is the section that's missing from most migration blog posts. We ran the full pipeline — snapshot, restore, mydumper, myloader, DMS CDC, validation — against a non-production Aurora target 7–8 times before the production cutover. Each rehearsal surfaced something. None of the five problems below are theoretical: all of them stopped a rehearsal task and required a fix before it would resume. The configs, task settings, and transformation rules shown elsewhere in this post are not the configs from the first run — they're the configs from the run that finally worked.

1. Generated columns broke DMS apply — and `DEFAULT_GENERATED` is a trap

DMS tried to write values into generated columns. Aurora rejected:

[TARGET_APPLY ]E: The value specified for generated column 'user_id'
                  in table 'activity_log' is not allowed.

Preflight to find them all:

SELECT TABLE_NAME, COLUMN_NAME, EXTRA, GENERATION_EXPRESSION
FROM information_schema.columns
WHERE table_schema = '<database>'
  AND EXTRA LIKE '%GENERATED%';

This query returns two different kinds of rows. Mix them up and you'll either leave a real problem unfixed or break columns DMS is supposed to write to.

DEFAULTGENERATED shows up in the same EXTRA LIKE '%GENERATED%' filter, but it's not a generated column — it's a column whose default is an expression (e.g., failedat TIMESTAMP DEFAULT (CURRENTTIMESTAMP)). DMS is supposed to write to those. Remove them from CDC apply and you'll get NULLs across the table.

For the actual schema we migrated, the remove-column transformation list looked like this:

| Table.column | Kind | | --- | --- | | activitylog.userid | VIRTUAL GENERATED | | activitylog.orderid | VIRTUAL GENERATED | | activitylog.subid | VIRTUAL GENERATED | | activitylog.productid | VIRTUAL GENERATED | | addresses.isstockempty | VIRTUAL GENERATED | | payments.intentexpiresat | VIRTUAL GENERATED | | failedjobs.failedat | NOT included (DEFAULTGENERATED) |

The fix is a DMS transformation rule per affected column. Don't drop the column on the target — Aurora still has the same generated column definition, you just need DMS to stop sending values for it:

{
  "rule-type": "transformation",
  "rule-id": "200",
  "rule-name": "remove-generated-activity-log-user-id",
  "rule-action": "remove-column",
  "rule-target": "column",
  "object-locator": {
    "schema-name": "<database>",
    "table-name": "activity_log",
    "column-name": "user_id"
  }
}

We exposed this in the Terraform module as a dmsexcludedcolumns variable — the module generates the transformation rules from the list. Don't hand-write 30 of these.

2. utf8mb3 vs utf8mb4 collation mismatch — and the wrong fix

DMS target connections came up speaking utf8mb3 by default. Aurora rejected any statement involving utf8mb4unicodeci:

[TARGET_APPLY ]E: COLLATION 'utf8mb4_unicode_ci' is not valid
                  for CHARACTER SET 'utf8mb3'

The intuitive fix — Initstmt=SET NAMES utf8mb4 in extraconnectionattributes — does not work. The MySQL ODBC driver DMS uses rejects it:

SET NAMES not allowed by driver

What does work is AfterConnectScript on the MySQL endpoint settings, which runs after the driver does its own session setup:

SET character_set_client=utf8mb4,
    character_set_connection=utf8mb4,
    character_set_results=utf8mb4,
    collation_connection=utf8mb4_unicode_ci,
    foreign_key_checks=0

(We combine the FK fix into the same statement — more on that below.)

A subtlety that wasted an hour the first time: if a previous attempt left Initstmt=SET NAMES utf8mb4 in extraconnectionattributes, you have to explicitly clear it when you add the AfterConnectScript. Updating one without clearing the other leaves the stale Initstmt in place, the driver still rejects it, and your "fix" looks broken. In Terraform we set extraconnectionattributes = "" on the target endpoint to be unambiguous.

Verify what's actually on the endpoint:

aws dms describe-endpoints \
  --filters 'Name=endpoint-arn,Values=<target-endpoint-arn>' \
  --query 'Endpoints[0].{ExtraConnectionAttributes:ExtraConnectionAttributes,MySQLSettings:MySQLSettings}' \
  --output json

3. Foreign-key ordering during CDC apply

CDC apply replays source transactions, but DMS doesn't always apply them in source-commit order under batch mode. That's fine for tables with no FK relationships and catastrophic when you have a graph like:

addresses.user_id       -> users.id
transactions.created_by -> users.id

A child-row insert can land before its parent. Apply errors out:

Cannot add or update a child row: a foreign key constraint fails
  (`<database>`.`addresses`, CONSTRAINT `fk_addresses_user_id`
   FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))

Two fixes, in order of preference:

"BatchApplyEnabled": false

This makes DMS apply changes transaction-by-transaction in source order. Slower throughput, but correct.

If FK ordering errors still occur, also set foreignkeychecks=0 only in the DMS apply session via AfterConnectScript (folded into the same statement as the charset fix above). This disables FK checks on the DMS apply session only — your application sessions still enforce FKs. The data integrity guarantee comes from the source: if it committed on the source with FKs intact, it'll be intact on the target once apply completes.

4. DMS endpoint test must be rerun after every change

This wasted an hour. Every time we touched a DMS endpoint — even adding a tag — the connection had to be retested before the task would resume.

The wrong move is to trust a "successful" status from yesterday. describe-connections shows the last test result, not the current would-be result. Endpoint config changes invalidate the test silently.

aws dms test-connection \
  --replication-instance-arn <repl-instance-arn> \
  --endpoint-arn <endpoint-arn>
# Watch until both source and target show successful
aws dms describe-connections \
  --filters 'Name=replication-instance-arn,Values=<repl-instance-arn>' \
  --query 'Connections[*].{Endpoint:EndpointIdentifier,Status:Status,LastFailureMessage:LastFailureMessage}' \
  --output table

The runbook now has this as a mandatory step after any endpoint modification.

5. CloudWatch log filter caught the wrong thing

Our initial alarm was a CloudWatch Logs metric filter on the literal string ERROR. It fired constantly during normal operation. The cause was buried in an info-level line:

[SOURCE_CAPTURE ]I: sql_mode = STRICT_TRANS_TABLES,NO_ZERO_DATE,
  ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

ERRORFORDIVISIONBYZERO matched. The fix is to filter on DMS severity markers, not the word "error". The DMS log component prefix is fixed-width — bracket spacing matters:

aws logs filter-log-events \
  --log-group-name dms-tasks-<task-name> \
  --start-time "$(python3 -c 'import time; print(int(time.time()*1000)-600000)')" \
  --filter-pattern '?"[TARGET_APPLY    ]E" ?"[SOURCE_CAPTURE  ]E" ?"[TASK_MANAGER    ]E"' \
  --query 'events[-10:].[timestamp,message]' \
  --output table

A few things to note:

- ?"..." is the CloudWatch Logs OR syntax — the filter matches if any of the three patterns appear. - The spacing inside the brackets is real. DMS pads component names to a fixed width (TARGETAPPLY gets 4 trailing spaces, SOURCECAPTURE gets 2, TASKMANAGER gets 4). Wrong spacing, no matches. - E = error, F = fatal, I = info. We alarm on E and F only. - The Python one-liner produces "10 minutes ago in epoch-ms", which is what --start-time expects. Recent-window queries are much cheaper than full-log queries.

Use table statistics and task status together — table stats can show zero changes when the task is running but hasn't applied anything yet (it's stuck on something the logs reveal), while logs reveal the apply-level blocker. Either signal alone is misleading.

---

Cross-VPC connectivity

The application lived in the source VPC. Aurora lived in the new VPC. For both DMS (read source → write target) and the application cutover, the two VPCs needed routed connectivity.

Four pieces, in order:

1. VPC peering          src-vpc  ←──peering──→  tgt-vpc
2. Route tables         src rt:  tgt-cidr → pcx-xxx
                        tgt rt:  src-cidr → pcx-xxx
3. Security groups      src mysql sg:  ingress 3306 from tgt-cidr  (for DMS)
                        tgt aurora sg: ingress 3306 from src-cidr  (for app)
4. DNS resolution       enable accepter/requester DNS resolution on peering

The acceptance test:

# From the source application server
nc -vz <aurora-writer-endpoint> 3306
# Connection to <aurora-writer-endpoint> 3306 port [tcp/mysql] succeeded!

If nc succeeds but mysql -h <endpoint> hangs, it's almost always DNS — peering allows the TCP connection but the application server resolves the Aurora endpoint to the wrong IP because DNS resolution on the peering isn't enabled.

---

Cutover

Once CDCLatencyTarget sat at zero for a sustained window, we cut over:

T-15m  Freeze deploys on the application
T-10m  Verify CDCLatencyTarget = 0 for 5 consecutive minutes
T-05m  Application maintenance page on
T-04m  Stop application writes; drain in-flight requests
T-03m  Verify final lag = 0; row counts on hottest tables match
T-02m  Flip application config to point at Aurora writer endpoint
T-01m  Maintenance page off; smoke tests
T+00m  DMS task stopped; source MySQL in read-only mode (insurance)

Row-count cross-check, sampled across the biggest tables at T-03m:

-- Run on both source and Aurora at T-03m
SELECT 'users' AS t, COUNT(*) FROM users
UNION ALL SELECT 'orders',       COUNT(*) FROM orders
UNION ALL SELECT 'events',       COUNT(*) FROM events
UNION ALL SELECT 'transactions', COUNT(*) FROM transactions
UNION ALL SELECT 'activity_log', COUNT(*) FROM activity_log;

The source MySQL was left in readonly = ON mode for 48 hours post-cutover as insurance. The rollback plan was: stop application writes on Aurora, reverse DMS direction (Aurora → source), wait for lag to zero, flip the application back. We never used it. Having it written down made the cutover decision less stressful.

---

What we automated

Terraform/Terragrunt owns infrastructure. Ansible owns procedural work. Two ways to run the Ansible side:

Staged, with explicit inspection between phases — this is what we used for production:

# 1. The ~1-minute write lock + snapshot, with explicit approval
ansible-playbook -i inventory.yml playbooks/snapshot-source-volume.yml \
  -e snapshot_execute=true \
  -e 'snapshot_safety_ack=I approve FTWRL and EBS snapshot for <project> production MySQL'
# 2. Apply Terraform for the worker + DMS infra using the returned snapshot_id

3. Procedural phases, each independently re-runnable

4. Set REKART_DMS_CDC_START_POSITION from /data/full_dump/metadata,

5. Cutover (or rollback) under explicit maintenance window

Orchestrated, one command wraps the whole pipeline:

ansible-playbook -i inventory.yml playbooks/orchestrate-full-migration.yml \
  -e migration_execute=true \
  -e migration_set_binlog_retention=true \
  -e migration_clean_aurora=true \
  -e migration_start_dms=true \
  -e 'migration_safety_ack=I approve full <project> MySQL migration automation'

The orchestrator is for non-production migrations where reproducibility matters more than inspection. For the actual production cutover, we used staged with migrationstartdms=false, inspected the generated CDC start position against SHOW BINARY LOGS on the source, then started DMS manually.

Two automation principles that turned out to matter:

- Approval phrases name the consequence. Every destructive operation requires both execute=true and a literal safety phrase. The phrase explicitly names the action and the environment (I approve FTWRL and EBS snapshot for <project> production MySQL). It's not a token to be cargo-culted — it forces the operator to type the consequence out loud before it happens. Wrong phrase, dry-run. - Teardown is never in the orchestrator. Automating terraform destroy is how you end up wiping the wrong account at 2 a.m. Destroy stays a separate, manually approved, intentionally awkward operation.

---

What it cost

The disposable infrastructure — snapshot worker EC2, restored EBS volume, DMS replication instance, additional snapshots taken during rehearsals — ran for ~5 days end-to-end (preflight through the 48-hour post-cutover insurance window). Total AWS spend on migration-specific resources: ~$100.

That's a small enough number that the 7–8 rehearsal runs mentioned earlier were the right way to spend the budget. At ~$100 in disposable infra, you can afford to err on the side of more rehearsals, not fewer. The real cost of this kind of migration is engineering time, not the AWS bill — and engineering time spent on the seventh rehearsal that finally goes clean is cheaper than engineering time spent debugging a half-broken production cutover at 2 a.m.

---

What we'd do differently

A few things we got right by accident or fixed mid-flight. The first one is the most important — it's the kind of thing that breaks migrations silently and only surfaces hours later when you're already deep into CDC catch-up.

- Hold the FTWRL until the snapshot is genuinely at pending state, not just until the API returns. This is the single highest-leverage correction in this entire post. The naïve sub-100ms lock pattern that most blogs describe creates a window where post-binlog-position writes leak into the snapshot, silently corrupting the snapshot↔binlog handoff. The fix is the poll loop in Phase 1: wait until Progress moves off 0% before releasing. On a busy 1TB volume that's ~45–60 seconds of blocked writes, not 10ms. Plan the maintenance window around the truth, not the marketing. - Drop non-PK indexes on the largest tables before the myloader phase, by default. We did this reactively after the first load ran 40% slower than expected. Should be the default for any table over a few hundred GB. - Test the DMS endpoint with the real character-set settings on day one. We discovered the utf8mb3/utf8mb4 issue during rehearsal, but it was avoidable — a single insert with a utf8mb4 string through the configured DMS endpoint would have surfaced it immediately. And we'd have caught the stale-Initstmt interaction sooner. - Pre-list generated columns and distinguish DEFAULTGENERATED from real generated columns as part of preflight. We hit the generated-column issue after the load was already done. The DEFAULTGENERATED gotcha didn't bite us, but only because we read the EXTRA column carefully — automating the list with a naive filter on EXTRA LIKE '%GENERATED%' would have broken the wrong columns. - Lock down CloudWatch alerting before the task starts, not after. Our first set of alarms was too noisy and we silenced them, which is exactly the wrong direction. Write the alarms against severity = "E" and "F" from the start, with the right bracket spacing. - Budget for binlog retention in disk planning. Going from default retention to 14 days added meaningful disk usage on the source. We had headroom, but it's the kind of thing that bites if you're already running close to the line.

---

Closing

The interesting part of this migration wasn't the tooling. mydumper, myloader, EBS snapshots, and DMS are all individually well-understood. The interesting part was the composition: using the snapshot to keep the bulk work off production, using the binlog coordinate as the precise handoff between the snapshot and DMS, and using Serverless v2's elasticity to make the load phase a non-event instead of a capacity-planning exercise.

The result was a ~1TB migration with a ~1-minute write-lock window and a 10-minute cutover, and a runbook we now use as the default pattern for self-managed-MySQL-to-Aurora migrations across other workloads.

If you're sitting on a self-managed database and the cutover risk is what's stopping you from moving, we're happy to share the runbook in more detail.

---

About DataOrc & OrcaSheets

This migration is the kind of work we've been doing since founding DataOrc in 2018 — make data accessible, at scale, at sane cost. Across 70+ enterprise clients, we've built petabyte-scale platforms and 50K+ TPS systems while obsessing over reliability, performance, and total cost of ownership. A ~$100 AWS bill for a 1TB production migration is exactly the kind of outcome that philosophy is aiming at.

OrcaSheets is that philosophy turned product: cloud-grade analytics that run on your machine. Open formats, local-first compute, billions of rows — no data center rental required.

Want a no-strings consulting session with our tech team, or just want to sanity-check an architecture decision before you commit to it? Ping us. We're happy to help — whether you end up using OrcaSheets or not.