Replication Lag: When Users Can't See What They Just Wrote

The ticket that landed on the support line read: "The customer defines a geographic zone, clicks save, and the list comes back empty. When they refresh the page, the zone shows up. Thinking the system had lost their data, the customer defined the same zone three times, now there are three copies in the list, and they're rightly annoyed." The support team handed it to us as a "UI bug." From the user's point of view, that's exactly what it was. But the UI was entirely innocent.

In our architecture at Yerlem, we used two read replicas to take read traffic off the primary database. Writes went to the master, list queries went to the replicas. Elegant on paper; in practice, the elegance ends the moment a user can't read the data they just wrote.

Three Suspects That Turned Out Innocent

Our first hypothesis was frontend caching; we figured the list component was showing stale state. We spent two days going through network logs: no, the request really was reaching the server, and the server really was returning an empty list. The second hypothesis was the query cache in the API layer; we turned it off, and the bug persisted. The third was that we were reading before the transaction had been committed; we read the code line by line, and the commit was right where it belonged.

Watching all three hypotheses collapse was demoralizing, but it wasn't wasted effort; each one definitively ruled out a possibility, and we were left with a single common observation: the bug never happened in development, only in production. And the most obvious architectural difference between the two environments was the read replicas — development had a single database. Once suspicion turned there, confirming it took minutes.

The monitoring graph told us the truth. When we overlaid the timestamps of the bug reports on the replication lag metric, the match was perfect: every single complaint clustered in the minutes when replica lag exceeded 3 seconds. For most of the day, lag stayed under 200 milliseconds; but during reporting hours and bulk delete jobs, it climbed to 8-12 seconds. The user would hit save, the write would land on the master, and half a second later the list request would hit a replica that hadn't seen that write yet.

The diagnosis also had a side effect: duplicate records. Because users assumed their save "didn't go through" and saved the same zone over and over, hundreds of duplicate zones had piled up in the database. Cleaning them up became a small project in its own right — which copy was the real one, which was junk, and which one were the alert definitions attached to? And that taught us a second lesson: consistency lag doesn't just produce confusion; through user behavior, it also produces data pollution. We added a double-click lock to the form after submission and a unique constraint on the zone name; even with replication fixed, those two defenses are staying in place.

The write lands on the master, the list request goes to a lagging replica, the list comes back empty, and the user saves the same zone again and again.
The complaints clustered in the minutes when replica lag exceeded 3 seconds.

The Sweet Lie of Seconds_Behind_Master

The embarrassing part: we had a lag alert, and it had never fired. That's because we trusted Seconds_Behind_Master in the SHOW SLAVE STATUS output. This metric looks at the timestamp of the event the replica is currently processing; when the SQL thread is idle, or when the IO thread itself is behind, it can misleadingly show 0. In our case, while a single giant DELETE statement ran for 9 seconds on the replica, the metric bounced between zero and nine, and because the alert looked at the average, it stayed silent.

The fix was an old but solid trick: a heartbeat table that the master writes the current timestamp to once per second. Read that value on the replica, subtract it from the current time, and you have a lag measurement with millisecond resolution that doesn't lie. With this measurement, we saw that the minutes when lag exceeded 1 second added up to 23 minutes a day. That also explained why the complaints came in only "now and then."

Where the routing mechanism should live was a decision in its own right. We could have put in a middle layer like ProxySQL and moved the read/write split and the pin-to-master logic there; we'd also seen slick setups that route based on query comments. We chose to stay in the application layer: our connection factory already had two doors, "read" and "write," and the three lines of logic that check the session flag fit there naturally. Adding a new network component means monitoring it too and managing its versions too; with a two-person infrastructure team, we pay the price of every new box ourselves. On a bigger team, I'd probably choose the opposite; the right answer depends on team size.

Seconds_Behind_Master can show a misleading zero, while the heartbeat table gives the real lag with millisecond resolution.
The heartbeat measurement explained why the complaints came only now and then.

Shrinking the Lag: Chasing the Causes

We found two major sources of lag. The first was the single-statement DELETEs in the cleanup jobs that ran at night and at noon; deleting 2 million rows in one statement kept the single-threaded replica SQL thread busy for minutes. We split them into chunks of 5,000 rows with short pauses in between; the longest single operation on the replica dropped below 200 milliseconds. The second was that the replicas weren't applying changes in parallel; using slave_parallel_workers and LOGICAL_CLOCK, we enabled parallelism while preserving commit order. Together, the two changes brought peak lag down from 12 seconds to 800 milliseconds.

The switch to parallel replication wasn't entirely smooth either; I'll mention it so the picture is complete. When we first turned it on, one of the replicas threw a recurring deadlock error all night; the cause was an old batch update job in the application, written in a pattern that didn't play well with parallelism in terms of commit order. Until we reworked the job, we got by with parallelism on that replica reduced to 4 workers. Replication settings aren't knobs you turn in isolation; they're part of a whole that has to be thought through together with your application's write patterns.

Living With Lag That Never Hits Zero

But here's the real lesson: replication lag can be reduced, not eliminated. As long as you use asynchronous replication, the "I wrote it but can't read it" window exists by the laws of physics. So we added a read-your-writes guarantee to the application layer. Our method was modest: when a user performed a write, we put a short-lived flag on their session and routed that user's read queries to the master for the next 3 seconds. Less than 2 percent of the traffic shifted to the master; in return, the "I saved it and it vanished" complaint never came in again. There are more elegant approaches, such as using GTID-based wait functions to wait for the replica to reach a specific point. We picked the simple one because we wanted to spend our error budget on visibility, not on complexity.

We used the occasion to overhaul our failover scenario as well, because lag isn't just a read consistency issue; in a disaster, it's a data loss issue. If the most up-to-date replica is 8 seconds behind when the master goes down, the promoted replica will never have seen those 8 seconds of writes. The heartbeat-based measurement paid off here too: our failover script now checks the candidates' lag before promotion and won't promote a candidate that is more than half a second behind without first applying the rest of the binlog. We also evaluated semi-sync replication; we measured the cost it adds to write latency and put enabling it for critical tables on next quarter's agenda. Once the lag problem became visible, every decision around it could be made more intelligently; the real danger was that silent period when the metric was lying.

A read-your-writes guarantee, the small share of traffic that goes to the master, a lag check at failover, and a semi-sync evaluation make it possible to live with lag.
Once lag becomes visible, the decisions around it get smarter.

There was also a subtle decision that touched the product side. Not every screen needs the same consistency: a zone the user just defined has to show up in the list instantly; whether the "total vehicle count" gauge on the admin dashboard is 5 seconds old, on the other hand, nobody cares. Classifying screens this way and routing only the ones that need it to the master is the only sustainable way to get consistency without throwing the replicas away. Consistency isn't an infrastructure setting; it's a product decision made screen by screen, and those three duplicate zone records taught us that. If you have a similar story of data that was "thought to be lost," write to me; I enjoy walking through the diagnostic steps together.