Skip to content
Tutorials Center
My learning

Topics

Lesson 69 of 119 ยท Spring Framework

Spring Transactions and Events

Understand @Transactional propagation, rollback rules and read-only mode, then decouple code with application events and @TransactionalEventListener, with runnable models.

Almost every business operation touches more than one row: an order and its lines, a transfer and its two balance updates, a signup and a welcome email. Either all of it must happen or none of it. In Spring you get that guarantee by putting @Transactional on a method, and most of the time it simply works. The trouble starts when one transactional method calls another: do they share a transaction, or does the inner one get its own? That choice is called propagation, and getting it wrong causes lost audit rows, mysterious UnexpectedRollbackExceptions and half-saved data.

This lesson explains propagation and the rollback rules with a small transaction manager you can run, built on plain JDBC and H2. Then it moves to application events, Spring's built-in publish/subscribe mechanism, and to @TransactionalEventListener, which makes sure side effects such as emails only happen for transactions that really committed. You should know how proxies work from Aspect-Oriented Programming and the basics of JDBC transactions.

What @Transactional really does

@Transactional is an aspect. Spring wraps your bean in a proxy; when a caller invokes a transactional method, the proxy asks a PlatformTransactionManager to begin a transaction, calls your method, and then commits, or rolls back if the method failed.

Java
@Service
public class OrderService {

    @Transactional
    public void placeOrder(Cart cart) {
        orders.save(Order.from(cart));
        stock.reserve(cart.items());
    }
}

With JDBC or JPA the transaction is bound to the current thread: the manager stores a connection in a thread-local, and JdbcTemplate, JPA and Spring Data find it there. That is why all repository calls inside placeOrder take part in the same transaction without anyone passing a connection around.

sequenceDiagram
    participant C as Caller
    participant P as Proxy
    participant M as TransactionManager
    participant B as OrderService
    C->>P: placeOrder(cart)
    P->>M: begin
    P->>B: placeOrder(cart)
    B-->>P: returns, or throws
    P->>M: commit, or rollback
    P-->>C: result or exception

The proxy starts the transaction before your method and ends it afterwards.

Because the proxy does the work, the usual proxy rules apply: only calls that go through the proxy are transactional, so a this.save() call inside the same class is not (the self-invocation trap from the AOP lesson), and the method must be visible to the proxy (public, not final or static).

Rollback rules

By default Spring rolls back on unchecked exceptions (RuntimeException and Error) and commits when a checked exception escapes. That surprises many developers, because in the EJB tradition checked exceptions meant "business problem, the data is still valid".

Java
@Transactional(rollbackFor = IOException.class)         // also roll back on this checked exception
@Transactional(noRollbackFor = PaymentDeclined.class)    // commit even though this one is thrown

An exception that is caught inside your method never reaches the proxy, so it does not cause a rollback either. If you catch an exception but still want the transaction rolled back, rethrow it or call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().

Propagation: joining or starting transactions

Propagation answers "what if a transaction already exists when this method is called?" The default is REQUIRED.

Propagation Transaction exists No transaction exists
REQUIRED (default) Join it Start a new one
REQUIRES_NEW Suspend it, start an independent one Start a new one
SUPPORTS Join it Run without one
NOT_SUPPORTED Suspend it, run without one Run without one
MANDATORY Join it Throw an exception
NEVER Throw an exception Run without one
NESTED Savepoint inside it (JDBC only) Start a new one

Only the first two matter in most applications. With REQUIRED, the inner call joins the outer transaction: one connection, one commit, one fate. With REQUIRES_NEW, the inner call runs on a second connection; it commits or rolls back on its own, whatever happens to the outer transaction later.

flowchart TD
    A["placeOrder() starts transaction T1"] --> B["audit.record()"]
    B --> C{"propagation?"}
    C -->|REQUIRED| D["joins T1<br/>same connection"]
    C -->|REQUIRES_NEW| E["T1 suspended, T2 starts<br/>second connection"]
    D --> F["rolls back or commits together with T1"]
    E --> G["T2 commits at once<br/>T1 continues"]

REQUIRED shares one fate; REQUIRES_NEW creates an independent transaction.

A transaction manager you can run

Spring itself isn't available in this runner, but the idea behind it fits in a few lines. The MiniTx class below keeps the current connection in a ThreadLocal, joins it for REQUIRED, and suspends it for REQUIRES_NEW. It rolls back on RuntimeException, just like Spring's default. The scenario writes an order and an audit entry. First the audit entry is REQUIRES_NEW, then REQUIRED:

Java REQUIRED versus REQUIRES_NEW

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Read the three results. In run 2 the order is rolled back but the audit row survives, because it was committed by its own transaction before the failure. In run 3 the audit row joined the outer transaction and vanished together with the order. That is exactly why audit logs, outbox-style failure records and "attempt" counters use REQUIRES_NEW, while ordinary business writes keep the default.

REQUIRES_NEW holds two connections at once: the suspended outer one and the new inner one. In a small connection pool, many threads doing this can deadlock waiting for a second connection. Use it sparingly, and see Connection Pooling.

The rollback-only trap

With REQUIRED, the inner method does not own the transaction. If it throws a RuntimeException, the proxy marks the shared transaction as rollback-only. If the outer method then catches that exception and carries on, it will later try to commit and Spring throws UnexpectedRollbackException: Transaction silently rolled back because it has been marked as rollback-only. The fix is to decide who owns failure: let the exception propagate, or give the inner call REQUIRES_NEW (or NESTED) so its failure is isolated.

Read-only, timeouts and isolation

Java
@Transactional(readOnly = true, timeout = 5, isolation = Isolation.READ_COMMITTED)
public List<OrderSummary> recentOrders() { ... }
  • readOnly = true is a hint. Hibernate skips dirty checking (faster, less memory) and some drivers or databases route the work to a replica. It is not a security feature. Put it on query methods, and often on the whole service class, overriding it with plain @Transactional on the write methods.
  • timeout is in seconds; the transaction fails if the statements run too long.
  • isolation defaults to the database default. Change it only when you understand the anomaly you are preventing; the options are explained in JDBC Transactions.

Keep transactions short: do not call remote HTTP services or send emails inside one, because a slow call holds a connection and row locks for as long as it takes. Which brings us to events.

Application events

Spring's ApplicationContext has a built-in event bus. A component publishes an event object with ApplicationEventPublisher; any bean with an @EventListener method taking that type receives it. Publisher and listener don't know each other, so OrderService doesn't need a dependency on the email, loyalty-points and analytics code.

Java
public record OrderPlaced(long orderId, String email) { }   // any object can be an event

@Service
class OrderService {
    private final ApplicationEventPublisher events;
    OrderService(ApplicationEventPublisher events) { this.events = events; }

    @Transactional
    public void place(Cart cart) {
        Order order = orders.save(Order.from(cart));
        events.publishEvent(new OrderPlaced(order.id(), cart.email()));
    }
}

@Component
class WelcomeMailer {
    @EventListener
    void on(OrderPlaced event) { mail.send(event.email(), "Thanks for your order"); }
}

By default listeners are synchronous: they run on the publisher's thread, inside publishEvent, before it returns. So they take part in the publisher's transaction, and an exception in a listener propagates to the publisher and fails the order. Add @Async (see Scheduling, Caching and Async) to run a listener on another thread. You can also filter with @EventListener(condition = "#event.total > 100"), order listeners with @Order, and return a new event object from a listener method to publish it in turn.

Events that wait for the commit

Here is the bug that synchronous events invite. place() publishes OrderPlaced, the mailer sends the email immediately, and then something later in the method fails and the transaction rolls back. The customer has a confirmation email for an order that does not exist.

@TransactionalEventListener fixes this by tying the listener to the transaction phase:

Java
@Component
class WelcomeMailer {
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    void on(OrderPlaced event) { mail.send(event.email(), "Thanks for your order"); }
}

The event is held until the surrounding transaction finishes. AFTER_COMMIT (the default) delivers it only if the commit succeeded; AFTER_ROLLBACK only after a rollback; AFTER_COMPLETION in both cases; BEFORE_COMMIT just before the commit, still able to write to the database. If there is no active transaction when the event is published, the listener is silently not called, unless you set fallbackExecution = true.

The model below mimics this with a tiny bus: ordinary listeners fire at once, after-commit listeners are queued and run only if the "transaction" succeeds.

Java Immediate versus after-commit listeners

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Order 2 produced a metrics line, since that listener ran immediately, but no email, because the transaction rolled back. That is the safe behavior for every irreversible side effect: emails, messages to a broker, cache invalidation, webhooks.

One more rule. In the AFTER_COMMIT phase the original transaction has committed but its resources may still be bound to the thread. If the listener must write to the database, give it its own transaction with @Transactional(propagation = Propagation.REQUIRES_NEW); a plain REQUIRED would join the finished transaction and its writes would never be committed.

Events decouple code inside one application. They are not durable: if the process dies between the commit and the listener, the email is lost. When delivery must be guaranteed, write the message to an outbox table in the same transaction and let a separate process publish it, as covered in Messaging.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A method annotated with the default @Transactional throws a checked IOException. What happens?

    Spring rolls back on RuntimeException and Error only. Use rollbackFor to include checked exceptions.
  2. 2. placeOrder() (REQUIRED) calls audit.record() annotated REQUIRES_NEW, then throws. What is the state afterwards?

    REQUIRES_NEW suspends the outer transaction and commits its own one on a second connection, so it is unaffected by the later failure.
  3. 3. Which listener type is the right choice for sending a confirmation email only for orders that were really saved?

    AFTER_COMMIT delivers the event only when the surrounding transaction committed. A plain @EventListener runs immediately, even if a rollback follows.
  4. 4. A plain @EventListener method throws an exception while the publisher is inside publishEvent(). What happens by default?

    Listeners are synchronous unless made asynchronous, so their failures surface in the publishing method and can roll back its transaction.

Summary

  • @Transactional is a proxy-based aspect: the transaction starts before and ends after the method, bound to the current thread. Self-invocation bypasses it.
  • By default only unchecked exceptions cause a rollback; use rollbackFor / noRollbackFor to change that. Use readOnly = true on queries and keep transactions short.
  • REQUIRED joins the existing transaction (shared fate); REQUIRES_NEW suspends it and commits independently on a second connection. Catching an inner failure after REQUIRED leads to UnexpectedRollbackException.
  • ApplicationEventPublisher and @EventListener decouple components; listeners are synchronous by default.
  • @TransactionalEventListener (default AFTER_COMMIT) runs side effects only after a successful commit. Listeners that write to the database need REQUIRES_NEW.
  • Events are not durable; use an outbox table when delivery must be guaranteed.

Next: Introduction to Spring Boot.