Fixing MySQL Replication Inconsistencies with pt-table-checksum and pt-table-sync

Database tutorial - IT technology blog
Database tutorial - IT technology blog

Real-World Problem: Silent Data Drift in MySQL Replication

Two months into managing our production database clusters, a support ticket landed on my desk: customers could not see their latest orders on the analytics portal. Our reporting stack queried a dedicated MySQL read replica to shield the primary writer from heavy analytical workloads. I immediately logged into the replica, ran SHOW REPLICA STATUS\G (or SHOW SLAVE STATUS\G on MySQL 5.7), and checked the vital signs:

Replica_IO_Running: Yes
Replica_SQL_Running: Yes
Seconds_Behind_Source: 0
Last_Errno: 0

Everything looked spotless on the surface. The I/O thread pulled relay logs, the SQL thread applied them cleanly, and replication lag was dead zero. Then I checked the actual data.

A quick count on the primary returned 1,420,105 rows in orders. The replica returned 1,419,892. Exactly 213 confirmed purchases had vanished from the secondary node without triggering a single alert or replication error.

This failure mode is called silent data drift. Native MySQL replication metrics only track thread activity and binary log positions. They confirm that transactions are processed without syntax or key errors, but they never verify row-level consistency between hosts.

Root Cause Analysis: Why Replication Desynchronizes

If binary logs apply without errors, where does the divergence come from? In production environments, discrepancies usually trace back to one of four common issues:

  • Direct writes on read replicas: Setting read_only = ON prevents standard users from writing to a replica. However, accounts with the SUPER or SYSTEM_VARIABLES_ADMIN privilege bypass this restriction completely. A single manual diagnostic query or maintenance update on the replica will silently knock tables out of alignment. Always enforce super_read_only = ON on replicas to block privileged writes.
  • Non-deterministic queries under statement-based logging: When binlog_format is set to STATEMENT or MIXED, functions like NOW(), RAND(), or UUID() evaluate independently on the primary and the replica. Similarly, UPDATE ... LIMIT 10 without an explicit ORDER BY can update completely different rows across servers. Switching to binlog_format = ROW eliminates this entire class of bugs.
  • Triggers and cascading foreign keys: Triggers that modify external tables or foreign keys defined with ON DELETE CASCADE can behave unpredictably across nodes, especially during schema migrations or partial rollouts.
  • Unlogged maintenance and manual data loads: Database operators sometimes run bulk inserts or seed data using SET sql_log_bin = 0 to speed up imports on a primary server, intending to run the same script on replicas later. Missing a single replica during that routine leads to permanent, silent divergence.

Solutions Compared: Options for Catching and Healing Drift

When you discover replica divergence, you have three primary recovery strategies:

1. Complete Replica Rebuild (mysqldump or Percona XtraBackup)

The brute-force fix requires taking a physical backup with Percona XtraBackup (or a logical dump with mysqldump), transferring 500GB+ across your network, wiping the replica’s data directory, and re-pointing replication coordinates.

  • Strengths: Delivers a proven, bit-for-bit identical replica.
  • Weaknesses: Exhausts network bandwidth and disk I/O. Rebuilding a 1TB node can take 6 to 12 hours of replica downtime just to fix 200 out-of-sync rows.

2. Custom SQL Verification Scripts

Engineering teams often write ad-hoc Python workers or federated queries to compute MD5 table hashes across servers.

  • Strengths: Uses built-in tools without installing external dependencies.
  • Weaknesses: Full-table scans flood the InnoDB buffer pool, evict hot cache pages, and trigger table lock contention. Even worse, they generate false positives because live tables receive writes during long-running comparisons.

3. Percona Toolkit (pt-table-checksum & pt-table-sync)

Percona Toolkit includes two battle-tested CLI utilities built specifically for live production audits:

  • pt-table-checksum: Chunks tables dynamically, calculates deterministic hash boundaries on the primary, writes them to a tracking table, and lets the replica verify its own chunks through replication.
  • pt-table-sync: Reads checksum diffs, computes the exact row-level delta, and generates targeted REPLACE or DELETE statements to bring nodes back in sync without taking either offline.

Step-by-Step Guide: Auditing and Syncing Your Data

Percona Toolkit lets you verify and heal replication drift online with minimal locking and built-in load throttling. Follow these steps to audit and fix your cluster.

Step 1: Install Percona Toolkit and Configure Permissions

Install the package on your administrative jump host or primary database node:

# Debian/Ubuntu
sudo apt update && sudo apt install -y percona-toolkit

# RHEL/Rocky Linux
sudo dnf install -y percona-toolkit

Create a dedicated administrative user on the primary. Because this account writes checksum results, the creation statement will replicate to your secondary instances:

CREATE USER 'pt_toolkit'@'10.0.%' IDENTIFIED BY 'K8#mP9$xL2vQ7wZ!';
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, PROCESS, SUPER, REPLICATION CLIENT, REPLICATION SLAVE ON *.* TO 'pt_toolkit'@'10.0.%';
FLUSH PRIVILEGES;

Step 2: Run pt-table-checksum on the Primary

Always run pt-table-checksum on the primary node, never directly on a replica. The utility breaks each table into indexed row chunks (defaulting to 1,000 rows), calculates an MD5 hash per block, and logs the results into a tracking table named percona.checksums. Replicas re-run the same checksum calculations on their local datasets when applying the replicated binary log events.

pt-table-checksum \
  --host=10.0.1.10 \
  --user=pt_toolkit \
  --ask-pass \
  --databases=production_app \
  --replicate=percona.checksums \
  --create-replicate-table \
  --empty-replicate-table \
  --recursion-method=processlist \
  --chunk-size=2000 \
  --max-load="Threads_running=25" \
  --critical-load="Threads_running=50"

Understanding key runtime controls:

  • --recursion-method=processlist: Discovers connected replicas dynamically by inspecting SHOW PROCESSLIST.
  • --max-load: Pauses chunk execution if active running threads cross 25, allowing sudden web traffic spikes to pass without adding query contention.
  • --critical-load: Aborts the entire run immediately if thread count hits 50, protecting production uptime.

Step 3: Evaluate Checksum Results

When the scan completes, the tool prints a summary table to stdout:

            TS ERRORS  DIFFS     ROWS  CHUNKS SKIPPED    TIME TABLE
11-27T10:15:02      0      0   845210      18       0   00:22 production_app.users
11-27T10:15:28      0      7  1420105      32       0   00:45 production_app.orders
11-27T10:16:15      0      0    53102       2       0   00:04 production_app.products

Look straight at the DIFFS column. A zero means the primary and replica match perfectly. In this sample output, production_app.orders contains 7 chunks with mismatched rows.

To inspect the affected chunks directly, run this query on the replica:

SELECT db, tbl, chunk, chunk_time, this_crc, master_crc, this_cnt, master_cnt
FROM percona.checksums
WHERE this_crc <> master_crc OR this_cnt <> master_cnt;

Step 4: Dry-Run the Remediation with pt-table-sync

Never apply blind fixes to production data. Run pt-table-sync with the --print flag first. This command reads the chunk boundaries flagged in percona.checksums, compares individual rows between the two hosts, and outputs the exact corrective SQL statements without executing them:

pt-table-sync \
  --print \
  --replicate=percona.checksums \
  h=10.0.1.10,u=pt_toolkit,p='K8#mP9$xL2vQ7wZ!' \
  h=10.0.1.20,u=pt_toolkit,p='K8#mP9$xL2vQ7wZ!'

The command produces deterministic corrective statements:

REPLACE INTO `production_app`.`orders`(`id`, `user_id`, `amount`, `status`) VALUES ('54102', '9912', '149.00', 'completed') /*pt-table-sync*/;
REPLACE INTO `production_app`.`orders`(`id`, `user_id`, `amount`, `status`) VALUES ('54103', '1040', '89.50', 'completed') /*pt-table-sync*/;

Examine the generated queries. Ensure the primary keys match your missing records and verify that existing data will not be overwritten inappropriately.

Step 5: Apply Corrections Through the Replication Stream

Once you verify the dry-run output, execute the fix by replacing --print with --execute:

pt-table-sync \
  --execute \
  --replicate=percona.checksums \
  --verbose \
  h=10.0.1.10,u=pt_toolkit,p='K8#mP9$xL2vQ7wZ!' \
  h=10.0.1.20,u=pt_toolkit,p='K8#mP9$xL2vQ7wZ!'

With --replicate enabled, pt-table-sync executes these modifications on the primary server using REPLACE or DELETE operations targeted strictly at the divergent keys. These write operations append to the binary log, replicate downstream, and update the replica in natural transaction order.

Finally, rerun pt-table-checksum using the command from Step 2. Verify that DIFFS drops to 0 across every table. Your replica is now an authenticated, zero-loss copy of production.

Share: