I moved a live shop database from MySQL 8 to PostgreSQL 17 while an application kept sending it 300 requests a second. Out of 546,361 requests, none failed and none returned a wrong answer, and writes paused for 87 milliseconds at the switch. My first attempt silently lost 93 orders, and the reason why is the most useful thing in this article.
Most migration guides stop at copying the data. Copying is the easy part. The hard part is that the application keeps writing while you copy, so by the time the copy finishes it's already out of date, and you have to catch up, prove the two databases match, and switch over without anyone noticing.
I wanted to do the whole thing for real, measure every step, and write down every surprise. So I built a MySQL database that looks like a typical ten-year-old application, pointed a live workload at it, and moved it to PostgreSQL on the same Contabo server I've used for my last few articles.
Everything here comes from that run, including the parts that went wrong. All of the code is on GitHub, linked at the end.
What "zero downtime" means in this article
It's worth being precise, because the phrase gets used loosely.
Here it means that no request failed and no request returned a wrong answer at any point during the migration. The application ran the whole time, reads never stopped, and writes were held back for a fraction of a second at the moment of the switch rather than rejected. I measured all of that from the application's side, not the database's, because that's what users would feel.
The setup
The server is a Contabo Cloud VPS Plus 4 with 4 shared vCPUs and 8 GB of RAM, running MySQL 8.0.46 and PostgreSQL 17.12 side by side on Ubuntu 24.04.
A deliberately awkward source database
The MySQL database is a small online shop with 1 million users, 50,000 products, 3 million orders and 5.95 million order items, exactly 10 million rows when I generated it. By the time the final migration started, the application had added enough orders to bring it to 10,377,277 rows.
I gave it the features that make real migrations painful.
-
TINYINT(1)columns that the application treats as booleans. - Zero dates. About 19,000 users have
last_login_at = '0000-00-00 00:00:00', which old MySQL versions happily accepted. - Unsigned integers, including a
SMALLINT UNSIGNEDstock column with values up to 65,535, which doesn't fit in PostgreSQL'ssmallint. - An
ENUMfor order status. - A JSON column for product attributes.
- Emoji and accented names, such as "Pro Lamp üéß" and "Jos√©".
- Mixed-case emails under MySQL's default
utf8mb4_0900_ai_cicollation, which compares text case-insensitively and accent-insensitively. -
ON UPDATE CURRENT_TIMESTAMPonorders.updated_at. - Both
DATETIMEandTIMESTAMPcolumns, which behave differently with time zones.
A live application that checks its own answers
A Python program stands in for the shop's application. It runs 8 threads at about 300 requests per second and does the kind of work a real shop does.
- It shows orders and their items, and lists a customer's recent orders.
- It logs users in by email, typing the email in lowercase.
- It creates orders with one to three items in a transaction, moves orders from paid to shipped, records logins, and deletes abandoned carts.
Every request is timed, and every answer is checked. A login that finds no user counts as a wrong result, not a success, so a migration that quietly broke email matching would show up immediately.
The application decides which database to use by reading a small control file, which is how the switch happens. In a real system this would be a feature flag or a configuration reload. It also supports a pause state, in which reads carry on but writes wait until the state changes.
The plan
The whole migration follows seven steps, and the order matters.
- Start capturing changes in MySQL before copying anything, so no write can slip through.
- Copy all existing rows into PostgreSQL while the application keeps running.
- Build indexes in PostgreSQL after the copy, which is much faster than during it.
- Replay every captured change until PostgreSQL catches up, then keep it current.
- Compare every row in both databases, while the application is still writing.
- Switch the application, holding writes for as short a time as possible.
- Add and validate the foreign keys in PostgreSQL once the application is on it.
Step 1. The standard tool failed twice
The usual tool for moving MySQL to PostgreSQL is pgloader, which converts the schema and copies the data in one command. I ran a schema-only rehearsal into a throwaway database first, and it failed before copying a single row.
MySQL 8 uses caching_sha2_password as its default login method, and the MySQL driver built into pgloader can't handle it. Giving the account mysql_native_password isn't enough on its own, because the server still announces the new method when a client first connects. The fix is to make the old method the server-wide default, which requires restarting MySQL. On a production system you'd want to schedule that restart well before migration day.
With that fixed, pgloader failed a second time.
Collation 76 is utf8mb3_tolower_ci, which MySQL 8.0.30 and later use internally for information_schema. The pgloader package I installed from the PostgreSQL apt repository (version 3.6.10) doesn't know it, and no configuration setting changes what MySQL reports there. So that version simply can't read a current MySQL 8 server.
Rather than fight it, I did what a lot of real migrations end up doing anyway. I wrote the PostgreSQL schema by hand, so every type decision is deliberate, and used a small streaming copier for the data. If you want to use pgloader, test it against your exact MySQL version first, and check whether a newer pgloader build supports it.
Step 2. Design the PostgreSQL schema yourself
These are the type decisions I made and why. Each one fixes a specific difference between the two databases.
-
INT UNSIGNEDbecamebigint, because unsigned integers go up to 4.29 billion and PostgreSQL'sintegerstops at 2.1 billion. -
SMALLINT UNSIGNEDbecameintegerwith a check constraint for 0 to 65,535. -
TINYINT(1)becameboolean, and the copier converts 0 and 1 to false and true. - Zero dates became
NULL, because PostgreSQL has no zero date. -
DATETIMEbecametimestamp, without a time zone, because that's whatDATETIMEis. It stores whatever wall-clock time the application gave it. -
TIMESTAMPbecametimestamptz, because MySQL storesTIMESTAMPvalues in UTC and converts them to the session's time zone when you read them. -
ENUMbecame a PostgreSQL enum type with the same labels in the same order. JSONbecamejsonb.- The email column became
citext, PostgreSQL's case-insensitive text type, so that logging in with a lowercase email still findsAhmed.Andersson…@EXAMPLE.org. This is the one most migrations get wrong, and I come back to it below. -
AUTO_INCREMENTbecame an identity column,GENERATED BY DEFAULT, so rows can be copied with their original ids.
Two things are deliberately left out of the initial schema. Indexes are built after the bulk copy, and foreign keys are added at the very end, for reasons that will become clear.
CREATE EXTENSION IF NOT EXISTS citext; CREATE TYPE order_status AS ENUM ('pending', 'paid', 'shipped', 'delivered', 'cancelled'); CREATE TABLE users ( id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, email citext NOT NULL, full_name varchar(200) NOT NULL, is_active boolean NOT NULL DEFAULT true, country char(2) NOT NULL, last_login_at timestamp NULL, created_at timestamptz NOT NULL DEFAULT now() ); The full schema for all four tables is in the repository.
One time zone detail cost me a bug before the migration even started. The migration tools must read MySQL in UTC, by running SET time_zone = '+00:00', or every TIMESTAMP value comes out shifted by the server's offset. That was one or two hours on this Berlin-based server. But the application itself must keep MySQL's default time zone, or the DATETIME values it writes with NOW() shift instead. Both databases here use Europe/Berlin, so a DATETIME written before the switch means the same thing as one written after it.
Step 3. Capture changes before you copy anything
The copy takes time, and the application keeps writing during it. Every insert, update and delete in that window has to reach PostgreSQL too, and the only safe way to guarantee that is to start recording changes before the copy starts.
I used triggers, because they need nothing beyond MySQL itself. Every insert, update and delete on the four tables adds a row to a small change log, recording only which table and which primary key changed.
CREATE TABLE _migration_changelog ( seq BIGINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, table_name VARCHAR(32) NOT NULL, pk BIGINT UNSIGNED NOT NULL, changed_at TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ); CREATE TRIGGER trg_orders_update_cdc AFTER UPDATE ON orders FOR EACH ROW INSERT INTO _migration_changelog (table_name, pk) VALUES ('orders', NEW.id); -- ...and the same for INSERT and DELETE on every table The log deliberately doesn't store the changed values. The process that applies changes re-reads each row's current state from MySQL instead. If the row exists, it's upserted into PostgreSQL, and if it's gone, it's deleted. That design has two big advantages. The result only ever depends on MySQL's latest state, no matter how many times a row changed, and replaying the same entry twice is harmless. Both turned out to matter.
For bigger systems, tools like Debezium read MySQL's binary log instead of using triggers, which avoids the extra writes. The trade-off is running Kafka and its connectors. At 300 requests a second, the triggers cost almost nothing, as the measurements below show.
Step 4. Copy everything while the application runs
The copier reads each table in primary-key order, 20,000 rows at a time, with WHERE id > last_id ORDER BY id LIMIT 20000. That way no MySQL query runs for long or holds old row versions open. Each page is converted and written to PostgreSQL with COPY, its fastest way to load data. The two big tables are split into ranges so that four processes can work at once.
It copied 10,393,629 rows in 66.7 seconds, an average of about 156,000 rows per second, while the application kept serving its 300 requests a second. Building the five indexes afterwards took 16 seconds.
Rows that changed during the copy might have been copied in their old state, or not copied at all if they were inserted after their range had been read. That doesn't matter, because the change log recorded all of them.
Step 5. Catch up, and keep up
The sync process reads the change log in order, re-reads the affected rows from MySQL, and applies each batch to PostgreSQL in one transaction. It deletes children before parents and upserts parents before children.
This is where my own mistakes showed up. In the final run, the sync process crashed on its first batch because of a bug in my code. I hadn't tested a change I'd made, and a Python tuple met a list. I didn't notice for 18 minutes. During that time the application carried on without a single error and the triggers kept recording, so the change log simply grew. When I fixed the bug and restarted sync, it worked through the backlog.
221,889 waiting changes were applied in 18 seconds, and from then on PostgreSQL stayed within a few changes and a few milliseconds of MySQL. That's the real argument for re-reading rows instead of replaying stored values. Because replaying is harmless, a crash costs you nothing except time, and you can restart from the beginning of the log without thinking about it.
Step 6. The bug that silently lost 93 orders
My first complete attempt finished, switched the application to PostgreSQL, and then failed while validating the foreign keys.
PostgreSQL had order items for orders it had never received. Order 3123631 existed in MySQL, but not in PostgreSQL. When I counted properly, 93 orders created during the migration were missing, and the foreign key only exposed the 10 of them whose items happened to make it across.
The cause is a trap that catches a lot of hand-built change capture. Every change log entry gets its seq number from AUTO_INCREMENT when the trigger fires, but it only becomes visible to other connections when the transaction commits, and transactions don't commit in the order they started. Here's how an entry gets lost.
- Transaction A creates an order and its trigger takes seq 100. A then inserts its items, which take seqs 105 and 106.
- Meanwhile, transaction B takes seqs 101 to 104 and commits first.
- Sync reads "everything after the last seq I saw", finds 101 to 104, and moves its position to 104.
- A commits. Sync reads everything after 104, finds the items at 105 and 106, and applies them. It never looks back for 100, so the order is lost.
The fix is to treat missing numbers as gaps, not as the end of the line. The corrected sync remembers every seq number it hasn't seen yet below the highest one it has processed. It re-checks those gaps on every loop until the missing entries appear, and only gives up on a gap after 30 seconds, which is far longer than any transaction in this application. A gap that never fills belongs to a transaction that was rolled back, because AUTO_INCREMENT never reuses numbers. At cutover, once no write is in flight, any remaining gap must be a rollback, so cutover tells sync to stop waiting.
In the second attempt, the gap tracking picked up 26 late commits that the first version would have skipped. The application was the same and so was the load, so at least that many changes would have been lost again.
Two lessons came out of this. First, if you build change capture on a sequence number, assume entries can become visible out of order. Second, foreign keys are a safety net, not a verification. They caught 10 problems out of 93. A full comparison catches all of them, which is the next step.
Step 7. Compare every row while the application is writing
Before switching, I compared all of the data in both databases. Each table is split into chunks of 50,000 ids, and each chunk is turned into a hash of every row's values, normalized so that the same value compares equal on both sides. Zero dates and NULLs both become NULL, JSON keys are sorted, and timestamps are converted to UTC. Matching chunks are skipped, and chunks that differ are compared row by row.
It compared 10,584,744 rows in 262 seconds. At first glance, 129 rows differed, because the application was still writing and sync hadn't applied those changes yet. In one example, an order the application inserted between the MySQL read and the PostgreSQL read showed up on one side only. The verifier waits a couple of seconds and re-checks only the rows that differed, and after that zero rows were different. If any row had still differed, the migration script would have refused to cut over and left the application on MySQL.
Step 8. The switch
The cutover follows a strict sequence, and each step is timed.
- Prepare. Every application thread opens its PostgreSQL connection in advance while still using MySQL, so nobody pays for a new connection at the critical moment.
- Pause writes. New writes wait while reads carry on. The script waits until no write is in flight anywhere in the application.
- Drain. Sync applies every change logged up to that moment.
- Finish PostgreSQL. In one transaction, the script resets the identity sequences to the highest copied id, creates the
updated_attrigger, and adds the foreign keys asNOT VALID. - Switch. The application moves to PostgreSQL, and the waiting writes continue there.
Writes were held for 87 milliseconds in total. Waiting for in-flight writes to finish took 21 ms, draining the last changes took 31 ms, and preparing PostgreSQL took 34 ms. Here's what the application saw, second by second.
In the second of the switch, 51 requests were served by MySQL and 235 by PostgreSQL. The slowest write took 103 ms, including its wait, and no request failed. The same moment in Grafana looks like this.
The foreign keys were added as NOT VALID, which takes effect instantly. PostgreSQL checks new rows against them immediately, but doesn't scan the existing ones. Validating them afterwards with ALTER TABLE ... VALIDATE CONSTRAINT scans the table without blocking reads or writes. That took 2.7, 3.9 and 0.9 seconds for the three keys while the application ran on PostgreSQL.
The whole migration from the application's point of view
Over 30 minutes, the application sent 546,361 requests. 489,784 were served by MySQL and 56,577 by PostgreSQL, and none failed and none returned a wrong answer, including during the 18 minutes when sync was down.
The response times show where the migration actually cost something.
- The triggers cost almost nothing. With change capture on and sync running, the median write took 2.5 ms, the same as before the triggers existed.
- The bulk copy was the expensive part. For the minute it ran, median writes went from 2.6 to 4.7 ms and the slowest 1% of writes from 6.7 to 17.7 ms, because the copier, the application and both databases shared four CPU cores.
- PostgreSQL was a little faster afterwards. Median reads went from 1.0 ms to 0.7 ms and median writes from 2.6 ms to 1.2 ms, although PostgreSQL also had a quieter server, since MySQL was no longer doing any work.
The behaviour changes that would have broken the application
Copying the data correctly isn't the same as the application behaving correctly. These are the differences I hit, each shown with real output from both databases.
Accents stopped matching
MySQL's default collation ignores accents as well as case, so searching for jose finds josé. citext only ignores case.
If your users rely on this, you need PostgreSQL's unaccent extension or a nondeterministic ICU collation. That's worth deciding before the switch, not after the first support ticket.
Case-insensitive email only works with citext
With an ordinary text column, every login typed in a different case from the stored email fails. The application's correctness check counted zero wrong logins in this migration only because the column is citext.
Zero dates
Modern MySQL won't even let you search for a zero date in strict mode, yet 18,965 of them were sitting in the table. All of them, plus 94,775 real NULLs, arrived in PostgreSQL as NULL. PostgreSQL shows slightly fewer NULLs now because some of those users logged in after the switch. Any application code that checks for '0000-00-00' needs to check for NULL instead.
The same SQL gives different answers
5 / 2 is 2.5 in MySQL and 2 in PostgreSQL, because PostgreSQL keeps integer division as an integer. 'a' || 'b' is 0 in MySQL, where || means OR, and 'ab' in PostgreSQL. IFNULL, backtick-quoted names and LIMIT 10, 5 don't exist in PostgreSQL at all. The silent ones, division and ||, are the dangerous ones, because they return a wrong answer instead of an error. In the test application, the only query that had to change was how a new order's id is fetched, from MySQL's lastrowid to PostgreSQL's RETURNING id. A real application will have many more, and searching the code for these patterns before the migration is time well spent.
Forgotten sequences break the first insert
Because rows were copied with their original ids, PostgreSQL's identity sequences still started at 1, and the first insert after the switch would have failed with a duplicate key error. Resetting them with setval is one line per table, and the cutover does it before the switch.
ON UPDATE CURRENT_TIMESTAMP needs a trigger
PostgreSQL has no equivalent of MySQL's ON UPDATE CURRENT_TIMESTAMP, so without a trigger updated_at would silently stop changing. The trigger is only created at cutover, because before that the sync process needs to copy MySQL's own updated_at values unchanged.
PostgreSQL used more disk
The same data takes about 1.3 GB in PostgreSQL against 1.1 GB in MySQL, mostly because PostgreSQL stores a larger header with every row. Plan for some extra space.
A checklist for your own migration
- Rehearse with your exact versions. pgloader failed here on two things that only show up with current MySQL 8 releases.
- Write down every column type decision. Unsigned integers,
TINYINT(1), zero dates,DATETIMEversusTIMESTAMP, enums and collations all need a deliberate answer. - Decide how text should compare. If MySQL ignored case or accents, PostgreSQL won't unless you make it, with
citext,unaccentor an ICU collation. - Start capturing changes before the copy, and make replaying a change harmless.
- Never trust a sequence number to tell you what's been committed. Track the gaps.
- Build indexes after the bulk copy and add foreign keys as
NOT VALIDat cutover. - Compare every row before switching, re-check differences, and refuse to switch if any remain.
- Reset sequences, recreate
ON UPDATEbehaviour with triggers, and search the application forIFNULL, backticks,LIMIT x, y, integer division and||. - Measure the switch from the application's side, and pause writes rather than rejecting them.
What this test doesn't tell you
- There was no way back. Once the application wrote to PostgreSQL, MySQL stopped receiving changes. A production migration should keep reverse replication running for a while, so you can switch back if something you didn't test goes wrong.
- The application was built for the switch. Its control file made pausing and switching easy. A real application needs a feature flag, a configuration reload or a connection layer that can do the same.
- The application's queries were known in advance. Real codebases hide dialect differences in reports, admin pages and background jobs. They need a proper search before the switch.
- The load was modest. At 300 requests a second, the triggers were nearly free. At thousands of writes a second, reading MySQL's binary log with a tool like Debezium is the better choice.
- Stored procedures, views, MySQL triggers and events weren't part of this schema. Each of them has to be rewritten by hand.
- Everything ran on one shared-CPU server, which made the bulk copy's impact on the application larger than it would be with separate machines.
The schemas, change capture, copier, sync process, verifier, cutover script, test application, Grafana dashboard and every log from both attempts are on GitHub at github.com/isaactony/mysql-to-postgres-migration.
The bottom line
Copying 10 million rows took a minute. Everything around it took the real effort. That meant catching every change made during the copy, proving the two databases matched, finding the behaviour differences hiding in collations and old SQL, and switching in a way users couldn't notice.
The most valuable moment wasn't the 87-millisecond switch. It was the failed first attempt, where a perfectly reasonable piece of code lost 93 orders without a single error, and only a foreign key check that happened to run afterwards gave it away. If you take one thing from this, make it this. Don't assume a migration worked because nothing complained. Compare every row before you switch, and design every step so that running it twice is safe.


















