Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A service with two DataSources and JPA on the primary one writes to the secondary database inside an @Transactional method, but those writes are not rolled back when the method throws. Explain and fix.

@Transactional without a name uses the primary transaction manager, which is the JpaTransactionManager for the main DataSource, so only connections to the main database take part in the transaction. Writes to the secondary database use connections in auto-commit mode, so each statement commits on its own and nothing rolls them back. We fix it with a DataSourceTransactionManager for the secondary DataSource and @Transactional(transactionManager = "reportingTx") on methods that write there; making both databases commit atomically needs XA, so we usually redesign with an outbox or compensation instead.

Why this question is asked

Multi-database services often work perfectly until the first failure. A method writes to both databases, throws an exception halfway through, and afterwards the main database is clean while the secondary keeps half the changes. The code looks transactional, so people assume both writes were covered. Interviewers ask this because the answer shows whether we understand that a Spring transaction belongs to one resource, and what it really takes to change two databases together. In this answer, we will recap how a transaction manager binds a connection, reproduce the partial write, explain why the secondary writes commit immediately, fix it with a second transaction manager, discuss writing to both databases at once, and finish with how to make the boundaries obvious and tested.

1A Quick Recap of How a Transaction Manager Works

A transaction manager is the Spring component that begins, commits and rolls back transactions. Each one is tied to one resource. JpaTransactionManager works with one EntityManagerFactory and therefore one DataSource; DataSourceTransactionManager works with one DataSource directly.

When a @Transactional method starts, the chosen manager borrows a connection from its DataSource, switches it out of auto-commit, and binds it to the current thread through TransactionSynchronizationManager, keyed by that DataSource. Any JdbcTemplate, JdbcClient or JPA call on the same thread that uses the same DataSource finds the bound connection and joins the transaction. Code that uses a different DataSource finds nothing bound for it.

2Reproducing the Partial Write

Here is the failing case: JPA on the main database and a JdbcClient on the reporting one, in a single method.

Java
@Transactional // uses the primary JpaTransactionManager
public void closeDay(LocalDate day) {
orderRepository.markClosed(day); // main database, inside the transaction
reportingJdbc.sql("INSERT INTO daily_sales(day, total) VALUES (?, ?)")
.params(day, total(day)).update(); // reporting database: committed immediately
throw new IllegalStateException("totals do not match");
}
// After the exception:
// main database: order rows not closed (rolled back)
// reporting database: daily_sales row exists (never rolled back)

Notice that the exception does exactly what we expect on the main database. The problem is only on the reporting side, which is the clue that the transaction never covered it.

3Why the Secondary Writes Commit Immediately

When closeDay() starts, the JpaTransactionManager binds a connection for the main DataSource. When the JdbcClient on the reporting DataSource runs its INSERT, it asks DataSourceUtils for a connection to the reporting DataSource. There is no transaction bound for that DataSource, so it gets a fresh connection from the reporting pool. That connection is in auto-commit mode, the default for JDBC, so the INSERT is committed the moment it runs, and the connection goes straight back to the pool.

When the exception reaches the transaction interceptor, it rolls back the only transaction it knows about, the one on the main database. The reporting INSERT was already committed and is outside its reach.

Step throughOne method, two databases, one transaction
closeDay()JpaTransactionManagerMain databaseReporting database
begin, bind main connection to the thread
update orders (inside the transaction)
insert daily_sales on a new auto-commit connection
committed at once
throws IllegalStateException
rollback

6 messages in order. Play them, or step through them one at a time.

The reporting insert never joined the transaction, so there was nothing to roll back.

4The Fix: A Transaction Manager for the Secondary DataSource

We give the reporting DataSource its own DataSourceTransactionManager and name it on methods that write there.

Java
@Bean
DataSourceTransactionManager reportingTx(@Qualifier("reportingDataSource") DataSource ds) {
return new DataSourceTransactionManager(ds);
}
@Primary @Bean
JpaTransactionManager transactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf); // declared explicitly so it stays the default
}
@Service
class ReportWriter {
@Transactional(transactionManager = "reportingTx")
public void writeDailySales(LocalDate day, BigDecimal total) {
reportingJdbc.sql("INSERT INTO daily_sales(day, total) VALUES (?, ?)").params(day, total).update();
checkTotals(day); // an exception here now rolls back the insert
}
}

Now the reporting writes run in a real transaction on the reporting database and roll back on an exception. Declaring the JpaTransactionManager ourselves, as @Primary, matters because Boot's transaction manager auto-configuration backs off once any transaction manager bean exists, and plain @Transactional must still resolve to the main one. Putting the reporting work in its own bean also avoids the self-call problem, where a call inside one class skips Spring's proxy.

But this gives us two separate transactions, not one. If the main database commits and the reporting commit then fails, or the other way round, the two databases still disagree. Each one is consistent on its own; the pair is not.

5Writing to Both Databases Atomically

Committing two databases as one unit needs a distributed transaction: JTA with XA, where a transaction coordinator runs a two-phase commit across both. It works, but it brings an external transaction manager library, XA-capable drivers and configuration, slower commits, and tricky recovery when the coordinator fails between phases. Spring Boot's built-in JTA support has also changed across versions, so check your version before planning on it.

For most services, a redesign is better. With the outbox pattern, closeDay() writes its main changes and an outbox row describing the report update in one transaction on the main database; a separate process reads the outbox and applies the update to the reporting database, retrying until it succeeds. The reporting side becomes eventually consistent but never loses an update. Where the second write is a business step, a compensating action, an operation that undoes the first step if the second fails, is the other common choice.

6Making the Boundaries Obvious and Tested

The root cause of this bug is that nothing in the code said which database a repository belonged to. We make that visible. JPA repositories for each database live in separate packages with their own @EnableJpaRepositories, naming the entityManagerFactoryRef and transactionManagerRef; JDBC access to the reporting database goes only through a qualified JdbcClient in a reporting package. A reviewer then sees at a glance that a method touches two databases.

Finally, we test the behaviour we rely on. An integration test with Testcontainers starts both databases, calls the method with input that makes it throw, and asserts what each database contains afterwards. That test would have caught the original bug in seconds, and it protects the fix from a later refactoring that drops the transactionManager attribute.

Java
@Test
void reportingInsertRollsBackWhenTotalsDoNotMatch() {
assertThatThrownBy(() -> reportWriter.writeDailySales(day, wrongTotal))
.isInstanceOf(IllegalStateException.class);
Integer rows = reportingJdbc.sql("SELECT count(*) FROM daily_sales WHERE day = ?")
.param(day).query(Integer.class).single();
assertThat(rows).isZero(); // 0: the insert was rolled back
}

7Follow-up questions

Could we use ChainedTransactionManager instead?

ChainedTransactionManager came from Spring Data Commons and has been deprecated for years. It starts transactions on several managers and commits them one after another, but it is not atomic: if the second commit fails after the first succeeded, the first is not undone. It hides the problem rather than solving it, so an outbox or explicit ordering with compensation is the better choice.

How can we see which transaction a statement runs in?

Inside the method we can call TransactionSynchronizationManager.isActualTransactionActive() and check TransactionSynchronizationManager.hasResource(reportingDataSource), which tells us whether a connection for that DataSource is bound. Turning on debug logging for org.springframework.transaction and org.springframework.jdbc.datasource also shows each transaction being created and which connection it uses.

What if both DataSources point to the same database server?

It makes no difference to Spring. Two DataSources means two pools and two sets of connections, and a transaction lives on one connection. Even two schemas on the same PostgreSQL instance are separate transactions when reached through separate DataSources. If we need them in one transaction, we use one DataSource and qualify table names with the schema.

8Conclusion

In this answer, we saw that a Spring transaction belongs to one transaction manager and one DataSource. Plain @Transactional used the primary JpaTransactionManager, so writes to the secondary DataSource ran on auto-commit connections and committed immediately, out of reach of the rollback. A DataSourceTransactionManager for the secondary database, named with @Transactional(transactionManager = "reportingTx"), fixes rollback there, but true atomicity across both needs XA, so we usually prefer an outbox or compensation. Separate packages and qualified clients make the boundaries visible, and Testcontainers tests prove the rollback.

What to say in the interviewAbout 80 seconds aloud

Open with

The method's @Transactional uses the default transaction manager, which is the JpaTransactionManager for the primary DataSource. That manager binds a connection for the main database to the thread, and only code using that DataSource joins the transaction.

Then, if they want more

When the JdbcClient for the secondary database runs, there is no transaction bound for its DataSource, so it gets an ordinary connection in auto-commit mode, and every statement commits the moment it runs. When the exception is thrown, Spring rolls back the main database only.

To fix it, I would define a DataSourceTransactionManager for the secondary DataSource, name it reportingTx, declare the JPA manager explicitly as @Primary so the default stays the same, and put the secondary writes in a bean method annotated with @Transactional transactionManager equals reportingTx. That makes them roll back, but it is still two separate transactions.

If the business needs both databases to change together, I would not reach for XA unless there is no alternative; I would use an outbox row in the main database and apply the report change asynchronously with retries, or a compensating action.

I would also separate repositories by package per database so the boundary is visible, and add a Testcontainers test that throws and checks both databases.

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
java.sql, package documentation
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 "A service with two DataSources and JPA on the primary one writes to the secondary...": https://scrivio-interview-library.netlify.app/databases/jdbc/7495fe566f/