Quick revision
The short answer
Routing every readOnly = true transaction to a replica automatically is risky, because replicas lag behind the primary and some reads must see the writes that just happened. I would set rules: each use case declares whether it tolerates stale data, lag is monitored with automatic fallback to the primary above a threshold, replica pools are sized and tested separately, and hot queries are first considered for caching or read models, which may remove more load than replicas do.
What to remember
In this answer, we saw that routing every read-only transaction to replicas silently changes reads that need current data, such as the page after a write or the check before a payment. The rules that make replicas safe are opt-in routing per use case, lag monitoring with a bounded fallback to the primary, separately sized and tested pools, and a check of whether caching or read models would remove the load more cheaply.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Routing every readOnly = true transaction to a replica automatically is risky, because replicas lag behind the primary and some reads must see the writes that just happened. I would set rules: each use case declares whether it tolerates stale data, lag is monitored with automatic fallback to the primary above a threshold, replica pools are sized and tested separately, and hot queries are first considered for caching or read models, which may remove more load than replicas do.
Background to this question
An overloaded primary is an urgent problem, and replicas look like a quick fix because the code change is small. A senior engineer is expected to see that the change also changes the meaning of every read in the system: from now on, some reads are allowed to be slightly in the past. In this answer, we will see why that matters, which rules keep it safe, how to monitor and fall back, and why caching or read models may be the better first step for the hottest queries.
1What Changes When Reads Move to a Replica
A replica receives the primary's changes through asynchronous replication. Under normal load it is a few milliseconds behind; during a bulk update, a vacuum, or a network hiccup it can be seconds or minutes behind. Every read served by the replica sees the database as it was at that moment in the past.
The readOnly = true flag on @Transactional was written by developers to say this method does not write. It was never a statement that the method can tolerate old data. Many read-only methods were written assuming they would see the latest committed state, because until now they always did. Routing them all automatically turns that assumption into a bug wherever it was relied on.
2Where Stale Reads Break Things
The classic case is read-your-writes. A user places an order, the API commits it on the primary, and the client immediately calls GET /orders/42. That read-only call hits a replica 300 milliseconds behind and returns 404. The user thinks the order failed and places it again.
Less visible cases are worse. A payment service checks whether an invoice is already paid in a read-only transaction before charging; with stale data it may charge twice. A stock check before reserving may approve an item that sold out a second ago. These reads are read-only, but their result feeds a decision that leads to a write, so they need current data.
| Use case | Tolerates staleness? | Route |
|---|---|---|
| Product catalogue, search results | Yes, seconds are fine | Replica |
| Reports and dashboards | Yes, minutes are often fine | Replica or warehouse |
| Order page right after checkout | No, must see own write | Primary |
| Check before charging or reserving | No, feeds a write decision | Primary, inside the write transaction |
| Account balance shown to the user | Usually no | Primary or a cache updated on write |
3Rule 1: Opt In Per Use Case
So the first rule is that routing is opt-in. Instead of routing every readOnly = true transaction, teams mark the use cases that may read stale data, for example with a custom annotation such as @ReplicaRead, or a named transaction attribute that the routing data source checks. Everything else keeps going to the primary. This costs a review of the read paths, but each team decides for its own endpoints, and the default stays correct.
Teams should start with the endpoints that produce the most load. Often five or ten queries make up most of the read traffic, so marking those gives most of the benefit while the rest of the system stays unchanged.
4Rule 2: Monitor Lag and Fall Back
Lag must be measured, not assumed. On PostgreSQL, the primary shows replay_lag per replica in pg_stat_replication, and on the replica we can compute now() - pg_last_xact_replay_timestamp(). We export this as a metric, alert on it, and use it in the router: if lag exceeds a threshold, say 2 seconds, reads that would go to the replica go to the primary instead until lag recovers.
There is a catch: falling back sends all that read traffic back to the primary that was overloaded in the first place. So the fallback needs a limit too, such as a circuit breaker or a reduced feature set, and the capacity plan must say what the primary can absorb when a replica is lost.
- Request arrivesUse case is marked as replica-safe or not
- Marked replica-safe?YesGo to lag checkNoUse the primary
- Replica lag under 2 seconds?YesUse the replicaNoFall back to the primary
- Primary under its fallback limit?YesServe from the primaryNoShed or degrade the request
4 steps in order. Play them, or step through them one at a time.
Lag and primary capacity are both checked before choosing.
5Rule 3: Consider Caching and Read Models First
Replicas copy the whole database and serve the same queries at the same cost. If the hot reads are the same product page fetched 50,000 times a minute, a cache in front of it removes that load almost completely, while a replica only moves it. If the expensive reads are complex joins for a dashboard, a read model, a table or view precomputed for that query and updated by events or a scheduled job, can make each query a hundred times cheaper.
So the proposal should start with the top queries by total time from pg_stat_statements. For each one, we ask whether a cache, a read model, a better index or a replica is the cheapest way to remove its load. Replicas are often part of the answer, but rarely the whole answer.
6Rule 4: Size Pools Separately and Test Failover
Replica and primary need their own connection pools, sized from their own traffic, with their own metrics, so a slow replica does not hold connections that writes need. Finally, we test the bad days on purpose: stop a replica, add artificial lag, promote a replica after a primary failure, and confirm that read-your-writes flows still behave and the primary survives the fallback.
7Follow-up questions
Is synchronous replication a fix for staleness?
Synchronous replication makes the primary wait for a replica to confirm a commit. With PostgreSQL's remote_apply setting the change is visible on that replica when the commit returns, which gives read-your-writes. The cost is higher write latency and a primary that stalls if the synchronous replica is slow or down, so it is a trade-off rather than a free fix.
How can a client get read-your-writes without always using the primary?
One technique is to record the primary's log position after a write, for example the WAL position from pg_current_wal_lsn(), and send it with the user's next requests. The router then uses a replica only if its replayed position has passed that value, and the primary otherwise. Simpler versions route a user to the primary for a fixed few seconds after any write they make.
What would you report back to the teams who proposed the change?
That the idea is sound but the automatic routing is not. I would propose a small pilot with the top read endpoints marked replica-safe, lag monitoring and fallback in place, a parallel look at caching for the hottest queries, and a measured result after two weeks before extending it.
8Conclusion
In this answer, we saw that routing every read-only transaction to replicas silently changes reads that need current data, such as the page after a write or the check before a payment. The rules that make replicas safe are opt-in routing per use case, lag monitoring with a bounded fallback to the primary, separately sized and tested pools, and a check of whether caching or read models would remove the load more cheaply.
Open with
I would support using replicas, but not by routing every readOnly true transaction automatically. That flag says the method does not write; it does not say the method can accept old data.
Then, if they want more
Replicas lag, sometimes by seconds, so a user who just created an order may get a 404 on the next page, and a check before charging could see an invoice as unpaid. So my first rule is opt-in: each team marks the use cases that tolerate staleness, like catalogue and reports, and everything else stays on the primary.
Second, we measure lag, from pg_stat_replication or the replay timestamp on the replica, and the router falls back to the primary above a threshold such as two seconds, with a limit so the fallback does not overload the primary again. Third, replica pools are sized separately and we test replica loss, lag and failover before relying on it.
And before all of this I would look at the top queries in pg_stat_statements, because often a cache or a precomputed read model removes far more load than a replica, which only moves the same query to another machine.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Your read traffic is ten times write traffic and the primary database is overloaded....": https://scrivio-interview-library.netlify.app/databases/transactions/2367c31a4b/