A common requirement: when something changes in the database, tell other systems about it. The obvious code updates the row and then publishes an event to a broker such as Kafka. It looks fine and fails in production, because those two actions are not atomic.
The dual-write problem
There is no transaction that covers both the database and the broker, so any ordering leaves a gap.
- Commit first, then publish. If the process dies or the broker is down after the commit, the data changed but the event was never sent. Other systems stay out of date, and nothing records that anything is missing.
- Publish first, then commit. If the commit fails or rolls back, you sent an event about a change that never happened.
Retrying does not close the gap, because the process that would retry may be the one that crashed. The reliable fix is to put both facts in the database, in one transaction, and let a separate process deliver the event.
The outbox table
Alongside the business change, insert a row into an outbox table describing the event. Both writes commit or roll back together.
START TRANSACTION;
UPDATE wallets SET balance = balance + 100000 WHERE id = 1;
INSERT INTO ledger_entries (txn_id, wallet_id, amount, created_at)
VALUES (3001, 1, 100000, CURRENT_TIMESTAMP(3));
INSERT INTO outbox (id, aggregate_id, event_type, payload, created_at)
VALUES ('0b9f3c1e-0000-4000-8000-000000000001', 1, 'TopupCompleted',
'{"wallet_id":1,"amount":100000}', CURRENT_TIMESTAMP(3));
COMMIT;If anything fails, nothing is committed, so there is no event without a change and no change without an event. The event is now durable data waiting to be delivered.
Delivering the events
A separate relay reads the outbox and publishes to the broker. There are two common designs.
- Polling publisher. A loop selects unsent rows in order, publishes them and marks them sent. It is simple and needs no extra infrastructure, at the cost of some latency and extra queries on the database.
- Change data capture. A tool such as Debezium reads the MySQL binary log and streams inserts into the outbox table to Kafka. Latency is low and the application database sees no polling load, but you operate more infrastructure and need row-based binary logging.
-- polling relay: claim a batch without blocking other relays
START TRANSACTION;
SELECT id, event_type, payload FROM outbox
WHERE published_at IS NULL ORDER BY created_at LIMIT 100
FOR UPDATE SKIP LOCKED;
-- publish to the broker, then:
UPDATE outbox SET published_at = CURRENT_TIMESTAMP(3) WHERE id IN (...);
COMMIT;SKIP LOCKED, available from MySQL 8.0.1, lets several relay instances work on different rows without waiting for each other.
At-least-once, so consumers must be idempotent
If the relay publishes a message and crashes before marking it sent, it will publish it again after restart. The outbox pattern therefore gives at-least-once delivery. Give every event a unique id and make consumers idempotent, using the processed-events technique from the previous articles. Ordering is only guaranteed per key: publish with the aggregate id as the message key so events for one wallet stay in order on one partition.
Housekeeping
- Delete or archive sent rows regularly, or the outbox table grows without limit. Deleting in small batches or partitioning by time keeps it cheap.
- Index the table for the relay query, on the unsent flag and creation time.
- Alert on the age of the oldest unsent row. That number is the health metric of the pipeline.
- Keep payloads small and versioned, so consumers can evolve.
Takeaway
Never rely on a database write and a broker publish happening together. Record the event in an outbox table in the same transaction as the change, deliver it with a polling relay or CDC, accept at-least-once delivery and make consumers idempotent.
Comments