Video in progress
Why is writing to the database and then sending a message to Kafka (dual write) unreliable, and what options are there besides a transactional outbox?
You can't write atomically to two systems: if the database commits and Kafka fails, the message is lost; in the opposite case, a message goes out about data that isn't in the database. An outbox turns the two into a single database transaction; the alternatives are CDC directly from the table, or making the event the primary source.
📖 Answer
Dual write has two failure cases:
@Transactional
public void place(Order o) {
repo.save(o);
kafka.send("orders", toEvent(o)); // went out before the commit
} // if the commit fails here, there is an event but no order
If you move send to after the commit, you get the opposite problem: the commit happened, the pod died, and there is no event. Kafka transactions don't help here, because they aren't in the same transaction as the database.
Transactional outbox. The event is written to an outbox table in the same transaction as the business data. A relay forwards it to Kafka:
- a polling relay is simple, with
select ... for update skip locked, but adds latency and load on the database; - Debezium CDC reads the WAL and has low latency, but it's one more piece of infrastructure (Kafka Connect) that you have to run and support.
In both cases the guarantee is at-least-once. The consumer must dedup by eventId.
CDC directly from the business table. There is no outbox table; Debezium emits changes of the orders table itself. It's simple, but your internal schema becomes an external contract: if you rename a column, the consumers break. Only for a team's internal integrations.
Event first. The service writes to Kafka first and updates its own database by reading from that topic (close to event sourcing). The atomicity problem goes away, but "reading your own writes immediately" gets harder, and the whole service design changes.
Choosing: for most teams, starting with a polling outbox is right: it's understandable, testable and needs no extra infrastructure. When latency or volume becomes a problem, moving to Debezium is limited to swapping the relay, and the business code doesn't change. Plan the cleanup of the outbox table (partitioning or a regular delete) from the beginning, otherwise it grows to millions of rows.
Sign up to mark studied questions and save your progress.