Spring Application Events and the Transactional Outbox: Three Designs, Two Failures
Closing a ticket must also send 'ticket.closed'. Send it inside the transaction and a rollback still announces it. Move it to an AFTER_COMMIT listener and a broker outage loses it. Write it to an outbox table in the same transaction and a relay delivers it once the broker is back.
What you will learn
- See why sending a message inside a transaction can announce a rollback
- Publish an event with ApplicationEventPublisher and handle it with @TransactionalEventListener(AFTER_COMMIT)
- Explain why an AFTER_COMMIT send can still be lost
- Write an outbox row in the same transaction and deliver it with a @Scheduled relay
Before you start
- Spring @Transactional: All or Nothing, the Proxy, and the Self-Call Trap
- Scheduled Jobs in Spring Boot
When a ticket is closed, two things must happen: the row in PostgreSQL changes, and a ticket.closed message goes to a broker so other services hear about it. Two writes, two systems, and no shared transaction. We'll try three designs against the same two failures: the transaction rolls back, and the broker is down. (For the idea in general, see Events and the Transactional Outbox; this article is the Spring version.)
Design 1: publish inside the transaction
DirectTicketService.close is @Transactional: it updates the ticket (not committed yet), calls broker.publish(...) right away, and then, for the test, fails. The log says the ticket was closed and published ticket.closed ticket 1. The request answered 500, the database rolled back, and GET /tickets/1 says OPEN. But the broker already has the message. The database can roll back; the message can't.
Design 2: publish an event, send after the commit
@Service
public class TicketService {
private static final Logger log = LoggerFactory.getLogger(TicketService.class);
private final JdbcClient jdbc;
private final ApplicationEventPublisher events;
public TicketService(JdbcClient jdbc, ApplicationEventPublisher events) {
this.jdbc = jdbc;
this.events = events;
}
@Transactional
public void close(long ticketId, boolean failAfterwards) {
jdbc.sql("update tickets set status = 'CLOSED' where id = ?").param(ticketId).update();
log.info("ticket {} closed", ticketId);
events.publishEvent(new TicketClosed(ticketId));
log.info("event published for ticket {}", ticketId);
if (failAfterwards) {
throw new IllegalStateException("the commit is refused");
}
}
}
publishEvent hands a TicketClosed event to listeners inside this application. Nothing goes to the broker yet. The listener decides when:
@Component
public class TicketClosedListener {
private final MessageBroker broker;
public TicketClosedListener(MessageBroker broker) {
this.broker = broker;
}
// runs only after the transaction has committed; a rollback means it never runs
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onTicketClosed(TicketClosed event) {
broker.publish("ticket.closed", "ticket " + event.ticketId());
}
}
For ticket 3, the "published" line appears a moment after the commit, on the same thread. For ticket 2, a request that failed, there's no published line at all: 500, the ticket is OPEN, and no message announces a close that never happened. The rollback problem is fixed.
The second failure: committed, then the send fails
Turn the stand-in broker off (POST /broker/down) and close ticket 4. The update and the event commit; ticket 4 is CLOSED. Then onTicketClosed runs, publish throws IllegalStateException, and Spring logs it as an ERROR from TransactionSynchronizationUtils. The caller got 200. The ticket is closed. No message was sent, and nothing will ever retry it. The event lived only in memory.
Design 3: the transactional outbox
A message that matters belongs in the same transaction as the change it announces. So make the message a row:
create table outbox (
id bigserial primary key,
topic varchar(40) not null,
payload varchar(200) not null,
created_at timestamp not null default now(),
sent_at timestamp
);
@Transactional
public void close(long ticketId, boolean failAfterwards) {
jdbc.sql("update tickets set status = 'CLOSED' where id = ?").param(ticketId).update();
log.info("ticket {} closed", ticketId);
// same transaction: the message exists exactly when the ticket is closed
jdbc.sql("insert into outbox (topic, payload) values ('ticket.closed', ?)")
.param("ticket " + ticketId).update();
log.info("outbox row saved for ticket {}", ticketId);
if (failAfterwards) {
throw new IllegalStateException("the commit is refused");
}
}
The broker isn't called here at all. Both rows commit together, or both roll back. Ticket 6 failed: 500, OPEN, and no outbox row for it.
A relay sends it, and keeps trying
@Scheduled(fixedDelay = 500)
public void relay() {
List<OutboxRow> pending = jdbc
.sql("select id, topic, payload from outbox "
+ "where sent_at is null order by id")
.query((rs, n) -> new OutboxRow(
rs.getLong("id"), rs.getString("topic"), rs.getString("payload")))
.list();
for (OutboxRow row : pending) {
try {
broker.publish(row.topic(), row.payload());
jdbc.sql("update outbox set sent_at = now() where id = ?")
.param(row.id()).update();
log.info("outbox row {} marked as sent", row.id());
} catch (RuntimeException e) {
// the row stays unsent; the next round tries again
log.warn("outbox row {} not sent: {}", row.id(), e.getMessage());
return;
}
}
}
With the broker down, ticket 5's row (row 1) got five WARN lines, not sent: broker is down, one every half second. Then the broker came back, the next round published it, and the log said outbox row 1 marked as sent.
One thing to keep in mind: a crash between the send and the update would send the same row a second time. The outbox gives you at least once, so the receiver has to cope with duplicates (see Retries, Dead-Letter Topics and Idempotency).
The same two failures, three designs
| Design | Transaction rolls back | Broker down after commit |
|---|---|---|
| Send inside the transaction | message already sent, ticket OPEN | the close and the send are tied together: no retry later |
AFTER_COMMIT event | no message (correct) | ticket CLOSED, message lost |
| Outbox + relay | no row, no message | row waits, sent later |
Common mistakes
- A plain
@EventListenerfor messages. It runs inside the transaction, so a rollback after it has already sent. - Trusting
AFTER_COMMITfor messages that matter. Fine for a cache refresh; not for an event other systems depend on. - Publishing from the relay without marking the row. Every round re-sends everything.
- Receivers that assume exactly once. Design them for duplicates.
Try it yourself
With the broker down, close three tickets through the outbox service, then bring the broker back. In what order are the rows sent, and why does the relay return on the first failure instead of trying the next row?
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Why Spring in 2026: What the Container Does and What Spring Framework 7 Changed
Spring in one line: a container that creates your classes and hands each one what it needs. Plus the Spring Framework 7 baseline (JDK 17 to 25, Jakarta EE 11, Tomcat 11, JUnit 6), what got better than Spring 6, and a two-line version check.
A Plain Spring Project, No Boot: Your First Bean With spring-context
One dependency, one recipe, one getBean: a Maven project with spring-context 7.0.9, a Blog record, an AppConfig with @Bean, and a main that asks the container for the Blog. Then delete @Bean and meet NoSuchBeanDefinitionException.
Inversion of Control and Dependency Injection in Spring: One Program, Built Three Ways
A PostService needs a PostRepository. Build it three ways: the service calls new itself (tight coupling), main hands it in through the constructor (DI by hand), and the Spring container does the wiring from a @Configuration recipe.
Spring Component Scanning: @Component and @ComponentScan Instead of @Bean Methods
Instead of one @Bean method per class, put @Component on EmailNotifier and PostService and @ComponentScan on an empty BlogConfig. Spring walks the package, finds the stickers and builds the beans; main doesn't change.
