Video in progress
What happens if you use @Transactional inside an @Async method, or call an @Async method from inside a transaction?
An async method runs on another thread, and a transaction is bound to its thread. So it doesn't see the caller's transaction: if it is @Transactional itself, it opens a separate new transaction, and it may not see data the caller hasn't committed yet.
📖 Answer
A typical mistake:
@Transactional
public void register(SignUp s) {
User u = users.save(new User(s));
mailer.sendWelcome(u.getId()); // @Async
} // commit happens here
@Async
@Transactional(readOnly = true)
public void sendWelcome(long userId) {
User u = users.findById(userId).orElseThrow(); // sometimes not found!
}
If the async thread starts fast, register hasn't committed yet and the new transaction doesn't find the user. On prod this shows up under load, now and then, and it is almost impossible to reproduce locally. On top of that, the email may go out even if register rolls back.
The right way is to run it after the commit:
@Async
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void on(UserRegistered e) { ... }
Put the data you need (email) inside the event, so you don't have to read it from the database again.
If the application goes down after the commit but before the email is sent, the email is lost. If you need a guarantee, use an outbox table: write the email task in the same transaction.
Sign up to mark studied questions and save your progress.