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
stickydatabase 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
- What is a clustered index in InnoDB, and why does primary key choice matter so much?
- Why is OFFSET pagination slow on large tables, and what is keyset pagination?
- How do you read EXPLAIN output in MySQL?
- Why might MySQL not use an index you created?
- What are the transaction isolation levels, and which does InnoDB use by default?
- How does a composite index work, and what is the leftmost-prefix rule?
- What causes deadlocks in MySQL, and how do you handle them?
- What are gap locks and next-key locks, and why do they surprise developers?