Video in progress

You need to write data to the database and send an event to Kafka. How do you solve the dual write problem?

Writing to the database and sending to the broker is not one atomic operation: one can succeed while the other fails. With the transactional outbox, the event is written to an outbox table in the same DB transaction as the business data, and then a separate process (a poller or CDC) delivers it to Kafka.

📖 Answer

The naive code breaks in two ways:

@Transactional
public void placeOrder(Order o) {
    repo.save(o);
    kafka.send("orders", toEvent(o)); // 1) it was sent, then the commit failed -> a phantom event
}                                     // 2) the commit went through, send failed -> the event is lost

The outbox:

@Transactional
public void placeOrder(Order o) {
    repo.save(o);
    outboxRepo.save(new OutboxEvent("Order", o.getId(), "OrderPlaced", toJson(o)));
}
CREATE TABLE outbox (
    id            bigserial PRIMARY KEY,
    aggregate_id  bigint NOT NULL,
    type          text NOT NULL,
    payload       jsonb NOT NULL,
    created_at    timestamptz NOT NULL DEFAULT now(),
    published_at  timestamptz
);

There are two ways to deliver:

  • Poller: SELECT ... WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED, send, mark. Simple, but it puts constant load on the DB and adds latency (the poll interval).
  • CDC (Debezium): reads the WAL and passes the outbox inserts to Kafka. Latency is small and there are no queries against the DB, but the infrastructure is more complex and the replication slot needs watching: a stalled slot fills the primary's disk with WAL.

The guarantee is "at-least-once": an event may be delivered twice (sent, then crashed before marking). So the consumer must be idempotent: a dedup table by event id, or a naturally idempotent operation.

Ordering: if events of one aggregate must be in order, use the Kafka key = aggregate_id and match the poller's parallelism to it. Cleaning the outbox table regularly is part of the plan too.