The transactional outbox pattern
The dual-write problem, writing events to an outbox table inside the same transaction, relaying them, at-least-once delivery, and how Spring Modulith's event_publication table plus SperoTek's sealed email outbox implement it.
The dual-write problem
You need to do two things: update the DB and send a message (an email, a RabbitMQ message, a webhook). There’s no transaction that covers both:
Option A: send, then commit -> commit fails -> message sent for something that never happened
Option B: commit, then send -> crash/network fail between -> DB updated, message LOST
Option B with after-commit hooks (previous lesson) is better, but it still loses messages if the process dies.
The outbox
Write the message into the database, in the same transaction as the business change. A separate relay delivers it later.
CREATE TABLE outbox (
id UUID PRIMARY KEY, aggregate_id UUID, type TEXT, payload JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), published_at TIMESTAMPTZ, attempts INT DEFAULT 0
);
@Transactional
public void approveBooking(UUID id) {
booking.approve(); // business change
outbox.save(new OutboxMessage("BookingApproved", payload)); // SAME transaction: atomic
}
// relay (scheduler or CDC)
@Scheduled(fixedDelay = 2000)
void relay() {
for (OutboxMessage m : outbox.lockNextBatch(50)) { // SELECT ... FOR UPDATE SKIP LOCKED
try { broker.send(m); m.markPublished(); }
catch (Exception e) { m.recordFailure(e); }
}
}
Guarantee: if the business change committed, the message will be delivered at least once. The relay can crash after sending but before marking the row published, which causes a resend, so consumers must be idempotent.
In your projects
001-event-publication.sql · application.yaml spring.modulith.events · notification/*SperoTek uses two layers of outbox:
-
Spring Modulith’s JDBC event publication registry. Every event sent to an
@ApplicationModuleListeneris written toevent_publicationin the publishing transaction. When the listener completes, the row is deleted (completion-mode: delete). Incomplete rows older than 5 minutes are stale and can be republished, including on restart. -
Email outbox.
EmailOutbox.enqueue(...)→DefaultEmailOutboxseals the message withKeyRingCipherand publishes aSendEmailcommand:
@Async(MailExecutorConfig.MAIL_EXECUTOR)
@TransactionalEventListener(id = LISTENER_ID)
public void on(SendEmail event) { transport.send(renderer.render(message)); }FailedEmailResubmitter retries every 5 minutes (up to 12 attempts, batches of 50), and UndeliveredEmailMonitor alerts on emails that never went out. Mail sending itself retries twice with backoff (1 s, ×3). The integration tests EmailRetryIT and EmailRestartIT prove that emails survive an app restart.
shared/messaging/ResilientPublisher.javaRM goes the other way: broker first, with a fallback. It publishes to RabbitMQ, and on AmqpException it runs the handler in-process on notificationThreadPool, deferred until after commit. That’s highly available when the broker is down, but in-process work is lost if the app also dies. It’s a pragmatic trade-off for notifications.
TransactionalRabbitPublisherAfter-commit publish to RabbitMQ. It’s correct for ordering (no message for a rolled-back change), but it’s not an outbox: a crash between commit and send loses the message. Reconciliation jobs cover the money-critical paths.
Alternatives
| Approach | Guarantee | Complexity |
|---|---|---|
| Send inside the transaction | ❌ Ghost messages | Low |
| After-commit hook (IR3D) | ❌ Lost on crash | Low |
| Outbox + polling relay (SperoTek) | ✅ At-least-once | Medium |
| Outbox + CDC (Debezium reads the Postgres WAL and pushes to Kafka) | ✅ At-least-once, low latency | High (Kafka Connect) |
| Inbox pattern on the consumer | Deduplication (exactly-once effect) | Medium |
| Distributed transactions (XA / 2PC) | Atomic | High; poorly supported by brokers; avoid |
Related concepts you must know
- Exactly-once delivery is a myth across networks. You build exactly-once effects from at-least-once delivery plus idempotency.
- The inbox pattern. The consumer records processed message ids in its own DB, in the same transaction as its effect.
- Ordering. Outbox rows are ordered per aggregate; parallel relays can reorder them.
- Outbox growth. Delete or archive published rows (
completion-mode: delete).