Publish events reliably with the write
Writing to the database and publishing to Kafka are two steps; one can succeed without the other.
Say it like this
A database commit and a Kafka publish cannot share a transaction, so I write the event into an outbox table in the same transaction as the row and let a relay publish it; the event is then exactly as durable as the data.
Basic solution
Write the event into an outbox table in the same transaction; a relay reads the outbox and publishes (transactional outbox).
One transaction, then a relay
The row and the outbox entry commit together. The relay reads the outbox and publishes; a crash after publish simply republishes, so consumers dedupe on the event id.
How it works
- The service opens a database transaction, writes the business row (the order, the post), and in the same transaction inserts a row into an outbox table: an event id, an event type, the payload, and created_at. Both inserts are part of one unit of work.
- The transaction commits. Either both rows exist or neither does, because that is what a transaction guarantees; there is no state in which the order exists but its event does not.
- A separate relay process reads outbox rows that have not been published yet, in id order, publishes each one to the broker, and once the broker acknowledges it, marks the row published (or deletes it).
- If the relay crashes after the broker accepted the event but before it marked the row, the row is still unpublished on restart, so the relay publishes it again. Consumers must therefore dedupe on the event id; the relay is at-least-once by design.
- The relay is either a poller that runs SELECT ... WHERE published = false ORDER BY id LIMIT 100 every few hundred milliseconds, or a change-data-capture connector that tails the database's own log and sees outbox inserts as they commit, which removes polling and its latency.
Why not publish first, then write
- A publish that succeeds followed by a commit that fails announces an order that never happened; writing first and publishing second fails the other way, with an order nobody hears about. Changing the order of the two steps moves the problem; only putting both in one transaction removes it.
Worked example
Notification intake
- 2,900 inserts/s average into notifications, each with one outbox row. Outbox grows at 2,900 rows/s × 500 B ≈ 1.5 MB/s; deleted after publish, so steady-state size is relay lag × rate.
- Poller: 10 relays, each claiming 500 rows with FOR UPDATE SKIP LOCKED every 100 ms, gives 50K rows/s of capacity, well above the write rate.
- End-to-end latency added: 50–100 ms average with polling, under 10 ms with Debezium reading the write-ahead log.
- With CDC the relay is a Kafka Connect task; the outbox table is the only thing Debezium is configured to watch, so other tables do not leak into the topic.
- Cost of skipping the outbox: at 2,900/s even a 0.01% failure between commit and publish is 25,000 lost notifications a day, each one a support ticket.
Variants and when each wins
Polling relay
- A worker periodically selects unpublished rows, publishes them, and marks them. It wins for its simplicity and because it works on any database; it adds polling latency and a little load, and parallel relays need SKIP LOCKED so they do not claim the same rows.
CDC relay (Debezium outbox event router)
- A connector tails the database log and emits each outbox insert as an event the moment it commits. It wins on latency (no polling) and load, but it is another component to operate and needs logical replication enabled on the database.
Listen / notify trigger
- An insert into the outbox fires Postgres NOTIFY, which wakes the relay immediately, so polling can be slow but reaction is instant. It wins as a middle ground when you want low latency without a CDC connector.
Dual write with reconciliation
- The service writes the row and publishes the event as two separate steps, and a periodic job compares the two and republishes anything missing. It wins only on per-request simplicity; the gap between the two steps can be as long as the reconciliation interval.
Use polling with SKIP LOCKED until the rate justifies CDC; never rely on dual write for events that drive money or user-visible state.
Failure modes
Outbox table bloat
- Inserts into the main table slow down over weeks, and the outbox is the biggest table in the database. It happens because published rows were never deleted, or constant updates to the published flag left dead row versions behind. Delete rows after publishing, in batches, or partition the outbox by day and drop whole partitions; vacuum aggressively.
Relay lag spikes
- Events arrive seconds or minutes after the write. It happens because the broker is slow to acknowledge, or the relay process died and nobody noticed, so rows pile up unpublished. Alert on the age of the oldest unpublished row, and run at least two relays so one dying is not an outage.
Out-of-order publish with parallel relays
- A consumer receives the update event for an order before its create event. It happens because two relays claimed adjacent rows and published them in different order. Give each relay its own slice of the data, by partitioning the outbox by aggregate id, so all rows for one order go through one relay in order.
Duplicate events
- A consumer processes the same event id twice. It happens because the relay crashed between the broker accepting the event and the relay marking the row, so it published the row again on restart. This is by design: consumers dedupe on the event id, and the relay never tries to be exactly-once.
Payload too large
- Outbox inserts fail, or the broker rejects messages for size. It happens because the event payload carries a full snapshot of the entity. Put ids and the changed fields in the event; consumers that need more fetch the entity by id.
Interviewer follow-ups
Answer out loud before you open each one.
Why not use a distributed transaction across the database and Kafka?
Two-phase commit across heterogeneous systems is slow, blocks while the coordinator is down, and Kafka transactions do not participate in XA anyway. The outbox gets the same guarantee with one local transaction and an idempotent relay.
How does the consumer deal with the at-least-once relay?
Every event carries the outbox row id as its event id. The consumer records processed ids (or makes its handler naturally idempotent) and skips repeats. The relay never tries to be exactly-once; the consumer makes the effect exactly-once.
How do you keep ordering for one aggregate?
Partition the topic by aggregate id and make sure the relay publishes rows for one aggregate in outbox id order. With parallel relays, assign each relay a range of aggregate hashes rather than letting them race for rows.
What does the outbox look like with CDC on the main table instead?
You can skip the outbox and let Debezium stream row changes from the business tables directly. You lose control of the event shape and leak schema details to consumers, which is why teams keep the outbox even with CDC: the outbox row is the public contract.
Connections
- In study paths
- Decoupling with events
- Pairs with
- React to database changes · Fan one event out to many consumers · Keep events as a replayable log · Make retries safe · Coordinate a multi-service transaction
- Pulls against
- Commit across two stores
- Used in
- Notification System
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon EC2 Auto Scaling | Notification API, Relay | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Aurora | Postgres | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |
| Amazon MSK (Kafka) | Topic: notifications | Managed Service for Apache Kafka | Event Hubs (Kafka API) | Confluent Cloud, Redpanda |