Video in progress
How do you use read replicas with Hibernate, and how do you prevent the errors caused by replication lag?
With AbstractRoutingDataSource + LazyConnectionDataSourceProxy I send read-only transactions to the replica and the rest to the primary. For "I wrote it but I can't see it" cases caused by lag, I keep reads right after a write on the primary and use the L2 cache carefully.
📖 Answer
The main trap in routing is when the connection gets acquired. Spring takes a connection when the transaction starts, and the readOnly flag is set after that. LazyConnectionDataSourceProxy delays acquiring the connection until the first SQL statement, so the router makes the right decision.
class ReplicaRouting extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? "replica" : "primary";
}
}
// give the EntityManagerFactory: new LazyConnectionDataSourceProxy(routing)
Since Spring 6.1, LazyConnectionDataSourceProxy has setReadOnlyDataSource(), so you can do it without writing a separate router.
Lag problems and fixes:
- a user saves their profile and immediately reopens it, but the replica is still old. The fix: for N seconds after a write, route that user's requests to the primary (a session/cookie marker), or return the response from the write transaction itself;
- if a writing method is called from inside a
readOnlymethod, it tries to write to the replica and fails. You need clear transaction boundaries; - the L2 cache is updated after a write on the primary, but a stale value read from the replica can land in the cache again. If you use L2 with replicas, keep the TTL short.
Monitoring: a replica lag metric (pg_last_xact_replay_timestamp on PostgreSQL), and if lag exceeds a threshold, temporarily switching routing to the primary. Important reads like money, stock and authorization I always keep on the primary.
Sign up to mark studied questions and save your progress.