MySQL GTID-Based Replication Setup Guide: Automating Failover and Preventing Data Drift

MySQL tutorial - IT technology blog
MySQL tutorial - IT technology blog

Real-World Incident: A 2 AM Binary Log Offset Disaster

At 2:15 AM, PagerDuty alerts went off relentlessly. The Primary (Master) node suffered a hardware failure on the virtualization cluster and abruptly lost power. On the Grafana dashboard, the HTTP 500 error rate spiked to 100% in less than 30 seconds.

The immediate objective was clear: promote Replica 1 to the new Primary to restore the service. The problem was that our database cluster was still running traditional File/Position-based replication. Synchronization relied entirely on log file names like mysql-bin.000142 and byte offsets like 7849201.

Trouble struck when reconnecting Replica 2 to the newly promoted node. Because the old Master had crashed abruptly, Replica 2 was left stranded. I had to strain my eyes parsing logs with mysqlbinlog to identify the last transaction position. Off by just a few dozen bytes, Replica 2 immediately threw a duplicate key error:

Last_SQL_Errno: 1062
Last_SQL_Error: Could not execute Write_rows event on table core_orders; Duplicate entry '892011' for key 'PRIMARY', Error_code: 1062; handler error HA_ERR_FOUND_DUPP_KEY; the event's master log mysql-bin.000012, end_log_pos 45102

At the time, the database held around 50GB of data with over 400,000 active orders. The offset error caused the two nodes to drift by nearly 1,200 transactions. The team endured over 45 minutes of downtime just to reconcile and backfill data. After that painful lesson, we decided to abandon File/Position replication entirely.

Why Position-Based Replication Breaks Easily During Failover

The traditional model forces replicas to track the primary using a pair of values: the binlog file name and byte offset. In practice, this approach reveals three fatal weaknesses:

  • Coordinates are strictly local: For the exact same INSERT statement, it might sit in mysql-bin.000142 at position 5021 on the Primary, but end up in mysql-bin.000005 at offset 1280 in the Replica’s binlog. These coordinates are completely independent and cannot be converted automatically.
  • Pressure of manual calculation: Pointing a replica to a new node requires engineers to inspect binlogs and manually calculate equivalent coordinates. Under the pressure of an active outage in the middle of the night, human calculation error is almost inevitable.
  • Risk of compromising data integrity: Many resort to quick fixes like SET GLOBAL sql_replica_skip_counter = 1. This command blindly skips the failing transaction without inspecting its payload, causing silent data corruption without any warning.

Comparing Recovery Approaches When Topology Breaks

When faced with reconnecting replication after a failure, operations teams typically have three choices:

Approach 1: Manually Hunting Coordinates Using mysqlbinlog

Filter transaction timestamps and commit positions directly from the binlog file:

mysqlbinlog --base64-output=DECODE-ROWS -v /var/lib/mysql/mysql-bin.000142 | grep -A 5 -B 5 "892011"

Assessment: Takes 15 to 30 minutes of manual effort. Extremely high risk of typing the wrong offset, significantly extending service downtime.

Approach 2: Dump and Rebuild the Replica from a Snapshot

Stop the replica, then use Percona XtraBackup to pull a fresh copy of the 50GB dataset from the new node.

Assessment: Guarantees 100% data consistency. However, transferring and restoring 50GB over the internal network takes roughly 20 to 35 minutes, exceeding the allowable RTO (Recovery Time Objective) for payment services.

Approach 3: Standardizing with GTID (Recommended)

Every transaction, upon commit, is assigned a cluster-wide unique identifier:

GTID = server_uuid:transaction_id

For example, 3E11FA47-71CA-11E1-9E33-C80AA9429562:23 represents the 23rd transaction generated by the server with that UUID.

The synchronization mechanism becomes completely straightforward. The replica simply announces: “I have received transactions 1 through 50; send me 51 onward.” Both nodes negotiate automatically without requiring human intervention for binlog files or byte offsets.

Configuring GTID-Based Replication in MySQL 8.0

Setting up GTID is an essential prerequisite if you want to integrate automated failover tools like Orchestrator or ProxySQL into production infrastructure.

Step 1: Configure my.cnf on Both Primary and Replica

Open the MySQL configuration file (typically at /etc/mysql/mysql.conf.d/mysqld.cnf or /etc/my.cnf):

[mysqld]
# Unique identifier for each node (Primary = 1, Replica = 2)
server-id = 1

# Enable Binary Log with ROW format
log_bin = /var/log/mysql/mysql-bin.log
binlog_format = ROW
log_replica_updates = ON

# Enforce GTID replication
gtid_mode = ON
enforce_gtid_consistency = ON

Note: Enabling enforce_gtid_consistency = ON prevents non-transaction-safe statements, such as CREATE TABLE ... SELECT or concurrent updates across both InnoDB and MyISAM tables.

Step 2: Create a Dedicated Replication User

Log in to the Primary node and create the replication account:

CREATE USER 'repl_user'@'192.168.1.%' IDENTIFIED WITH caching_sha2_password BY 'UltraSecurePassword#2026';
GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'repl_user'@'192.168.1.%';
FLUSH PRIVILEGES;

Step 3: Start Replication on the Replica with SOURCE_AUTO_POSITION

On the Replica node, you no longer need to worry about log file names or byte offsets. Simply set SOURCE_AUTO_POSITION = 1:

STOP REPLICA;

CHANGE REPLICATION SOURCE TO
  SOURCE_HOST = '192.168.1.10',
  SOURCE_PORT = 3306,
  SOURCE_USER = 'repl_user',
  SOURCE_PASSWORD = 'UltraSecurePassword#2026',
  SOURCE_AUTO_POSITION = 1;

START REPLICA;

Step 4: Verify Replication Status

Run the verification command on the Replica node:

SHOW REPLICA STATUS\G

Check the following four key metrics:

  • Replica_IO_Running: Yes (the thread fetching binlogs from the Primary is running normally)
  • Replica_SQL_Running: Yes (the SQL thread applying events to the storage engine is running normally)
  • Auto_Position: 1 (automatic GTID positioning is enabled)
  • Executed_Gtid_Set: shows the range of successfully applied transactions (e.g., d5c31278-6549-11ed-b5ea-0242ac120002:1-1402)

Failover Procedure When the Primary Fails

When the Primary node unexpectedly crashes, failover takes place in three straightforward steps:

  1. Run STOP REPLICA; on Replica 1 and disable read-only mode to promote it to the new Primary.
  2. Point Replica 2 to the IP address of the new node while keeping SOURCE_AUTO_POSITION = 1 enabled.
  3. Both servers automatically negotiate the missing GTID sets and reconcile data seamlessly. No more data drift or duplicate key crashes.

Migrating to GTID significantly simplifies cluster maintenance. Engineering teams no longer need to spend sleepless nights parsing raw log lines just to re-establish a broken replication stream.

Share: