Comprehensive Guide: Zero-Downtime Migration of PostgreSQL and MySQL

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Comprehensive Guide: Zero-Downtime Migration of PostgreSQL and MySQL
Complex
~3-5 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1358
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1250
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    956
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1188
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    947

Imagine this: your PostgreSQL 13 database is running under 10,000 RPS, and you need to upgrade to PostgreSQL 15 without stopping the application. A typical dump and restore means hours of downtime—clients are lost, revenue drains. Each hour of downtime can cost up to $250,000. We solve this with zero-downtime migration using logical replication, batched data transfer, and automatic failover. With over 50 successful projects, we guarantee 99.9% data integrity and provide a custom plan for your infrastructure.

Over the past three years, we have handled migrations for projects with loads from 1,000 to 50,000 RPS. This article covers all aspects of database upgrade—both pg_upgrade and logical replication—and shows how to update your database painlessly while maintaining availability. Contact us for a free consultation, and we will prepare an individual migration plan within one day. Pricing starts at $5,000 for a basic PostgreSQL upgrade.

Principles of zero-downtime migrations

Any schema change follows backward-compatible stages:

  1. Add new (column, table) — the application ignores the new.
  2. Deploy code that writes to both places.
  3. Migrate existing data in batches.
  4. Deploy code that reads only from the new.
  5. Remove the old.

No DROP COLUMN or RENAME COLUMN in production in a single step.

How to perform a zero-downtime PostgreSQL migration?

Method 1: pg_upgrade with a replica

pg_upgrade is about 10x faster than logical replication in terms of execution time, but requires a short downtime window for preparation and does not allow rollback. "pg_upgrade uses hard links to avoid copying data, making it extremely fast."

# 1. Set up the new PostgreSQL version side by side
apt install postgresql-15

# 2. Stop writes (short downtime for preparation)
pg_ctl -D /var/lib/postgresql/14/main stop

# 3. pg_upgrade with --link (no file copying)
/usr/lib/postgresql/15/bin/pg_upgrade \
  --old-datadir=/var/lib/postgresql/14/main \
  --new-datadir=/var/lib/postgresql/15/main \
  --old-bindir=/usr/lib/postgresql/14/bin \
  --new-bindir=/usr/lib/postgresql/15/bin \
  --link \
  --check

# 4. Execute upgrade
/usr/lib/postgresql/15/bin/pg_upgrade \
  --old-datadir=/var/lib/postgresql/14/main \
  --new-datadir=/var/lib/postgresql/15/main \
  --old-bindir=/usr/lib/postgresql/14/bin \
  --new-bindir=/usr/lib/postgresql/15/bin \
  --link

The --link mode uses hard links instead of copying—for a 100 GB database, it takes seconds instead of hours. Drawback: you cannot start the old version afterward.

Method 2: Logical Replication (true zero-downtime)

-- On the old server (PG 13)
CREATE PUBLICATION migration_pub FOR ALL TABLES;

-- On the new server (PG 15) — create the same schema
pg_dump -s -U postgres myapp | psql -U postgres -h new-server myapp

-- Subscribe to replication
CREATE SUBSCRIPTION migration_sub
  CONNECTION 'host=old-server dbname=myapp user=replication password=pass'
  PUBLICATION migration_pub;

-- Monitor initial sync progress
SELECT subname, received_lsn, latest_end_lsn
FROM pg_stat_subscription;

After synchronization:

-- Check lag (should be near zero)
SELECT now() - last_msg_receipt_time AS subscription_lag
FROM pg_stat_subscription;

-- Cutover: stop writes to old DB, wait for lag = 0
-- Update application connection string
-- Drop subscription
DROP SUBSCRIPTION migration_sub;

Comparison of migration methods

Method Execution time Downtime Rollback Additional resources
pg_upgrade Seconds (100 GB) Yes (up to 5 min) No Minimal
Logical replication Hours (setup) No Yes Extra server, disks

Why schema migrations require multiple steps?

Adding a NOT NULL column

You cannot do it in one step — ALTER TABLE will lock the table for the entire DEFAULT computation.

Correct approach:

-- Step 1: add column with DEFAULT (PostgreSQL 11+ — instant)
ALTER TABLE users ADD COLUMN phone VARCHAR(20) DEFAULT NULL;

-- Step 2: fill data in batches
DO $$
DECLARE
  batch_size INT := 1000;
  offset_val INT := 0;
BEGIN
  LOOP
    UPDATE users SET phone = '' WHERE id IN (
      SELECT id FROM users WHERE phone IS NULL ORDER BY id LIMIT batch_size
    );
    EXIT WHEN NOT FOUND;
    PERFORM pg_sleep(0.01);
  END LOOP;
END $$;

-- Step 3: add NOT NULL constraint (fast if no NULLs)
ALTER TABLE users ALTER COLUMN phone SET NOT NULL;

Renaming a column

-- Step 1: add new column
ALTER TABLE orders ADD COLUMN customer_id BIGINT;

-- Step 2: fill data (+ trigger for new writes)
CREATE OR REPLACE FUNCTION sync_customer_id() RETURNS TRIGGER AS $$
BEGIN
  NEW.customer_id := NEW.user_id;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER sync_customer_id_trigger
BEFORE INSERT OR UPDATE ON orders
FOR EACH ROW EXECUTE FUNCTION sync_customer_id();

-- Batch fill existing records
UPDATE orders SET customer_id = user_id WHERE customer_id IS NULL;

-- Step 3: deploy code reading customer_id
-- Step 4: remove old column and trigger
ALTER TABLE orders DROP COLUMN user_id;
DROP TRIGGER sync_customer_id_trigger ON orders;

Tools for online migrations

Tool Database Features
gh-ost MySQL Online schema migration without locks, from GitHub
pg-osc PostgreSQL Analog of gh-ost for Postgres
Flyway PostgreSQL, MySQL Versioned migrations, undo support
Liquibase PostgreSQL, MySQL Changelogs in XML/YAML/JSON

Example of using gh-ost:

gh-ost \
  --host=db-master \
  --database=myapp \
  --table=users \
  --alter="ADD INDEX idx_email (email)" \
  --execute

Testing the migration plan

# Restore production dump to staging
pg_restore -U postgres -d myapp_staging production.dump

# Verify migration plan
psql -U postgres myapp_staging < migration_plan.sql

# Measure execution time
\timing on
\i migration_plan.sql
Additional checks for logical replication - Ensure wal_level = logical on the old server. - Verify the replication user has publish privileges. - Monitor lag using pg_stat_replication.

Monitoring and rollback readiness

After initiating logical replication, it is critical to monitor replication lag and the health of both servers. We configure Prometheus + Grafana with a dashboard for pg_stat_replication: lag exceeding 100 MB signals to slow down batch migration or increase resources. Simultaneously, we keep a rollback plan ready: in case of any anomaly, we can return traffic to the old server within 30 seconds. Typical metrics for monitoring: received_lsn vs sent_lsn (lag in bytes), write_lag, flush_lag, and replay_lag from pg_stat_replication. For MySQL — Seconds_Behind_Source from SHOW SLAVE STATUS. Zero lag before cutover is achieved by stopping writes on the source for 2–5 seconds—this is the only moment of 'risk'. For large databases (>=500 GB), pre-synchronization via rsync or pg_basebackup speeds up initial subscription preparation by 3-5 times compared to pure replication. We document every step in a runbook and train the client's team to use it.

What's included in the work

  • Audit of current database schema and DBMS versions.
  • Development of a backward-compatible migration plan.
  • Setup of logical replication or pg_upgrade.
  • Batch data transfer with integrity verification.
  • Lag monitoring and automatic failover.
  • Documentation and team training.
  • Rollback plan guarantee for 30 days.

Timelines and cost

Zero-downtime PostgreSQL upgrade with logical replication: 2–3 days. Complex schema migration with multiple steps: 1–2 weeks (including staging tests). Cost: starting from $5,000 for a basic PostgreSQL upgrade. Contact us for a free evaluation of your project.

Website Redesign and Migration: CMS Change, SEO Preservation

A client came to us 6 weeks after a self-attempted redesign: 'We moved from WordPress to Tilda, traffic dropped by 70%.' I opened Google Search Console — 847 pages returned 404, the URL structure had completely changed, not a single 301 redirect was in place. Yandex hadn't reindexed the new site yet, positions collapsed. Recovery took 4 months and resulted in significant revenue loss for the quarter. Our experience — over 7 years and 80+ successful migrations, we guarantee position retention with the right approach.

Why Do Migrations Break SEO?

Search engines have indexed specific URLs. If /catalog/shoes/nike-air-max-270 turned into /products/nike-air-max-270 without a 301 redirect — all the link equity, traffic, and rankings go nowhere. Google says 301 passes ~99% of PageRank, but in practice positions recover over 2–8 weeks, not instantly.

Commonly, SEO gets broken not out of malice, but because a developer doesn't view the URL structure as a public API. Here are typical breakages:

Problem Cause Solution
Duplicate content New site opened parallel to old Disable indexing of dev version, set canonical
Loss of metadata Title and description left in old CMS Export via API, mass import with verification
Canonical changes Pagination and filters reset Lock before development, implement in template
Speed drop Heavy sections, unoptimized images Optimize LCP, CLS, TTFB before launch

How to Recover Traffic After a Failed Migration?

If traffic dropped, act immediately:

  1. Crawl the new site for 404s and compare with the pre-migration URL list.
  2. Create redirects for all lost pages with traffic >0.
  3. Check structured data and meta tags on a test sample.
  4. Daily monitor Coverage in Search Console and positions for top 50 queries.
  5. If after 2 weeks traffic does not recover — deep audit of redirects (transitivity, chains, loops).

In our practice, a large e-commerce site lost 50% of traffic when moving from Bitrix to React + Strapi. We restored 95% of redirects in three days, and within 3 weeks traffic returned to 90% of original.

What Does a Pre-Migration Audit Include?

Before starting development on the new site:

  1. Full crawl of current site via Screaming Frog or Sitebulb. Get list of all indexable URLs with traffic from Google Search Console.
  2. Export all pages with organic traffic >0 over the last 6 months — these are priority for redirects.
  3. Record all external backlinks to specific pages — Ahrefs, Semrush.
  4. Snapshot current positions for key queries — baseline for post-migration comparison.
  5. Save Core Web Vitals from Search Console for the previous 90 days.

Table for recording:

Audit Stage Tool Criticality
URL collection Screaming Frog + GSC High
Page traffic Google Analytics / Search Console High
External links Ahrefs / Majestic Medium
Positions Yandex Wordstat / Serpstat Medium
Core Web Vitals GSC CrUX High

Contact us for a detailed pre-migration audit — we will help identify all risks and create an action plan.

URL Mapping and Redirects

For projects with 200+ pages, we create a mapping table: old URL → new URL → status (301, merged with another page, deleted). Each row is verified: does the content actually migrate here?

In Laravel, redirects are handled via configuration file and middleware, not .htaccess — faster and more manageable. For WordPress → Next.js: redirects are set in next.config.js (static) and at the Nginx/CDN level for dynamic ones. Old .htaccess on shared hosting with 500+ lines of redirects is a special hell. Each redirect is checked sequentially, performance suffers. We move to Nginx map directive or Redis cache for dynamic lookup. More at Wikipedia: HTTP 301.

How to Migrate Content from Different CMSs?

WordPress → Headless CMS (Contentful, Strapi, Sanity): WordPress REST API or WP All Export to export posts, meta fields, media files. Migration script in Node.js: parse export, transform structure, upload via CMS API. Media files are reuploaded to new storage, links updated in content. Typical problem — shortcodes in WordPress content ([gallery id="123"]): need parser and transformation to new format.

1C-Bitrix → modern stack: Bitrix stores content in non-standard tables with IBLOCK_ELEMENT_PROPERTY. Direct SQL export via phpMyAdmin or Bitrix API. Transformation is the longest part due to specific Bitrix data structure.

Heavy WYSIWYG → structured content: Years of editing in FCKEditor/TinyMCE leave inline styles, non-standard tags, broken attributes. HTML sanitize + transformation to Markdown or Portable Text (Sanity) with manual check of problematic pages.

CMS Migration Tools Complexity Risks
WordPress WP All Export, WP-CLI, REST API Medium Shortcodes, meta fields
1C-Bitrix Bitrix API, SQL export High Complex structure, infoblock properties
Joomla J2XML, direct DB export High Outdated extensions
Tilda/Readymag API export (limited) Medium No full content access

How to Preserve Technical SEO Elements During Migration?

Structured data (Schema.org) — if the old site had Product, Article, BreadcrumbList markup, they must be on the new site too. Google Search Console → Enhancement reports will show loss of rich snippets.

Sitemap XML: generated automatically, submitted to GSC a day after launch. Old sitemap remains until full reindexing.

hreflang for multilingual sites: if tags are lost during migration, conflicts between language versions in search results will start within weeks.

Open Graph and Twitter Card meta tags — often forgotten when changing template, pages stop displaying correctly when shared on social networks.

Launch and First Weeks Monitoring

DNS propagation: DNS switching takes up to 48 hours, plan launch with buffer. Cloudflare as DNS provider — propagation takes minutes, not hours.

After launch, monitor daily: Search Console → Coverage (indexing errors), Analytics → organic traffic, year-over-year comparison, crawl site for 404 errors.

First 2 weeks are critical. If traffic drops more than 30% — immediate audit of redirects and comparison with pre-migration crawl.

Launch checklist (spoiler)
  • [ ] All 301 redirects work and do not form chains
  • [ ] Sitemap submitted to GSC and Yandex.Webmaster
  • [ ] Canonical tags set on all pages
  • [ ] Open Graph / Twitter Card display checked
  • [ ] robots.txt and noindex meta tags adjusted
  • [ ] Core Web Vitals in green zone (LCP <2.5s, CLS <0.1, INP <200ms)

What the Service Includes

Results you receive:

  1. Migration plan with URL mapping and redirects in Excel/Google Sheets format.
  2. Configured 301 redirects at server level (Nginx/Cloudflare/Vercel).
  3. Migrated content with integrity check: images, meta fields, links.
  4. Structured data (Schema.org) on the new site, identical to old or improved.
  5. SEO report: position trend at 1, 3, and 6 weeks after launch.
  6. Coverage monitoring in Search Console with error notifications.
  7. Guaranteed position retention: if traffic drops more than 15% within the first month — free audit and correction.

Timelines and Estimates

  • Redesign with migration for a small site (up to 100 pages): 4–8 weeks.
  • E-commerce migration with 500+ product pages: 8–16 weeks.
  • Only technical migration part (redirects, metadata) without redesign: 1–3 weeks.

Cost is calculated individually based on scope.

Get a consultation for your project — we will respond within a day. Order a pre-migration audit of your site and receive a detailed proposal with a redirect plan. Contact us to discuss details.