Video in progress
In a leader-follower setup, where do write and read requests go?
All writes go only to the leader (primary), which passes the changes on to the followers. Reads can also be served from followers, but you have to keep in mind that they can be a little behind.
📖 Answer
In Spring this is often done with two DataSources and routing: methods with @Transactional(readOnly = true) go to the replica, the rest to the primary.
public class RoutingDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return TransactionSynchronizationManager.isCurrentTransactionReadOnly()
? "replica" : "primary";
}
}
The key rule: write in only one place. If you write to two servers, they can accept conflicting changes, and you have to decide whose is correct — that is much more complicated (multi-leader).
Which reads should not go to a replica: anywhere the user has to see what they just changed. For example, the "Your order status" page right after a payment — read it from the primary.
Sign up to mark studied questions and save your progress.