Video in progress

Senior 🌱 Spring

How do you set up routing read queries to a replica database and writes to the primary in Spring, and what is risky about it?

A routing DataSource picks the replica or the primary based on the transaction's readOnly flag. A LazyConnectionDataSourceProxy goes on top so the connection is acquired after the transaction starts. The main risk is replication lag: a user may not see what they just wrote.

📖 Answer

class ReadWriteRoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        return TransactionSynchronizationManager.isCurrentTransactionReadOnly() ? "replica" : "primary";
    }
}

@Bean @Primary
DataSource dataSource(DataSource primary, DataSource replica) {
    var routing = new ReadWriteRoutingDataSource();
    routing.setTargetDataSources(Map.of("primary", primary, "replica", replica));
    routing.setDefaultTargetDataSource(primary);
    routing.afterPropertiesSet();
    return new LazyConnectionDataSourceProxy(routing); // delays the connection until the first SQL
}

Without LazyConnectionDataSourceProxy, Spring may grab the connection before the readOnly flag is set, and everything silently goes to the primary. People often get this wrong in interviews.

The risks:

  • Read-your-writes. A user updates their profile and reloads the page: the replica is still behind, and the old data shows up. For a few seconds after a write, send that user's reads to the primary, or make critical reads readOnly = false.
  • Business checks like "is the balance sufficient?" should never read from a replica.
  • If the replica goes down, fall back to the primary, but don't choke the primary.
  • Watch the replication lag and set an alert.