MySQL interview question · Most asked

How do you deal with replication lag when reading from replicas?

Summary

Route reads that must see the user's own recent writes to the primary (read-your-writes), monitor lag, and only use replicas for reads that tolerate staleness. Reduce lag with parallel appliers, smaller transactions and adequate replica hardware.

Longer Answer

Symptoms: a user saves a profile, the next page reads from a replica and shows old data. Strategies:

  • Sticky primary after write: for a few seconds after a write (or for the rest of the request), read from the primary. Laravel's sticky database option does this per request.
  • GTID-based waits: wait until the replica has applied the GTID of the write (WAIT_FOR_EXECUTED_GTID_SET) before reading.
  • Lag-aware routing: proxies such as ProxySQL stop sending reads to replicas that are too far behind.

Causes of lag: huge transactions (a single DELETE of millions of rows replays as one unit), single-threaded applying, DDL, and weaker replica hardware.

Key Points

  • Read-your-writes from the primary.
  • Lag-aware routing.
  • Avoid huge transactions; parallel appliers.
  • Monitor lag.

Deep dive: Scaling Databases & Data Consistency

More most-asked MySQL questions

← All MySQL questions