Course contentsShow
← Databases & SQL
Lesson 1020 of 1,9539. MySQL and MariaDB EcosystemsFree lesson

Asynchronous Replication Latency

Measure and mitigate lag between master and slave nodes in a replication stream.

In this lesson, you will learn how to identify and address the delays that occur when a replica node falls behind its primary master node in an asynchronous replication setup.

The Mechanics of Lag

In asynchronous replication, the primary node commits transactions to its binary log and continues processing without waiting for the replica to apply them. While this is great for performance, it creates a "replication gap." If the write volume on the primary exceeds the sequential execution capacity of the replica’s SQL thread, latency builds up.

Latency is typically measured by Seconds_Behind_Master. You can check this by running:

SHOW SLAVE STATUS\G

Look for the Seconds_Behind_Master field. If this value is greater than 0, your replica is currently lagging. Note that if the IO thread is disconnected, this value may appear as NULL.

Mitigating the Lag

When you identify persistent lag, consider these common mitigation strategies:

  1. Reduce Transaction Complexity: Long-running transactions on the primary create "batch" delays on the replica. Breaking large updates into smaller chunks allows the replica to commit more frequently, preventing spikes in lag.
  2. Optimize the Replica's Hardware: Since the replica must perform identical writes to disk, ensure its IO subsystem (IOPS) is at least as fast as the primary.
  3. Use Multi-Threaded Replication: In older setups, a single SQL thread processes the relay log. By enabling slave_parallel_workers (or replica_parallel_workers in newer versions), you allow the replica to execute non-conflicting transactions in parallel, significantly reducing the bottleneck.
  4. Audit Indexes: Ensure that the tables being updated on the replica have the exact same indexes as the primary. If a query on the primary uses an index but the replica is missing it, the replica will perform a full table scan, causing massive latency.

By monitoring the Seconds_Behind_Master and tuning the replica's ability to process parallel events, you keep your read-only nodes fresh and reliable for application traffic.

Key Takeaway: Replication lag occurs when the replica’s SQL thread cannot keep pace with the primary’s binary log; mitigate this by optimizing replica IO, adding necessary indexes, and enabling multi-threaded replication.