Transactional outbox: events without loss or duplicates
The service saved the order and sent an event to Kafka. The process can crash between those two actions: the order exists, the event does not. Or the other way around: the event went out but the transaction rolled back. The outbox removes that fork.
The dual-write problem
There are two systems: a database and a broker. There is no atomic write to both (well, distributed transactions exist, but few people want to operate them). "DB first, then Kafka" leaves a window for loss, and "Kafka first, then DB" leaves a window for a phantom event.
The outbox moves the event into the same transaction as the data change:
BEGIN;
INSERT INTO orders (id, total) VALUES (7781, 1200);
INSERT INTO outbox (id, type, payload)
VALUES ('evt-7781', 'order.created', '{"order_id": 7781}');
COMMIT;
Either both the order and the event exist, or neither does. Publishing becomes a separate step.
The publisher
A background process reads unpublished rows and sends them:
SELECT id, type, payload, attempts
FROM outbox
WHERE published_at IS NULL AND dead_at IS NULL
ORDER BY id
LIMIT 100;
After a successful send it sets published_at. After an error it increments
attempts and stores the error text. After max_attempts it moves the row to
the dead-letter.
The publisher can run in several instances if the selection and the mark are
atomic: SELECT ... FOR UPDATE SKIP LOCKED in PostgreSQL or an equivalent
mechanism. Otherwise two processes will send the same event twice.
At-least-once is fine
The publisher can crash after sending but before published_at. The event
stays in the outbox and goes out again. The outbox gives you at-least-once,
not exactly-once. That is not a bug: exactly-once between a DB and a broker is
expensive, and in practice it is enough to make the retry safe.
The idempotency key is event_id. It is generated once when the row is
written to the outbox and does not change between attempts. If you generate a
new id on every retry, deduplication becomes impossible: to the consumer these
are two different events.
The idempotent consumer
A stable id alone is not enough. The consumer must be able to recognise a repeat and avoid a second side effect. Options:
- a
processed_events(event_id PRIMARY KEY)table; the insert happens in the same transaction as the business change, and a key conflict means "already processed"; - a unique index on a business key, for example
(order_id, event_type); - an upsert instead of an insert if the operation is naturally idempotent.
A "have I seen this before?" check as a separate query without a unique index does not work: two consumers will pass the check at the same time and create two effects. You need atomicity at the database level.
Dead-letter and retries
Endless retries block the queue and burn resources. After max_attempts the
event goes to the dead-letter: someone handles it manually or replays it once
the cause is fixed. Make sure dead-letter events are excluded from the pending
selection, otherwise every pass will try to send them again.
Retries should have a delay and a ceiling. An instant loop of three attempts will not survive a broker outage longer than a second.
What to test
- a failed outbox write rolls back the order;
- the publisher sends pending rows in insertion order;
- a crash after sending leads to a retry with the same
event_id; - the broker/consumer deduplicates the repeat, and the side effect happens once;
- after
max_attemptsthe event goes to the dead-letter and is no longer selected; - the
limitdoes not lose the remaining events; - a programmer error in the publisher is not masked as a retryable failure.
Common mistakes
- Publishing inside the DB transaction: the network cannot be rolled back, and locks are held for too long.
- Generating
event_idon every attempt. - Relying only on in-memory dedup in the consumer: it is empty after a restart.
- Deleting the outbox row right after sending: then you have no proof of publication and nothing to retry.
- Treating the outbox as a replacement for idempotency. The outbox guarantees delivery; idempotency ensures correct processing.