A replica does the same work the source did. It receives the changed rows, applies them with four parallel workers by default, and runs on the same kind of server. So when it falls behind, the reflex is to look at the link between them or at the replica’s disks. In my test runs, that reflex would have been wrong every time. With the source and replica on the same laptop, 0.1 ms apart, 64,000 single-row inserts from 16 sessions finished on the source in 26 seconds and on the replica in 92 (the median of three runs). One UPDATE that took 0.27 seconds on the source took the replica 82. An ALTER TABLE that finished in 17 milliseconds held up every commit behind it for 28 seconds.
The cost of lag is concrete: reads routed to the replica return old data, and a failover has to wait for the replica to finish applying before it can promote it (Part 4 measures that wait). In November 2020, a surge of token requests at GitHub caused “abnormal levels of replication lag within one of our MySQL clusters,” and the requests that read from the lagging replicas failed (GitHub’s availability report, January 2021). Part 1 covered how the binary log, the receiver and the applier work. This part takes each cause of lag in turn, reproduces it, and measures what fixes it.
Reading lag before chasing it
The number everyone watches is Seconds_Behind_Source from SHOW REPLICA STATUS, and it measures something narrower than its name. It is the age of the transaction the applier is working on: how long ago that transaction committed on the source. The manual adds that it compares the applier with the receiver, not with the source, which makes it “useful only for fast networks” (manual), since a receiver that is itself behind leaves it at 0.
To see what that means under load, I ran 16 sessions inserting rows on the source for 20 seconds and sampled a replica every half second. When the writes stopped, the replica was 43,113 transactions behind and Seconds_Behind_Source read 16. It took another 68 seconds to catch up, and the figure kept climbing the whole time, to 67, because each transaction the applier reached had been waiting longer than the one before it.
So the figure answers “how stale is the newest row a reader can see” and says nothing about how long the backlog will take to clear. For that, compare Retrieved_Gtid_Set with Executed_Gtid_Set, or read performance_schema.replication_applier_status_by_worker, which reports each worker’s last applied transaction with its original commit time on the source. Many teams skip both and write a timestamp into a heartbeat table on the source every second (pt-heartbeat does this), then read it on the replica: it measures exactly what a reader experiences, including time spent in the receiver.
The shape of the writes
The setup for everything below: MySQL 8.4.13 in Docker, 1 CPU and 900 MB per server, one source and two replicas on the same host, replicas at default settings (4 applier workers, sync_binlog = 1, innodb_flush_log_at_trx_commit = 1) unless a row says otherwise.
The first test wrote the same 64,000 rows from 16 sessions, varying only how many rows went into each transaction:
| Rows per transaction | Transactions | Source finished | Replica finished | Replica behind at worst |
|---|---|---|---|---|
| 1 | 64,000 | 24–31 s | 90–98 s | 66–67 s |
| 10 | 6,400 | 3.9 s | 11.8 s | 8.0 s |
| 100 | 640 | 1.1 s | 2.1–2.4 s | 1.3–1.5 s |
| 1,000 | 64 | 0.6 s | 0.8 s | 0.35 s |
Rows of 1 and 100: three runs each, range shown. Rows of 10 and 1,000: one run.
The source has an advantage the replica does not get back. Sixteen sessions committing at once share binary log flushes on the source (group commit), so sixteen commits can cost one disk sync. The replica applies them with four workers and commits each one again in its own binary log and redo log, in the source’s order, and most of the per-transaction cost is in that commit, not in the row. A single session writing one row at a time did not lag at all: 10,000 commits took 33.7 seconds on the source and the replica was never more than 0.13 seconds behind. It is concurrency in small transactions that the replica cannot match.
So batch. Then the other direction bites, because MySQL writes a transaction to the binary log only when it commits, and the replica cannot start on it before that. One session wrote 1,000,000 rows in batches of different sizes, while a second session committed one small row every 100 ms and measured how long the replica took to show it:
| Rows per transaction | Source finished | Replica finished | Small commit visible on the replica: median / worst |
|---|---|---|---|
| 100 | 63.8 s | 63.8 s | 7 ms / 139 ms |
| 1,000 | 9.8 s | 9.8 s | 9 ms / 56 ms |
| 10,000 | 5.8 s | 5.8 s | 17 ms / 167 ms |
| 100,000 | 4.5 s | 4.8 s | 16 ms / 464 ms |
| 1,000,000 | 4.0 s | 9.2 s | 9 ms / 4,925 ms |
At a million rows in one transaction, the replica could not begin until the source committed, then spent five seconds applying it, and the small commit that arrived just after it waited behind it for 4.9 seconds. Anything that reads from that replica sees the whole table frozen at its state from before the batch for the duration. A single UPDATE of every row in a 1,000,000-row table showed the same thing in Part 1: 1.8 seconds on the source, visible on the replica 3.4 to 3.5 seconds after COMMIT. A batch job that runs for an hour inside one transaction puts every replica an hour behind at the moment it finishes.
The range that worked here was 1,000 to 10,000 rows per transaction, and the exact numbers depend on row size. The tools built for this (pt-archiver, gh-ost, the chunked delete loops in most migration frameworks) also pause between chunks when replica lag rises.
Work the replica does differently
Row-based replication ships the changed rows, and the replica has to find each one before it can change it. With a primary key that is an index lookup. Without one, the manual says the applier builds a hash table from the rows in the event, then “iterates over all the records in the target table, using the selected index if it found one, or else performing a full table scan” (manual). The source found its rows with one scan for the whole statement; the replica scans once per row event, and a large UPDATE is many events.
One UPDATE changed 50,000 rows spread across the table:
| Table | Source | Replica showed the change after |
|---|---|---|
| 200,000 rows, primary key | 0.13–0.15 s | 0.18–0.26 s |
| 200,000 rows, no primary key | 0.13–0.18 s | 17.1–18.3 s |
| 1,000,000 rows, no primary key | 0.27 s | 82.5 s |
| 200,000 rows, generated invisible primary key | 0.14–0.19 s | 0.19–0.30 s |
Three runs each, except the 1,000,000-row table (one run).
The replica’s time grew with the size of the table, about five times longer for a five times larger table, while the source’s barely moved. My first version of this test updated the first 50,000 rows in the table’s physical order, and the replica took only 4.9 seconds on both table sizes, because a scan that finds all its rows early can stop early. Production tables rarely line up that neatly, so the interleaved figures are the ones to expect. The fix costs nothing at the application level: sql_generate_invisible_primary_key = ON (8.0.30 and later) adds a hidden auto-increment key to any table created without one, which is the bottom row, and sql_require_primary_key = ON refuses to create such tables at all.
Schema changes are the other kind of work the replica cannot parallelize. Online DDL lets the source keep taking writes while it rebuilds a table, but the ALTER reaches the replica as one statement, after it finishes on the source, and the replica’s applier runs it before anything that committed later:
| Statement on a 2,000,000-row table | Source | Small commits held on the replica, worst |
|---|---|---|
ALTER TABLE ... ENGINE=InnoDB (rebuild, online) | 5.5 s | 4.7 s |
ADD INDEX (online) | 2.8 s | 2.4 s |
ADD COLUMN ... ALGORITHM=INSTANT | 0.03 s | 0.03 s |
A rebuild that takes an hour on a large table puts the replica an hour behind as soon as the source finishes it, which is why gh-ost and pt-online-schema-change exist: they copy the table in small, throttled transactions, and the replica applies those like any other writes. INSTANT is free when the change qualifies.
The replica applies rows, not your queries
When a slow write on the source lines up with lag, the natural move is to tune that write: add the index its WHERE needs, rewrite the subquery that picks the rows. With row-based replication, which every test here uses, the replica never runs that WHERE. It receives the rows the statement changed and applies each one by primary key (Part 1 showed what the event holds). These tests ran on one source and one replica, set up as above. Two UPDATEs on a 2,000,000-row table changed the same 11,266 rows, one choosing them with an aggregate over a million groups and the other with a primary-key range:
| How the rows were chosen | Source | Replica, after the source committed | Binary log written |
|---|---|---|---|
| Aggregate over 1,000,000 groups | 4.6–4.9 s | 0.04–0.11 s | 2,965,045 bytes |
| Primary-key range | 0.07–0.08 s | 0.04 s | 2,965,045 bytes |
Three runs each.
The two binary logs were the same size to the byte, and the replica spent the same time on both. Tuning that WHERE would have sped up the source and changed nothing on the replica. It works in the other direction too: an UPDATE whose SET leaves a row as it was sends the replica nothing. One that matched 2,132 rows and changed none added 0 bytes to the binary log, and the same statement with a new value added 561,317. A batch job that sets updated_at = NOW() on every row it visits turns those free no-ops into rows the replica has to apply. (With binlog_format = STATEMENT or MIXED, the replica does run the statement, and this section reverses.)
So what the replica pays for is rows changed, and the source’s statement digests show which statements change the most:
| |
How much each of those rows costs depends on the indexes it has to update. An index is a trade: queries that use it read faster, and every write pays to keep it current, because every server updates every secondary index for each row inserted or deleted and for each update that changes an indexed column. An index no query reads keeps the cost and drops the benefit, and the replica pays that cost a second time after the source. To see how large it gets, the same 64,000-row burst as above (10 rows per transaction, 16 sessions) went into a 2,000,000-row table carrying indexes that no query used, on random-valued columns:
| Secondary indexes | Their size | Source finished | Replica finished | Replica behind at worst | Replica’s disk reads |
|---|---|---|---|---|---|
| 0 | 0 MB | 2.0–2.5 s | 6.9–8.6 s | 4.6–6.1 s | 3 |
| 1 | 42 MB | 2.9–3.0 s | 10.1–10.7 s | 6.9–7.5 s | 148 |
| 3 | 125 MB | 16.2–20.5 s | 29.7–33.9 s | 13.6–14.2 s | 99,363 |
| 5 | 208 MB | 36.4–39.1 s | 49.1–49.4 s | 10.2–12.7 s | 227,531 |
Three runs each, the second pass in reverse order, every run after a restart and a short warm-up. Disk reads are the replica’s Innodb_buffer_pool_reads during the burst, from the third run. The table’s rows take 307 MB; the buffer pool is the default 128 MB.
None of that time made any read faster, since nothing read those indexes. How much it cost depended less on the count than on memory. One 42 MB index cost about two seconds. Three cost more than twenty, and the last column shows why: once the indexes stopped fitting in memory, inserts into a random-valued index kept landing on pages that had to be read from disk first, 148 reads with one index and 99,363 with three. MySQL 8.4 also switched off the change buffer by default (innodb_change_buffering = none), which used to defer exactly those writes. Lag in seconds peaked at three indexes and fell at five only because the source slowed down as well. The number that kept growing is when the replica had the rows: 8 seconds on average, then 49.
sys.schema_unused_indexes lists indexes with no reads since the server last started. Check it on the source and on each replica before dropping anything, because an index the source never reads may be the one a reporting replica depends on, and a DROP INDEX on the source replicates to all of them. Making the index invisible first (ALTER TABLE ... ALTER INDEX ... INVISIBLE) stops the optimizer from using it while keeping it maintained, so a query that needed it shows up before the index is gone; the write cost only goes away with the drop.
One cause I expected to find and did not: a hot row. Sixteen sessions sending 64,000 single-row updates to one counter row took the source 154–157 seconds and the replica 164–169, never more than 17 seconds behind. Spread across 10,000 rows, the same updates finished on the source in 15–16 seconds and on the replica in 58–61, up to 44 seconds behind. The replica did apply the hot-row updates one at a time, as writesets require for transactions touching the same row, but the source had already done the same, with each session waiting on the row lock until the one before it committed. A hot row caps how fast the source can write, and the replica keeps up with that rate.
What the replica is doing at the same time
A replica is also a server answering queries, and those queries compete with the applier for the same CPU, disk and locks. I repeated the 16-session write burst (64,000 rows, 10 per transaction), first on an idle replica and then while sysbench ran 16 threads of read-only queries against it, about 31,000 to 34,000 queries a second:
| Replica load | Replica finished | Behind at worst |
|---|---|---|
| Idle | 11.1–12.0 s | 7.6–8.8 s |
| 16 threads of reads | 39.5–40.0 s | 37.0–37.2 s |
Two runs each. The read load ran for 40 seconds.
With reads running, the replica applied almost nothing: it was 62,840 of 64,000 rows behind at the worst point and caught up only once the read load stopped. On one CPU that is an extreme case; on real hardware the applier gets a share instead of almost none, but the share shrinks as reads grow, and a replica added to absorb reporting queries is the one most likely to lag. That leaves three choices, none of which I ran. Reporting can get its own replica, so the one that would be promoted stays lightly loaded, which costs another server. Readers on a shared replica can be capped, with a limit on report connections or MAX_EXECUTION_TIME on their queries, so that reports queue or fail instead of the applier. Or the replica can be given more CPU than the source, which pays for the reads in hardware.
Locks do it without any load at all. I opened a transaction on the replica, ran one SELECT against a table and left the transaction open, the way an idle reporting connection or a forgotten client session does. Then I ran an instant ALTER TABLE ... ADD COLUMN on that table on the source, which took 0.017 seconds there. On the replica, the processlist showed:
| |
The ALTER needed an exclusive metadata lock that the open transaction’s SELECT was holding, and every transaction committed on the source after the ALTER queued behind it. Small commits waited up to 28 seconds, until the replica’s transaction ended after 30. The stalled replica post describes another way one idle connection on a replica caused three days of lag, through InnoDB purge rather than a metadata lock: its snapshot kept purge from removing old row versions, the history list grew past a billion, and the applier slowed walking them (how purge and the history list work). Two things keep an idle session from stalling a replica this way, and I ran neither. A short wait_timeout for the accounts that reporting tools and people connect with closes the idle session before it matters, and those clients have to reconnect. Or a check runs before the ALTER goes out on the source: look in each replica’s information_schema.innodb_trx for old open transactions and end them, which rolls back whatever they were doing.
innodb_flush_log_at_trx_commit = 2, InnoDB flushes its redo log about once a second, so an OS crash or power loss drops up to a second of applied transactions. With sync_binlog = 0, the binary log and InnoDB can disagree afterwards, and the replica may need rebuilding before it is safe to promote. It fits one case: a replica hours behind that has to catch up. Keep that replica out of failover while it runs, and set both back to 1 once it has.| Replica setting | Replica finished | Behind at worst |
|---|---|---|
replica_parallel_workers = 1 | 189 s | 166 s |
replica_parallel_workers = 4 (default) | 90–98 s | 66–67 s |
replica_parallel_workers = 16 | 37 s | 9.7 s |
4 workers, sync_binlog = 0, innodb_flush_log_at_trx_commit = 2 | 27 s, with the source | 0 s |
binlog_group_commit_sync_delay = 1000 on the replica | 294 s | 271 s |
binlog_group_commit_sync_delay = 5000 on the replica | 373 s | 350 s |
More workers helped even on one CPU, because most of each worker’s time was spent waiting on disk syncs, not computing. binlog_group_commit_sync_delay is the classic tuning for this, and it belongs on the source. Delaying each binary log flush lets more transactions share it, which before MySQL 8.4 also gave replicas wider groups to apply in parallel. On the replica it is harmful: the workers commit in order, and each group waited out the delay. On the source, in 8.4, it did something else:
Source binlog_group_commit_sync_delay | Source finished | Replica finished | Behind at worst |
|---|---|---|---|
| 0 (default) | 24–31 s | 90–98 s | 66–67 s |
| 1,000 µs | 49.2 s | 102.2 s | 53.1 s |
| 5,000 µs | 55.6 s | 88.0 s | 32.5 s |
The replica finished at about the same time with or without it, and the lag was lower only because the source wrote more slowly. MySQL 8.4 removed binlog_transaction_dependency_tracking and always tracks dependencies by writeset (release notes): two transactions that touched different rows can be applied in parallel regardless of whether they committed in the same group. On 8.0 at its default, the delay was the way to get parallel apply; on 8.4 it is a throttle on the source, which is occasionally what you want, and it should be read as one.
Does semi-sync or Group Replication help?
Semi-synchronous replication makes each commit wait until a replica has received the transaction and written it to its relay log. Received, not applied, so it leaves the applier exactly as far behind as before. With semi-sync on, the 1,000,000-row UPDATE took 0.67 to 1.09 seconds to commit, against 0.18 to 0.34 seconds asynchronously, because the commit now waited for 142.6 MB of binary log to cross to the replica, and the replica still showed the change 3.1 to 4.7 seconds after COMMIT returned. Semi-sync protects commits against losing the source. It does nothing for lag.
Group Replication is the one setup that can bound lag, through flow control: when a member’s queue of transactions waiting to be applied passes a threshold, the group throttles writes on the primary. The default threshold, group_replication_flow_control_applier_threshold = 25000, is high enough that the 20-second burst from Part 1 never reached it. Lowering it on all three members:
| Flow control threshold (applier and certifier) | Primary commits per second | Secondary behind at worst | Caught up after writes stopped |
|---|---|---|---|
| 25,000 (default) | 1,720 | 19,605 transactions | 26.3 s |
| 1,000 | 752 | 2,518 transactions | 0.8 s |
| 100 | 260 | 781 transactions | 0.3 s |
16 sessions inserting for 20 seconds, three members on one host, default consistency.
The lag shrank because the primary slowed down to the speed of the slowest member, which is all flow control can do. Group Replication also refused the large transaction outright: an UPDATE of 1,000,000 wider rows produced 351 MB of changes and was rejected for exceeding group_replication_transaction_size_limit, 150,000,000 bytes by default. Part 3 shows the error and what happens to the session.
What to check first
A replica that is behind on a quiet source has a cause on its own side: look for long-running or idle transactions (information_schema.innodb_trx), a history list length that keeps climbing (trx_rseg_history_len in information_schema.innodb_metrics), threads in “Waiting for table metadata lock”, and the read load. A replica behind on a busy source points at the writes: the commit rate (Com_commit per second, compared with what the replica sustains), batch jobs and their transaction size, a recent ALTER, and tables without a primary key, which this query lists:
| |
Then the replica’s settings: replica_parallel_workers first. Relaxed durability cleared the lag completely, but only as the emergency measure in the warning above.
Settings raise the ceiling, and the workload is what usually hits it: the statements changing the most rows (the digest query above), the indexes on the busiest tables that nothing reads, and the reports running on the replica. No setting takes that cost away, which Part I of It’s Almost Always the Queries argues for hardware too.
Part 3 covers the other way a replica stops keeping up, which is stopping altogether: errant writes, purged binary logs and the errors they produce.
