The outbox pattern and change data capture
Update your database and publish an event without ever doing one and not the other.
15 min readThe dual-write problem
A service saves an order and then publishes OrderPlaced to the broker. If it crashes between the two, the order exists but nobody downstream hears about it: no payment, no email. Reverse the order and a failed database write leaves an event announcing an order that does not exist. Retrying does not fix this, and distributed transactions across a database and a broker (two-phase commit) are rarely available and slow when they are. Any design that writes to two systems separately will eventually leave them disagreeing.
The transactional outbox
Write the event into an outbox table in the same database transaction as the business change. Either both commit or neither does. A separate relay process reads unpublished outbox rows in order, publishes them to the broker, and marks them sent. If the relay crashes after publishing but before marking, it publishes again on restart, so the outbox gives at-least-once delivery and consumers must be idempotent. Delete or archive sent rows on a schedule so the table stays small.
Change data capture
Databases already keep an ordered log of every committed change for replication: the Postgres write-ahead log, the MySQL binlog. Change data capture (CDC) tools such as Debezium read that log and publish each change as an event, with latency in the tens of milliseconds and no polling queries against your tables. Pointing CDC at the outbox table is the most common combination: transactional safety from the outbox, low latency from the log.
Choosing between them
Both approaches work; they differ in operations and coupling.
- A polling relay is simple to build, but adds up to one poll interval of latency and steady query load
- CDC is fast and efficient, but adds a connector to run and depends on replication slots that can fill disk if the connector stalls
- Publishing raw table changes couples every consumer to your schema; publish deliberate outbox events as a stable contract instead
- CDC is also a good way to keep caches, search indexes and warehouses in sync with a database you cannot change
Key takeaways
- Writing to a database and a broker separately will eventually lose or invent events
- The outbox makes the event part of the same transaction as the change
- CDC streams committed changes from the database log with low latency
- Publish intentional events, not raw tables, to keep consumers decoupled from your schema
Sign in to track lessons and earn badges.