零停机数据库迁移:MySQL 到 TiDB 的平滑过渡方案
Zero-Downtime Database Migration: Smooth Transition from MySQL to TiDB
| Zhao Jun | 2026-07-25T10:00:00
详解 iDev 核心业务从 MySQL 迁移到 TiDB 的零停机方案,包括双写策略、数据校验和灰度切换流程。
Detailed guide on iDev's zero-downtime migration from MySQL to TiDB for core business, including dual-write strategy, data verification, and canary switching.
迁移动机随着业务增长,iDev 订单系统的单表数据量突破5亿行,MySQL 主从架构面临读写瓶颈。选择 TiDB 作为目标数据库,因为它兼容 MySQL 协议、支持水平扩展、且无需手动分库分表。迁移架构我们采用了"双写+灰度切换"的零停机迁移方案:全量同步:使用 TiDB DM(Data Migration)工具同步历史数据增量同步:基于 Binlog 实时同步增量数据双写验证:应用层同时写入 MySQL 和 TiDB,对比结果一致性读流量灰度:逐步将读请求从 MySQL 切换到 TiDB(1% → 10% → 50% → 100%)写流量切换:确认数据一致后,将写入切换到 TiDB下线旧库:保留 MySQL 作为冷备一周后下线数据校验# 使用 sync-diff-inspector 进行数据校验 tiup sync_diff_inspector \ --source-db "mysql://user:pass@mysql:3306/orders" \ --target-db "mysql://user:pass@tidb:4000/orders" \ --check-thread-count 16关键经验提前处理 MySQL 特有的 SQL 语法(如 GROUP BY 隐式排序)TiDB 的事务大小有限制(默认100MB),大批量更新需分批索引策略需重新评估,TiDB 的 Coprocessor 下推特性影响索引选择
Migration MotivationWith business growth, iDev's order system single-table data volume exceeded 500 million rows, and the MySQL primary-replica architecture faced read-write bottlenecks. We chose TiDB as the target database because it's MySQL-compatible, horizontally scalable, and eliminates manual sharding.Migration ArchitectureWe adopted a "dual-write + canary switching" zero-downtime migration approach:Full Sync: Use TiDB DM (Data Migration) tool to sync historical dataIncremental Sync: Real-time incremental sync based on BinlogDual-Write Verification: Application layer writes to both MySQL and TiDB, comparing result consistencyRead Traffic Canary: Gradually shift read requests from MySQL to TiDB (1% → 10% → 50% → 100%)Write Traffic Switch: After confirming data consistency, switch writes to TiDBDecommission Old DB: Keep MySQL as cold backup for one week before decommissioningData Verification# Using sync-diff-inspector for data verification tiup sync_diff_inspector \ --source-db "mysql://user:pass@mysql:3306/orders" \ --target-db "mysql://user:pass@tidb:4000/orders" \ --check-thread-count 16Key LessonsHandle MySQL-specific SQL syntax in advance (e.g., implicit GROUP BY ordering)TiDB has transaction size limits (default 100MB), batch large updatesIndex strategies need reevaluation; TiDB's Coprocessor pushdown affects index selection