Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Zero-Downtime MySQL Migration at 100M Rows: Dual-Write Pattern & MyBatis Plugin Design
Databases 21 min read

Zero-Downtime MySQL Migration at 100M Rows: Dual-Write Pattern & MyBatis Plugin Design

This article details vivo's zero-downtime migration of 100M-row MySQL tables for their game center appointment service, covering dual-write strategy selection, MyBatis plugin implementation for seamless data source switching, auto-increment ID consistency challenges, async write pitfalls, and a seven-step cutover process with rollback safeguards.

Background

The appointment service is a critical business in vivo Game Center. Historically, its tables shared a database with other services. Slow SQL from other services could impact appointment reliability. To improve stability and data isolation, the team decided to migrate appointment tables to a dedicated database.

Solution Selection

Common migration approaches include downtime migration, incremental migration, and dual-write. The appointment service has high read/write frequency, cannot tolerate downtime, and can accept second-level inconsistency for most scenarios. Downtime migration was rejected. Incremental migration struggles with inactive user data. Dual-write was chosen because every step is rollback-capable, minimizing business risk. To reduce code-change overhead across many read/write scenarios, a MyBatis plugin was implemented to handle dual-write logic centrally.

Preparation

3.1 Full Sync, Incremental Sync & Consistency Verification

Company-provided data tools were used: full sync via MySQLDump, incremental sync via binlog, consistency verification by comparing aggregated column checksums between old and new databases.

3.2 Code Transformation

A new data source and corresponding MyBatis Mapper classes were created. A custom FullPathBeanNameGenerator using fully-qualified class names as bean names avoided Spring bean-name conflicts caused by duplicate simple class names.

public class FullPathBeanNameGenerator implements BeanNameGenerator {
    @Override
    public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
        return definition.getBeanClassName();
    }
}

Primary keys are MySQL auto-increment IDs (no sharding middleware). The team verified all inserts use MyBatis useGeneratedKeys to retrieve generated IDs, ensuring old and new databases stay in sync.

3.3 Plugin Implementation

The plugin intercepts Executor.update and Executor.query to implement data-source switching, result comparison, and async writes. It extracts the mapper path from MappedStatement, maps it to the new mapper, obtains a new SqlSession, and reflectively invokes the target method.

@Intercepts({
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class})
})
public class AppointMigrateInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement ms = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        String id = ms.getId();
        String sourceMapper = id.substring(0, id.lastIndexOf("."));
        // ...
    }
}

The invoke method resolves the new mapper class, opens a new session, converts MyBatis-wrapped parameters back to raw arguments, locates the target method via cache, and invokes it reflectively.

protected Object invoke(Invocation invocation, TableConfiguration tableConfiguration) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    Object parameter = invocation.getArgs()[1];
    Class<?> targetMapperClass = tableConfiguration.getTargetMapperClazz();
    SqlSession sqlSession = sqlSessionFactory.openSession();
    Object result = null;
    try {
        Object mapper = sqlSession.getMapper(targetMapperClass);
        Object[] paramValues = getParamValue(parameter);
        Method method = getMethod(ms.getId(), targetMapperClass, paramValues);
        paramValues = fixNullParam(method, paramValues);
        result = method.invoke(mapper, paramValues);
    } finally {
        sqlSession.close();
    }
    return result;
}

private Object[] fixNullParam(Method method, Object[] paramValues) {
    if (method.getParameterTypes().length > 0 && paramValues.length == 0) {
        return new Object[]{null};
    }
    return paramValues;
}
getMethod

caches method lookups; findMethodByMethodSignature matches by name only (MyBatis mappers don't support overloading). getParamValue reverses MapperMethod.convertArgsToSqlCommandParam to extract raw parameters from maps keyed by "collection", "array", or "paramN".

private Object[] getParamValue(Object parameter) {
    List<Object> paramValues = new ArrayList<>();
    if (parameter instanceof Map) {
        Map<String, Object> paramMap = (Map<String, Object>) parameter;
        if (paramMap.containsKey("collection")) {
            paramValues.add(paramMap.get("collection"));
        } else if (paramMap.containsKey("array")) {
            paramValues.add(paramMap.get("array"));
        } else {
            int count = 1;
            while (count <= paramMap.size() / 2) {
                try {
                    paramValues.add(paramMap.get("param" + (count++)));
                } catch (BindingException e) {
                    break;
                }
            }
        }
    } else if (parameter != null) {
        paramValues.add(parameter);
    }
    return paramValues.toArray();
}

Dual-Write Process

4.1 Deploy Dual-Write Code (Read/Write Old Only)

Switches: read=old, write=old, compare=off. Business still uses old DB.

4.2 Sync Old Data to New DB

Same switches. Use offline replica as source to avoid impacting online traffic. Steps 1 and 2 can be parallel.

4.3 Stop Sync, Enable Dual-Write

Switches: read=old (compare=on), write=dual, compare=on. After sync catches up, run full verification and monitor comparison logs. Stop sync before enabling dual-write to avoid duplicate/overwrite issues; gap data is fixed by compare-and-compensate job. Switch took ~30 seconds.

4.3.1 Auto-Increment Primary Key Issue

Batch INSERT IGNORE / ON DUPLICATE KEY UPDATE causes MyBatis to assign IDs incorrectly: it uses LAST_INSERT_ID() + n * AUTO_INCREMENT for affected rows only, ignoring skipped rows. Example: table has id=1; batch insert a,b,c with b duplicate → IDs become a:2, b:1, c:3; affected rows=2; LAST_INSERT_ID() =2; MyBatis sets a:2, b:3, c:null. Solution: skip these statements in plugin (force write old), handle migration at business layer by querying unique key to get real ID before inserting into new DB.

4.3.2 Transactions

Transactional logic was paused during dual-write; plugin does not support transactions. If needed, refactor at business layer.

4.3.3 Async Write Pitfall

Async write to new DB risks stale object references. Example: list.clear() after old insert but before async new insert → new DB receives empty list. Team manually audited business code to prevent such patterns.

4.4 Start Compare & Compensate Job

Switches unchanged; add compare-and-compensate job. Job cannot handle physical deletes (old row gone, new row remains). Logical deletes used mostly; one physical delete had logging for manual compensation if needed. No deletes occurred during the 30-second switch.

4.5 Gradually Shift Reads to New DB

Switches: read=partial→new, write=dual, compare=on, compensate=on. Because async write lags, latency-sensitive reads cannot be gradually shifted; must switch read+write atomically to old-write/new-read for those cases.

4.6 Stop Compensate, Cut Over to New DB, Start Reverse Compensate

Switches: read=new, write=new, compare=off, compensate=reverse (new→old). Reverse compensate runs periodically (1-2 min lag) allowing quick rollback if new DB writes fail. Why not async write old via plugin? Plugin intercepts Executor; after plugin returns, Spring's SqlSessionTemplate closes the executor, causing async old-write to fail on closed executor.

4.7 Stop Reverse Compensate, Clean Up

Monitor old DB for non-compensate traffic. Once quiet, stop job, remove migration code, purge old data.

Summary & Lessons

Plugin Design Reflection: Proxying or rewriting MapperProxy instead of Executor could avoid complex parameter conversion and enable write-new-then-async-write-old (not yet validated).

Auto-Increment IDs: Confirm if old/new ID consistency is required.

Transactions: Evaluate transaction support needs per business; pause if unsupported.

Async Write Consistency: Plugin cannot solve object-mutation races; pre-audit business logic.

Migration solution comparison diagram
Migration solution comparison diagram
Solution evaluation matrix
Solution evaluation matrix
Plugin read/write function matrix
Plugin read/write function matrix
MyBatis parameter conversion flow
MyBatis parameter conversion flow
Compare and compensate task flow
Compare and compensate task flow
About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

data migrationdual-writeMySQLvivozero-downtimeMyBatis pluginauto-increment IDconsistency verification

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion