Video in progress

Strong Middle 🌱 Spring

If a synchronous @EventListener throws an exception, what happens to the code that published the event and to its transaction?

A plain @EventListener runs synchronously on the publishing thread, inside that transaction. The exception the listener throws comes out of the publishEvent() call and rolls back the outer transaction: even if the listener is "extra" work, the main operation is cancelled.

📖 Answer

@Transactional
public Order place(OrderRequest req) {
    Order o = orderRepository.save(Order.from(req));
    events.publishEvent(new OrderPlaced(o.getId())); // the listeners run right here
    return o;
}

@EventListener
void sendSms(OrderPlaced e) {
    smsClient.send(...); // the SMS service returned 500 → RuntimeException
}

The SMS wasn't sent, and the order wasn't saved either. This is often an unexpected result, because events were used for "loose coupling". In reality a synchronous listener is just a different way of writing an ordinary method call.

Another effect: if the listener is slow, the transaction and the connection stay open that long.

The options:

  • The listener must be part of the transaction (for example, reducing stock): it stays synchronous, and a failure rolling back is correct.
  • It must run after the commit: @TransactionalEventListener(phase = AFTER_COMMIT). Now a failure doesn't affect the order, but a listener error can be lost without a retry.
  • Independent and slow work: add @Async, or write to an outbox table and send from a separate worker.
  • Let the listener handle the error itself: try/catch and a log inside the listener; but that's also a way of hiding the error, so add a metric.

The order of several listeners is set with @Order; if the first one fails, the following ones aren't called at all.