Video in progress

How do you make sending an event to Kafka reliable alongside a Hibernate transaction? Explain the transactional outbox.

I don't send the event to Kafka directly; I write it to an outbox table in the same transaction. A separate relay (polling or Debezium CDC) reads the outbox and sends to Kafka. That way either both the data and the event are saved, or neither is.

📖 Answer

The typical buggy code:

@Transactional
public void pay(long orderId) {
    order.markPaid();
    kafka.send("order-paid", event); // the transaction has not committed yet
}

The event goes to Kafka, then the commit fails with a constraint error: the event is out and the data is not. Or the other way around: if you send in afterCommit, the commit succeeds and then the pod dies: the data is there and the event is not. You cannot update two systems in a single atomic operation (leaving XA aside, which is hardly used in practice).

The outbox:

@Transactional
public void pay(long orderId) {
    Order order = orders.findById(orderId).orElseThrow();
    order.markPaid();
    outbox.save(new OutboxEvent("Order", orderId, "OrderPaid", toJson(order)));
}

Both the INSERT and the UPDATE are in one database transaction. Then the relay:

  • Polling: select ... from outbox where sent_at is null order by id limit 100 for update skip locked, send, mark. Simple, but it adds load on the database and some latency.
  • CDC (Debezium): reads from the WAL, latency is low, no queries against the database, but the infrastructure is more complex.

Important consequences:

  • delivery is "at-least-once", so the consumer has to be idempotent (dedup by event ID);
  • ordering is only guaranteed within a single aggregate, so make the aggregate ID the partition key;
  • the outbox table has to be cleaned up regularly, otherwise it keeps growing.

One subtle point on the Hibernate side: so the outbox row goes out in the same flush as the entity, convert the event to JSON after the entity's state is final.