Scrivio Interview library
CodingIntermediate6 min read · updated 12 November 2026

You need to write an audit record that must be saved even if the business transaction rolls back. Write the code and explain the risks.

Put the audit write in a method on a separate bean annotated @Transactional(propagation = Propagation.REQUIRES_NEW) and call it through the injected bean, not through this, so the proxy starts an independent transaction that commits even when the business transaction rolls back. The risks are that the outer transaction is suspended but keeps its connection, so each request needs two connections from the pool; that the audit commits independently, so we must decide whether an audit failure should fail the business operation; and that an asynchronous audit from an after-completion event is often a simpler alternative.

Why this question is asked

Audit trails often have to record attempts, not just successes: a failed payment, a rejected login, a refused withdrawal. If the audit row is written in the same transaction as the business work, a rollback removes it together with everything else, which is exactly when we needed it. Interviewers ask this as a coding question because the obvious code has two traps, the self-invocation trap and the connection pool trap. In this answer, we will see the broken version, write the working one, look at what happens to connections, decide what an audit failure should do, and compare it with an event-based alternative.

1The Version That Loses the Audit Record

Here is the first attempt. The audit row is written inside the business transaction, so when the withdrawal is refused and the exception rolls back the transaction, the audit row is rolled back too.

Java
@Service
class AccountService {
@Transactional
public void withdraw(long accountId, BigDecimal amount) {
auditRepository.save(new AuditEntry(accountId, "WITHDRAW_ATTEMPT", amount));
Account a = accounts.findById(accountId).orElseThrow();
a.withdraw(amount); // throws InsufficientFundsException (unchecked)
}
}
// SELECT count(*) FROM audit_entry; -- 0: the attempt was rolled back with the withdrawal

A common second attempt is to move the save into a private or same-class method annotated REQUIRES_NEW. That does nothing, because a call on this never goes through the proxy, so the annotation is never read.

2Writing the Audit in Its Own Transaction

The working version puts the audit write in its own bean. The business method calls it through the injected reference, so the call goes through that bean's proxy, and REQUIRES_NEW suspends the business transaction and starts a fresh one.

Java
@Service
class AuditWriter {
private final AuditRepository repository;
AuditWriter(AuditRepository repository) { this.repository = repository; }
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void record(long accountId, String action, BigDecimal amount) {
repository.save(new AuditEntry(accountId, action, amount));
} // COMMIT of the audit transaction here
}
@Service
class AccountService {
private final AuditWriter audit;
private final AccountRepository accounts;
@Transactional
public void withdraw(long accountId, BigDecimal amount) {
audit.record(accountId, "WITHDRAW_ATTEMPT", amount); // through the proxy: own transaction
Account a = accounts.findById(accountId).orElseThrow();
a.withdraw(amount); // throws, business tx rolls back
}
}
// SELECT count(*) FROM audit_entry; -- 1: the attempt survived the rollback
Step throughTwo transactions in one request
AccountServiceAuditWriter proxyTx managerDatabase
begin business tx (connection 1)
record(...)
REQUIRES_NEW: suspend tx 1
begin audit tx (connection 2)
insert audit row, COMMIT
resume tx 1
update account fails
rollback tx 1 only

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

While the audit transaction runs, the suspended business transaction still holds connection 1.

Notice the order of events. The audit transaction has already committed by the time withdraw() fails, so the later rollback cannot touch it. If we want to audit the outcome as well, we catch the exception in withdraw(), call audit.record(..., "WITHDRAW_REFUSED", ...) and rethrow, and that second record also gets its own transaction.

3The Connection Pool Risk

Suspending a transaction does not release its connection. The business transaction keeps connection 1 while the audit transaction takes connection 2. So every request that reaches audit.record() needs two connections at once.

With a HikariCP pool of 10 connections and 10 concurrent withdrawals, each request holds one connection and waits for a second, and there are none left. Every request waits until the pool's connectionTimeout, 30 seconds by default, and then fails. This is a pool deadlock, and it only shows up under load. The defences are to size the pool for two connections per concurrent request on this path, to keep the audit transaction very short, and to avoid calling REQUIRES_NEW methods in loops.

4Deciding What an Audit Failure Means

The audit transaction commits independently, but it can also fail independently: a full disk, a constraint violation on the audit table, a pool timeout. If record() throws, the exception propagates into withdraw() and, being unchecked, rolls back the business transaction too. Whether that is right is a business decision. For a regulatory audit trail, 'no audit, no withdrawal' is often the rule, so letting the failure propagate is correct. For an informational log, we would catch the exception around the call and carry on.

Java
try {
audit.record(accountId, "WITHDRAW_ATTEMPT", amount);
} catch (DataAccessException e) {
log.error("audit write failed for account {}", accountId, e); // informational audit only
}

There is also the reverse case to think about: the audit records an attempt that then rolls back, so audit readers must understand that an 'attempt' row does not mean the action happened. Naming the actions clearly, such as ATTEMPT, SUCCEEDED and REFUSED, avoids misreading.

5An Alternative: Audit From an Event After Completion

If the audit does not have to be written before the business work, we can publish an application event and handle it after the transaction finishes. @TransactionalEventListener with phase AFTER_COMPLETION runs once the transaction has committed or rolled back, and we can record which one happened.

Java
// in withdraw(): events.publishEvent(new WithdrawAttempted(accountId, amount));
@Component
class AuditListener {
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMPLETION)
@Transactional(propagation = Propagation.REQUIRES_NEW) // needed to write after completion
public void on(WithdrawAttempted e) { repository.save(AuditEntry.of(e)); }
}

This keeps the audit out of the business method and avoids holding two connections at the same moment, because the first is released before the listener runs. Adding @Async moves the write off the request thread entirely. The trade-off is durability: if the application crashes between the business commit and the listener, the audit is lost. For audits that must never be lost, the outbox pattern, writing the audit intent in the business transaction and publishing it afterwards, is the stronger option, though it only covers committed work.

6Follow-up questions

Why not use NESTED instead of REQUIRES_NEW?

Because NESTED is a savepoint inside the same transaction. If the outer transaction rolls back, the nested work is rolled back with it, which is exactly what we are trying to avoid. NESTED also is not supported for JPA operations in general.

Can you test that the audit survives?

Yes. Call withdraw() with an amount that fails, assert the exception, then query the audit table in a separate transaction and assert the row is there. The test itself must not be @Transactional, or the test transaction would hide the real commit behaviour.

Does the audit transaction see the business transaction's uncommitted changes?

No. It runs on a different connection, so under READ COMMITTED it sees only committed data. If it tries to update a row the suspended transaction has locked, it waits on a lock that will never be released, a deadlock inside one request.

7Conclusion

In this answer, we wrote an audit record that survives a business rollback by placing it in a separate bean's method with REQUIRES_NEW and calling it through the bean so the proxy applies. We saw that the suspended transaction keeps its connection, so each request needs two connections and a small pool can deadlock, that we must decide on purpose whether an audit failure fails the business operation, and that an after-completion event or an outbox is often a simpler alternative.

What to say in the interviewAbout 90 seconds aloud

Open with

I'd put the audit write in its own bean, say AuditWriter, with a method annotated @Transactional with propagation REQUIRES_NEW, and call it from the business method through the injected bean.

Then, if they want more

Calling it through this, or making it private, wouldn't work, because the proxy is what starts the new transaction. With REQUIRES_NEW, Spring suspends the business transaction, starts a new one, saves the audit row and commits it, then resumes the business transaction. So if the withdrawal later fails and rolls back, the audit row is already committed.

There are a few risks I'd call out. The suspended transaction keeps its connection, so each request needs two connections at once; with a small pool and enough concurrent requests, they all hold one and wait for a second, and you get a pool deadlock until the connection timeout.

So I'd size the pool for it, keep the audit transaction tiny and never call it in a loop. Second, the audit can fail on its own, and the exception would roll back the business transaction too; for a regulatory audit that's probably right, for an informational one I'd catch and log it.

Third, an attempt row doesn't mean the action happened, so I'd name actions clearly. If the audit can be written after the fact, a TransactionalEventListener in the AFTER_COMPLETION phase, or an outbox for committed work, is often simpler.

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.
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 "You need to write an audit record that must be saved even if the business transaction...": https://scrivio-interview-library.netlify.app/databases/transactions/5714027107/