Video in progress

Senior 🌱 Spring

You need to send an event to Kafka after an order is saved. How do you guarantee in Spring that both happen?

There is no shared transaction between the database and Kafka, so if you do "save, then send", sooner or later one of them gets lost. The solution is a transactional outbox: the event is written to an outbox table in the same DB transaction, and a separate process sends it to Kafka and marks it. Consumers must tolerate duplicates.

📖 Answer

Here is the problem:

@Transactional
public void place(Order o) {
    orders.save(o);
    kafka.send("orders", toEvent(o)); // sent, then the commit fails -> phantom event
}                                     // or the commit succeeds, then the app dies -> no event

With an outbox:

@Transactional
public void place(Order o) {
    orders.save(o);
    outbox.save(new OutboxRecord("Order", o.getId(), "OrderPlaced", json(o))); // one transaction
}
@Scheduled(fixedDelay = 500)
@Transactional
public void relay() {
    List<OutboxRecord> batch = outbox.lockNextBatch(100); // SELECT ... FOR UPDATE SKIP LOCKED
    for (OutboxRecord r : batch) {
        kafka.send("orders", r.aggregateId().toString(), r.payload()).get(); // the key preserves ordering
        r.markSent();
    }
}

Things to watch:

  • This is at-least-once. If it went to Kafka but markSent didn't commit, the event is sent again. The consumer has to recognize duplicates by event id.
  • For ordering, events of one aggregate should land in the same partition, with the aggregate id as the key.
  • SKIP LOCKED lets several pods work in parallel.
  • Delete the sent rows after a while, otherwise the table grows forever.

At high volume, CDC (Debezium) reads the WAL instead of polling: low latency and no polling load on the database, but the infrastructure gets more complicated.