Video in progress

What problem does the outbox pattern solve?

It removes the case of "I wrote to the database but the message wasn't sent" (or the other way around). The event is written to a separate outbox table in the database, in the same transaction as the business data, and then a separate process sends it to the broker.

📖 Answer

The problem: a service has to save an order to the database and send an OrderCreated event to Kafka. These are two different systems with no shared transaction:

  • database first, then Kafka: if the service goes down before sending to Kafka, the event is lost;
  • Kafka first, then database: if the database rolls back, an event goes out about an order that doesn't exist.

With an outbox:

BEGIN;
INSERT INTO orders (id, status, ...) VALUES (...);
INSERT INTO outbox (id, aggregate_id, type, payload, created_at)
       VALUES (..., 'OrderCreated', '{...}', now());
COMMIT;

Both are one local transaction: either both exist or neither does.

Then a "relay" process reads the not-yet-sent rows from outbox, sends them to Kafka and marks them. You can do this with a simple scheduler or with a CDC tool like Debezium (reading from the database WAL).

One catch: if the relay sends but goes down before it can mark the row, the message is sent again. So the outbox gives "at least once", and consumers have to be idempotent.