Video in progress

Strong Middle 📨 Kafka and messaging

What's wrong with code that writes to the database and then sends an event to Kafka, and how does the outbox pattern fix it?

@Transactional
public void placeOrder(OrderRequest req) {
    Order order = orderRepository.save(Order.from(req));
    kafkaTemplate.send("orders", order.getId().toString(),
                       new OrderPlaced(order.getId(), order.getTotal()));
}

This is a "dual write": if the DB commits and sending to Kafka fails, the event is lost; if you swap the order, the event goes out and the DB rolls back. With an outbox, the event is written to a table in the same DB transaction, and a separate process delivers it to Kafka.

📖 Answer

This code has several hidden problems:

  • send is asynchronous: by the time the @Transactional method returns, the message may not have been sent yet; the commit succeeds, the broker doesn't, and the event is lost;
  • the other way around: the message goes out, then the commit fails (say, a constraint error), and consumers learn about an order that doesn't exist.

The outbox version:

@Transactional
public void placeOrder(OrderRequest req) {
    Order order = orderRepository.save(Order.from(req));
    outboxRepository.save(new OutboxEvent(
        UUID.randomUUID(), "orders", order.getId().toString(),
        json(new OrderPlaced(order.getId(), order.getTotal()))));
}

The order and the event are in one transaction: either both exist or neither does.

There are two ways to deliver from the outbox to Kafka:

  1. Polling relay: a scheduler picks up the unsent rows with select ... for update skip locked, sends them and marks them. Simple, but it adds load on the DB and a delay of seconds.
  2. CDC: Debezium reads the DB log (Postgres WAL, MySQL binlog) and publishes the outbox rows to Kafka. Low latency, but you add infrastructure.

In both cases delivery is at-least-once, so consumers must be idempotent using the event ID.