The transactional outbox: publishing events without losing them
Saving data and sending a message are two writes that no local transaction covers, so one can succeed while the other fails. The outbox pattern writes the message into the database with the data and publishes it afterwards. This page runs both dual-write failures, then the outbox, its relay, duplicate delivery and competing relays, with Spring Framework 7.0 and H2 standing in for a real database and broker.
Contents
The dual-write problem
A service that saves an order usually has to tell other services about it: billing, shipping and email all want an OrderPlaced
- Message first, then the database fails: other services act on an order that does not exist. Shipping prepares a parcel for a rolled-back order.
- Database first, then the broker fails: the order exists, but no one hears about it. The customer is never charged, and nothing in the logs says why.
Retrying the send does not fix the second case, because the process may crash before the retry. Distributed transactions (XA, two-phase commit) can cover both systems, but Kafka does not take part in XA, and two-phase commit adds locking and a coordinator that most teams avoid.
The transactional outbox pattern removes the second write from the request. The service writes the order and the message into the same database, in one local transaction: the message goes into an outbox
| Approach | Message lost possible | Message for rolled-back data possible | Best for |
|---|---|---|---|
| Send inside the transaction | No | Yes | Nothing; this is the bug |
Send after commit, such as with @TransactionalEventListener | Yes, on a crash or broker outage | No | Notifications where an occasional loss is acceptable |
| Outbox table and a polling relay | No | No | Most services; needs only the database you already have |
| Outbox table and change data capture (Debezium) | No | No | High volume, or teams already running Kafka Connect |
| Two-phase commit (XA) | No | No | Brokers and databases that both support XA, such as some JMS setups |
The outbox gives at-least-once delivery, not exactly-once: a message can be published twice, as shown below, so consumers must handle duplicates. In these programs, an H2 database stands in for PostgreSQL or MySQL, and an in-memory list stands in for the broker. A real system uses Kafka, RabbitMQ or another broker in its place; the database side of the pattern is the same.
Both dual-write failures, shown running
The first order is sent to the broker inside its transaction, and a later statement in that transaction breaks a check constraint. The second order is committed first and sent afterwards, while the broker is down:
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
public class DualWrite {
/** Stands in for Kafka or another broker: it keeps every message it accepts. */
static class Broker {
final List<String> messages = new CopyOnWriteArrayList<>();
volatile boolean down;
void send(String message) {
if (down) {
throw new IllegalStateException("broker unreachable");
}
messages.add(message);
}
}
@Configuration
@EnableTransactionManagement
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:dualwrite;DB_CLOSE_DELAY=-1");
}
@Bean
JdbcTemplate jdbc(DataSource dataSource) {
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, total INT CHECK (total > 0))");
return jdbc;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
Broker broker() {
return new Broker();
}
@Bean
OrderService orderService(JdbcTemplate jdbc, Broker broker,
PlatformTransactionManager manager) {
return new OrderService(jdbc, broker, manager);
}
}
static class OrderService {
private final JdbcTemplate jdbc;
private final Broker broker;
private final TransactionTemplate transaction;
OrderService(JdbcTemplate jdbc, Broker broker, PlatformTransactionManager manager) {
this.jdbc = jdbc;
this.broker = broker;
this.transaction = new TransactionTemplate(manager);
}
/** Sends inside the transaction, then a later statement fails. */
@Transactional
public void sendThenFail(int id) {
jdbc.update("INSERT INTO orders VALUES (?, 100)", id);
broker.send("OrderPlaced " + id);
jdbc.update("UPDATE orders SET total = -1 WHERE id = ?", id);
}
/** Commits first, then sends: the send can fail after the commit. */
public void commitThenSend(int id) {
transaction.executeWithoutResult(
status -> jdbc.update("INSERT INTO orders VALUES (?, 100)", id));
broker.send("OrderPlaced " + id);
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
OrderService service = context.getBean(OrderService.class);
Broker broker = context.getBean(Broker.class);
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("1. Send inside the transaction, then the transaction fails:");
try {
service.sendThenFail(1);
} catch (RuntimeException e) {
System.out.println(" caller sees " + e.getClass().getSimpleName());
}
System.out.println("2. Commit, then send while the broker is down:");
broker.down = true;
try {
service.commitThenSend(2);
} catch (IllegalStateException e) {
System.out.println(" caller sees " + e.getMessage());
}
System.out.println("Orders in the database: "
+ jdbc.queryForList("SELECT id FROM orders ORDER BY id", Integer.class));
System.out.println("Messages on the broker: " + broker.messages);
}
}
}
1. Send inside the transaction, then the transaction fails:
caller sees DataIntegrityViolationException
2. Commit, then send while the broker is down:
caller sees broker unreachable
Orders in the database: [2]
Messages on the broker: [OrderPlaced 1]
- Order 1 was rolled back by the
, butDataIntegrityViolationException was already on the broker. A broker send cannot be rolled back with the database.OrderPlaced 1 - Order 2 is in the database, but the broker has no message for it. The caller saw "broker unreachable" after the order had been committed, so it cannot simply report a failure either: the order exists.
- The database says
and the broker says[2] : each system holds the order the other one does not know about.[OrderPlaced 1]
Moving the send into a @TransactionalEventListener
Writing to the outbox in the same transaction
The fix starts with a table. Each row is one message: an id that orders the rows, the aggregate it belongs to, the event type, the payload and a published flag. Order 3 here exceeds a credit limit and fails after its outbox row has been written:
import javax.sql.DataSource;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
public class OutboxWrite {
@Configuration
@EnableTransactionManagement
static class Config {
@Bean
DataSource dataSource() {
return new DriverManagerDataSource("jdbc:h2:mem:outboxwrite;DB_CLOSE_DELAY=-1");
}
@Bean
JdbcTemplate jdbc(DataSource dataSource) {
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.execute("CREATE TABLE orders (id INT PRIMARY KEY, total INT CHECK (total > 0))");
jdbc.execute("""
CREATE TABLE outbox (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
aggregate_id VARCHAR(20) NOT NULL,
event_type VARCHAR(40) NOT NULL,
payload VARCHAR(200) NOT NULL,
published BOOLEAN DEFAULT FALSE NOT NULL)""");
return jdbc;
}
@Bean
PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
@Bean
OrderService orderService(JdbcTemplate jdbc) {
return new OrderService(jdbc);
}
}
static class OrderService {
private final JdbcTemplate jdbc;
OrderService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Transactional
public void placeOrder(int id, int total) {
jdbc.update("INSERT INTO orders VALUES (?, ?)", id, total);
jdbc.update("INSERT INTO outbox (aggregate_id, event_type, payload) VALUES (?, ?, ?)",
"order-" + id, "OrderPlaced",
"{\"orderId\":" + id + ",\"total\":" + total + "}");
if (total > 1000) {
throw new IllegalStateException("credit limit exceeded");
}
}
}
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(Config.class)) {
OrderService service = context.getBean(OrderService.class);
service.placeOrder(1, 250);
service.placeOrder(2, 40);
try {
service.placeOrder(3, 5000);
} catch (IllegalStateException e) {
System.out.println("order 3 failed: " + e.getMessage());
}
JdbcTemplate jdbc = context.getBean(JdbcTemplate.class);
System.out.println("orders: "
+ jdbc.queryForList("SELECT id FROM orders ORDER BY id", Integer.class));
System.out.println("outbox:");
jdbc.query("SELECT * FROM outbox ORDER BY id", rs -> {
System.out.printf(" %d %-8s %-12s %-28s published=%s%n", rs.getLong("id"),
rs.getString("aggregate_id"), rs.getString("event_type"),
rs.getString("payload"), rs.getBoolean("published"));
});
}
}
}
order 3 failed: credit limit exceeded
orders: [1, 2]
outbox:
1 order-1 OrderPlaced {"orderId":1,"total":250} published=false
2 order-2 OrderPlaced {"orderId":2,"total":40} published=false
- Orders 1 and 2 committed with their outbox rows, ids 1 and 2, both with
. Nothing has gone to a broker yet.published=false - Order 3 inserted its order and its outbox row, then threw. The rollback removed both, so there is no row 3 in either table. The data and the message now succeed or fail together.
- The
column,aggregate_id andorder-1 , becomes the message key. Kafka sends all messages with the same key to the same partition, which keeps each order's events in order.order-2
The payload is usually JSON, written by the same code that would otherwise call the broker. Keep the outbox insert next to the business write, in the same @Transactional
The relay: publishing outbox rows
The relay is a loop that runs every few hundred milliseconds: read unpublished rows in id order, send each one, mark it published. In a Spring application it is usually a @Scheduled(fixedDelay = ...)
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class OutboxRelay {
/** Stands in for Kafka: send() returns only when the broker has stored the message. */
static class Broker {
final List<String> messages = new CopyOnWriteArrayList<>();
volatile boolean down;
void send(String key, String payload) {
if (down) {
throw new IllegalStateException("broker unreachable");
}
messages.add(key + " " + payload);
}
}
/** Polls unpublished rows in id order, sends each one, then marks it published. */
static class Relay {
private final JdbcTemplate jdbc;
private final TransactionTemplate transaction;
private final Broker broker;
Relay(JdbcTemplate jdbc, TransactionTemplate transaction, Broker broker) {
this.jdbc = jdbc;
this.transaction = transaction;
this.broker = broker;
}
// In an application: @Scheduled(fixedDelay = 500)
int publishBatch() {
Integer sent = transaction.execute(status -> {
List<Map<String, Object>> rows = jdbc.queryForList("SELECT id, aggregate_id,"
+ " payload FROM outbox WHERE published = FALSE ORDER BY id"
+ " FETCH FIRST 10 ROWS ONLY FOR UPDATE SKIP LOCKED");
int count = 0;
for (Map<String, Object> row : rows) {
try {
broker.send((String) row.get("AGGREGATE_ID"), (String) row.get("PAYLOAD"));
} catch (IllegalStateException e) {
System.out.println(" send failed: " + e.getMessage()
+ ", row " + row.get("ID") + " stays unpublished");
break;
}
jdbc.update("UPDATE outbox SET published = TRUE WHERE id = ?", row.get("ID"));
count++;
}
return count;
});
return sent == null ? 0 : sent;
}
}
public static void main(String[] args) {
DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:relay;DB_CLOSE_DELAY=-1");
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
TransactionTemplate transaction =
new TransactionTemplate(new DataSourceTransactionManager(dataSource));
jdbc.execute("CREATE TABLE outbox (id BIGINT AUTO_INCREMENT PRIMARY KEY,"
+ " aggregate_id VARCHAR(20), payload VARCHAR(200),"
+ " published BOOLEAN DEFAULT FALSE)");
for (String row : new String[] {"order-1|OrderPlaced", "order-2|OrderPlaced",
"order-1|OrderPaid"}) {
String[] parts = row.split("\\|");
jdbc.update("INSERT INTO outbox (aggregate_id, payload) VALUES (?, ?)",
parts[0], parts[1]);
}
Broker broker = new Broker();
Relay relay = new Relay(jdbc, transaction, broker);
broker.down = true;
System.out.println("Poll 1, broker down:");
System.out.println(" published " + relay.publishBatch());
broker.down = false;
System.out.println("Poll 2, broker back:");
System.out.println(" published " + relay.publishBatch());
jdbc.update("INSERT INTO outbox (aggregate_id, payload) VALUES ('order-2', 'OrderPaid')");
System.out.println("Poll 3, one new row:");
System.out.println(" published " + relay.publishBatch());
System.out.println("Poll 4, nothing new:");
System.out.println(" published " + relay.publishBatch());
System.out.println("Broker received, in order:");
broker.messages.forEach(m -> System.out.println(" " + m));
}
}
Poll 1, broker down:
send failed: broker unreachable, row 1 stays unpublished
published 0
Poll 2, broker back:
published 3
Poll 3, one new row:
published 1
Poll 4, nothing new:
published 0
Broker received, in order:
order-1 OrderPlaced
order-2 OrderPlaced
order-1 OrderPaid
order-2 OrderPaid
- Poll 1 failed on row 1 and stopped. All three rows stayed unpublished, waiting in the database rather than being lost.
- Poll 2 published all three, in id order. Poll 3 picked up the row added afterwards, and poll 4 found nothing.
- The broker received the four messages in the order the rows were written, so
arrived beforeorder-1 OrderPlaced .order-1 OrderPaid - The relay stops at the first failure instead of skipping the row. Skipping would publish later events for the same order before the failed one, which breaks the order consumers depend on.
The send must wait for the broker to confirm before the row is marked. With Spring for Apache Kafka that means waiting on the future that KafkaTemplate.send
@Scheduled(fixedDelay = 500)
@Transactional
public void publishBatch() {
List<OutboxRow> rows = outbox.lockNextBatch(100); // FOR UPDATE SKIP LOCKED
for (OutboxRow row : rows) {
kafka.send("orders", row.aggregateId(), row.payload()).get(10, TimeUnit.SECONDS);
outbox.markPublished(row.id());
}
}
A published
At-least-once delivery and duplicate messages
The relay sends a message and then records that it did. If it crashes between the two, the row is still unpublished after a restart, and the message is sent again. This program sends a loyalty-points message and kills the relay before its UPDATE
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class AtLeastOnce {
record Message(long id, String customer, int points) {
}
public static void main(String[] args) {
DataSource dataSource = new DriverManagerDataSource("jdbc:h2:mem:alo;DB_CLOSE_DELAY=-1");
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
TransactionTemplate transaction =
new TransactionTemplate(new DataSourceTransactionManager(dataSource));
jdbc.execute("CREATE TABLE outbox (id BIGINT PRIMARY KEY, customer VARCHAR(20),"
+ " points INT, published BOOLEAN DEFAULT FALSE)");
jdbc.execute("CREATE TABLE points (customer VARCHAR(20) PRIMARY KEY, total INT)");
jdbc.execute("CREATE TABLE processed_messages (message_id BIGINT PRIMARY KEY)");
jdbc.update("INSERT INTO outbox (id, customer, points) VALUES (41, 'ada', 50)");
jdbc.update("INSERT INTO points VALUES ('ada', 0)");
List<Message> broker = new ArrayList<>();
// The relay sends row 41, then crashes before its UPDATE commits.
for (int attempt = 1; attempt <= 2; attempt++) {
boolean crash = attempt == 1;
try {
transaction.executeWithoutResult(status -> {
for (Map<String, Object> row : jdbc.queryForList(
"SELECT * FROM outbox WHERE published = FALSE FOR UPDATE")) {
broker.add(new Message((Long) row.get("ID"),
(String) row.get("CUSTOMER"), (Integer) row.get("POINTS")));
jdbc.update("UPDATE outbox SET published = TRUE WHERE id = ?",
row.get("ID"));
if (crash) {
throw new IllegalStateException("relay killed before commit");
}
}
});
System.out.println("relay attempt " + attempt + ": committed");
} catch (IllegalStateException e) {
System.out.println("relay attempt " + attempt + ": " + e.getMessage());
}
}
System.out.println("messages on the broker: " + broker);
System.out.println("Consumer without deduplication:");
for (Message m : broker) {
jdbc.update("UPDATE points SET total = total + ? WHERE customer = ?",
m.points(), m.customer());
}
System.out.println(" ada has " + jdbc.queryForObject(
"SELECT total FROM points WHERE customer = 'ada'", Integer.class) + " points");
jdbc.update("UPDATE points SET total = 0");
System.out.println("Consumer that records each message id in the same transaction:");
for (Message m : broker) {
try {
transaction.executeWithoutResult(status -> {
jdbc.update("INSERT INTO processed_messages VALUES (?)", m.id());
jdbc.update("UPDATE points SET total = total + ? WHERE customer = ?",
m.points(), m.customer());
});
System.out.println(" message " + m.id() + ": applied");
} catch (DuplicateKeyException e) {
System.out.println(" message " + m.id() + ": already processed, skipped");
}
}
System.out.println(" ada has " + jdbc.queryForObject(
"SELECT total FROM points WHERE customer = 'ada'", Integer.class) + " points");
}
}
relay attempt 1: relay killed before commit
relay attempt 2: committed
messages on the broker: [Message[id=41, customer=ada, points=50], Message[id=41, customer=ada, points=50]]
Consumer without deduplication:
ada has 100 points
Consumer that records each message id in the same transaction:
message 41: applied
message 41: already processed, skipped
ada has 50 points
- Attempt 1 sent message 41 and then failed before commit, so the
update was rolled back. Attempt 2 found the row unpublished and sent it again: the broker holds message 41 twice.published = TRUE - A consumer that applies every message gave ada 100 points instead of 50.
- The second consumer inserted the message id into
in the same transaction as the points update. The second copy hit the primary key withprocessed_messages , was skipped, and ada ended with 50 points.DuplicateKeyException
No ordering of "send" and "mark" avoids this: marking first and then crashing loses the message instead. Duplicates are the price of never losing one, which is why the outbox and an idempotent consumer are used together. The
Several relays: locking and ordering
Every instance of the service runs the relay, so two or more relays read the same table. Two problems follow: both can publish the same rows, and rows can be published out of order. Here relay A reads a batch of 2 first but is slow to send it, while relay B reads and sends at once:
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.transaction.support.TransactionTemplate;
public class CompetingRelays {
static final String[] EVENTS = {
"order-7 OrderPlaced", "order-7 OrderPaid", "order-7 OrderShipped", "order-8 OrderPlaced"
};
static void run(String db, String label, String select) throws InterruptedException {
String url = "jdbc:h2:mem:" + db + ";DB_CLOSE_DELAY=-1";
DataSource dataSource = new DriverManagerDataSource(url);
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
TransactionTemplate transaction =
new TransactionTemplate(new DataSourceTransactionManager(dataSource));
jdbc.execute("CREATE TABLE outbox (id INT PRIMARY KEY, event VARCHAR(40),"
+ " published BOOLEAN DEFAULT FALSE)");
for (int i = 0; i < EVENTS.length; i++) {
jdbc.update("INSERT INTO outbox (id, event) VALUES (?, ?)", i + 1, EVENTS[i]);
}
List<String> broker = new CopyOnWriteArrayList<>();
CountDownLatch relayAHasRows = new CountDownLatch(1);
CountDownLatch relayBDone = new CountDownLatch(1);
// Relay A reads its batch first, but is slow to send it: it waits for relay B.
Thread relayA = new Thread(() -> transaction.executeWithoutResult(status -> {
List<String> rows = jdbc.queryForList(select, String.class);
relayAHasRows.countDown();
await(relayBDone);
rows.forEach(e -> broker.add("A: " + e));
markPublished(jdbc, rows);
}));
Thread relayB = new Thread(() -> {
await(relayAHasRows);
transaction.executeWithoutResult(status -> {
List<String> rows = jdbc.queryForList(select, String.class);
rows.forEach(e -> broker.add("B: " + e));
markPublished(jdbc, rows);
});
relayBDone.countDown();
});
relayA.start();
relayB.start();
relayA.join();
relayB.join();
System.out.println(label);
broker.forEach(m -> System.out.println(" " + m));
}
static void markPublished(JdbcTemplate jdbc, List<String> events) {
for (String event : events) {
jdbc.update("UPDATE outbox SET published = TRUE WHERE event = ?", event);
}
}
static void await(CountDownLatch latch) {
try {
latch.await();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) throws InterruptedException {
run("plain", "Plain SELECT, batches of 2:", "SELECT event FROM outbox"
+ " WHERE published = FALSE ORDER BY id FETCH FIRST 2 ROWS ONLY");
run("skiplocked", "SELECT ... FOR UPDATE SKIP LOCKED, batches of 2:",
"SELECT event FROM outbox"
+ " WHERE published = FALSE ORDER BY id FETCH FIRST 2 ROWS ONLY"
+ " FOR UPDATE SKIP LOCKED");
}
}
Plain SELECT, batches of 2:
B: order-7 OrderPlaced
B: order-7 OrderPaid
A: order-7 OrderPlaced
A: order-7 OrderPaid
SELECT ... FOR UPDATE SKIP LOCKED, batches of 2:
B: order-7 OrderShipped
B: order-8 OrderPlaced
A: order-7 OrderPlaced
A: order-7 OrderPaid
- With a plain
, both relays read rows 1 and 2, soSELECT andorder-7 OrderPlaced were each published twice. Rows 3 and 4 were left for the next poll.order-7 OrderPaid - With
, relay A's read locked rows 1 and 2, and relay B skipped them and took rows 3 and 4 instead. No row was published twice.FOR UPDATE SKIP LOCKED - But relay B published
before relay A publishedorder-7 OrderShipped . A consumer would see the order shipped before it was placed.order-7 OrderPlaced
SKIP LOCKED
- A single active relay: elect one instance with a lock row or a library such as ShedLock, so only one relay reads the table at a time. This is simple and fast enough for most services.
- Relays split by key: give each relay a share of the aggregates, for example
, so that all events of one order go through the same relay.WHERE MOD(hash, 4) = 2 - Change data capture: Debezium reads the database's transaction log in commit order and publishes each outbox insert, so there is no polling and no competing relays.
Change data capture and ready-made outboxes
A polling relay costs one query every interval, even when the table is empty, and adds up to one interval of latency. Change data capture removes both. Debezium, running in Kafka Connect, reads the PostgreSQL write-ahead log or the MySQL binlog and turns each committed insert into the outbox table into a Kafka message. Its outbox event router reads the aggregate, type and payload columns and routes each row to a topic. That setup needs Kafka Connect and database log access, so it was not run here.
Spring Modulith offers an outbox built on Spring events. Its event publication registry writes one entry per @TransactionalEventListenerspring.modulith.events.republish-outstanding-events-on-restart=true@Externalized
Whichever variant you use, a few rules carry over:
- Payload: store everything consumers need in the row. A relay that reloads the order when it publishes may see a later state than the one the event describes.
- Schema: version the payload, for example with an event version column, because rows written by the old code may still be waiting when the new code is deployed.
- Monitoring: alert on the age of the oldest unpublished row. A stuck relay looks like silence, not like an error.
Choosing how to publish
| Situation | Use |
|---|---|
| Other services must hear about every committed change | Outbox table written in the business transaction |
| Moderate volume, one database you already run | Polling relay with FOR UPDATE SKIP LOCKED |
| Strict per-aggregate order with several relays | Relays split by aggregate key, or change data capture |
| High volume or low latency, Kafka Connect available | Debezium with the outbox event router |
| A modular monolith that already uses Spring events | Spring Modulith's event publication registry |
| A best-effort notification, where an occasional loss is fine | @TransactionalEventListener |
| Consumers of any outbox | Idempotent handling keyed by the message id |
Three rules hold for every variant: the business data and the outbox row are written in one transaction, the relay marks a row only after the broker has confirmed it, and consumers deduplicate because a message can arrive twice. Related pages: