Video in progress

Strong Middle 🧩 Microservices

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:

  1. Read-your-writes. POST /profile wrote to the primary, the frontend immediately does GET /profile, and the replica still has the old name. The user thinks "it wasn't saved" and clicks again.
  2. 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).
  3. Reading after an event. A consumer that received an OrderPaid event asks for the order, and order-service reads from the replica and says "not paid yet".
  4. 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_lag in pg_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?"