Video in progress
How do you make saving an order to the DB and sending an event to Kafka a single atomic unit?
You can't write to two different systems in one transaction. With the outbox pattern, the event is written to an outbox table in the same DB transaction as the order, and a separate relay reads it and sends it to Kafka.
📖 Answer
The naive code:
@Transactional
public void placeOrder(Order o) {
orderRepo.save(o);
kafka.send("orders", new OrderPlaced(o.getId()));
}
It breaks in two ways. The message went to Kafka and then the commit failed — there's an event but no order. Or the commit succeeded and the service died before sending to Kafka — there's an order but no event, and the warehouse doesn't know.
Outbox:
CREATE TABLE outbox (
id uuid PRIMARY KEY,
aggregate_id bigint NOT NULL,
type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
sent_at timestamptz
);
@Transactional
public void placeOrder(Order o) {
orderRepo.save(o);
outboxRepo.save(OutboxEvent.of("OrderPlaced", o.getId(), toJson(o)));
}
Now either both exist or neither does.
Sending works in two ways:
- Polling relay — a scheduler picks up the
sent_at IS NULLrecords every N ms (withFOR UPDATE SKIP LOCKED, so several instances don't get in each other's way), sends them to Kafka and marks them. - CDC — Debezium reads the rows added to the outbox from the PostgreSQL WAL and publishes them to Kafka. Latency is low and it doesn't load the DB with queries, but it adds infrastructure.
With both, delivery is at-least-once: if a message was sent to Kafka but sent_at wasn't marked, the event goes out again. So consumers have to be idempotent. If you set aggregate_id as the partition key, the events of one order go out in order.
Sign up to mark studied questions and save your progress.