Video in progress
You routed reads to a read replica to cut the load. What "stale data" bugs show up, and which queries do you keep on the primary?
Replication is asynchronous and the replica lags by milliseconds to seconds. A user doesn't see what they just saved, and "check, then write" logic makes wrong decisions. Checks before a write, reads after a write, and everything involving money stay on the primary.
📖 Answer
The typical setup in Spring is AbstractRoutingDataSource routing on @Transactional(readOnly = true): read-only transactions go to the replica, the rest to the primary.
Where bugs show up:
- Read-your-writes.
POST /profilewrote to the primary, the frontend immediately doesGET /profile, and the replica still has the old name. The user thinks "it wasn't saved" and clicks again. - Check, then write.
if (repo.findByEmail(email).isEmpty()) repo.save(...): the check runs on the replica, the write on the primary. If the replica is behind, a duplicate gets created (when there is no unique constraint). - Reading after an event. A consumer that received an
OrderPaidevent asks for the order, andorder-servicereads from the replica and says "not paid yet". - Pagination. If two requests land on two replicas with different lag, the list jumps around.
What you can do:
- every read tied to a write (validation, "I wrote it, now I return it") goes to the primary, in one transaction;
- for a short time after a user writes (say 5 seconds), route their requests to the primary, keeping the "last write time" in the session or a cookie;
- carry enough data in events so the consumer doesn't have to query again; or attach the version from the event to the request and fall back to the primary if the replica is older;
- track replica lag as a metric (
replay_laginpg_stat_replication) and temporarily send reads back to the primary when it goes over a threshold.
Another trap: routing by readOnly often doesn't work without LazyConnectionDataSourceProxy. The connection is acquired before the transaction attributes are known, and everything goes to the primary.
A replica is cheap read capacity, but it is "the database at a different point in time". For every query, ask "what happens if the data here is a few seconds old?"
Sign up to mark studied questions and save your progress.