BBackend CourseLeroy Labs
0/0
Search the course

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.

● expertSperoTek (in dev)Report-Manager-2IR3D (Kontentt)

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.

Transactional outbox patternThe service writes the business row and an outbox row in one database transaction. A relay later reads unsent outbox rows and publishes them to a broker or email provider, then marks them sent. Consumers must be idempotent because delivery is at least once.ServiceapproveBooking()ONE database transactionbookingsUPDATE status = APPROVEDoutboxINSERT BookingApprovedRelaySKIP LOCKEDBrokeremail · queuepollmark published
Either both rows commit or neither does, so a message can never be lost or sent for a change that rolled back. A crash before "mark published" just means a resend.

In your projects

SperoTek (in dev)001-event-publication.sql · application.yaml spring.modulith.events · notification/*

SperoTek uses two layers of outbox:

  1. Spring Modulith’s JDBC event publication registry. Every event sent to an @ApplicationModuleListener is written to event_publication in 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.

  2. Email outbox. EmailOutbox.enqueue(...) → DefaultEmailOutbox seals the message with KeyRingCipher and publishes a SendEmail command:

@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.

Report-Manager-2shared/messaging/ResilientPublisher.java

RM 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.

IR3D (Kontentt)TransactionalRabbitPublisher

After-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
  • 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).

Check yourself

1. Core idea of the outbox?
2. Outbox delivery guarantee?
3. Which SperoTek test proves emails survive restart?