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. That is two writes to two systems, the database and a message broker such as Kafka, and no local transaction covers both. Whichever happens second can fail after the first has succeeded:

  • 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 table. A separate relay reads new outbox rows and publishes them to the broker. If the transaction rolls back, there is no message to publish. If the broker is down, the row waits until it is back.

Ways to keep a database and a broker in step
ApproachMessage lost possibleMessage for rolled-back data possibleBest for
Send inside the transactionNoYesNothing; this is the bug
Send after commit, such as with @TransactionalEventListenerYes, on a crash or broker outageNoNotifications where an occasional loss is acceptable
Outbox table and a polling relayNoNoMost services; needs only the database you already have
Outbox table and change data capture (Debezium)NoNoHigh volume, or teams already running Kafka Connect
Two-phase commit (XA)NoNoBrokers 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:

Java
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);
        }
    }
}
Output
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 DataIntegrityViolationException, but OrderPlaced 1 was already on the broker. A broker send cannot be rolled back with the database.
  • 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 [2] and the broker says [OrderPlaced 1]: each system holds the order the other one does not know about.

Moving the send into a @TransactionalEventListener, as the Spring events page shows, fixes case 1 but not case 2. The listener runs after the commit, in memory, and a crash or broker outage at that moment loses the message.

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:

Java
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"));
            });
        }
    }
}
Output
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 published=false. Nothing has gone to a broker yet.
  • 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 aggregate_id column, order-1 and order-2, becomes the message key. Kafka sends all messages with the same key to the same partition, which keeps each order's events in order.

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 method, so that no code path can write one without the other. The @Transactional page explains the rules that decide what is in the transaction.

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 = ...) method; this program calls it by hand so that each poll can be shown. The broker is down for the first poll:

Java
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));
    }
}
Output
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 order-1 OrderPlaced arrived before 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 returns. This version of the loop was not run here, because it needs a Kafka broker:

Java
@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 flag keeps a history but makes the table grow. Delete published rows after a few days with a second scheduled job, or delete each row as soon as it is sent. The Spring scheduling page covers running the relay on a schedule.

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 commits:

Java
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");
    }
}
Output
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 published = TRUE update was rolled back. Attempt 2 found the row unpublished and sent it again: the broker holds message 41 twice.
  • A consumer that applies every message gave ada 100 points instead of 50.
  • The second consumer inserted the message id into processed_messages in the same transaction as the points update. The second copy hit the primary key with DuplicateKeyException, was skipped, and ada ended with 50 points.

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 idempotency page covers consumer deduplication in more depth. Send the outbox row id with each message, for example as a Kafka header, so consumers have a stable id to deduplicate on.

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:

Java
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");
    }
}
Output
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 SELECT, both relays read rows 1 and 2, so order-7 OrderPlaced and order-7 OrderPaid were each published twice. Rows 3 and 4 were left for the next poll.
  • With FOR UPDATE SKIP LOCKED, 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.
  • But relay B published order-7 OrderShipped before relay A published order-7 OrderPlaced. A consumer would see the order shipped before it was placed.

SKIP LOCKED is supported by PostgreSQL, MySQL 8, Oracle and H2 2.x, which is what ran here. To keep the order of each aggregate's events, use one of these:

  • 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 WHERE MOD(hash, 4) = 2, so that all events of one order go through the same relay.
  • 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 @TransactionalEventListener into a table, in the same transaction that publishes the event. It marks the entry complete when the listener succeeds, and it can resubmit incomplete entries after a restart, with spring.modulith.events.republish-outstanding-events-on-restart=true. Event classes annotated with @Externalized are also sent to Kafka, AMQP or JMS. The registry was checked against the Spring Modulith 2.1 reference documentation but not run here.

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

Common situations and the approach that fits them
SituationUse
Other services must hear about every committed changeOutbox table written in the business transaction
Moderate volume, one database you already runPolling relay with FOR UPDATE SKIP LOCKED and a single active instance
Strict per-aggregate order with several relaysRelays split by aggregate key, or change data capture
High volume or low latency, Kafka Connect availableDebezium with the outbox event router
A modular monolith that already uses Spring eventsSpring Modulith's event publication registry
A best-effort notification, where an occasional loss is fine@TransactionalEventListener sending after commit
Consumers of any outboxIdempotent 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: idempotency, saga choreography, which builds on outbox events, and KafkaTemplate for the sending side.