Scrivio Interview library
DesignIntermediate7 min read · updated 12 November 2026

Order service must publish OrderPlaced to Kafka whenever an order is saved, with no lost or phantom events. Design this.

Writing the order to the database and then sending to Kafka is a dual write: a crash between the two either loses the event or, if we send first, publishes an event for an order that was never saved. The fix is a transactional outbox: insert the OrderPlaced event into an outbox table in the same database transaction as the order, and let a relay publish outbox rows to Kafka, by polling or with change data capture such as Debezium, and mark them sent. Delivery is then at least once, so consumers must be idempotent, and each event carries an id, type, version and timestamp with a compatibly evolving schema; Spring Modulith's event publication registry is another option.

Why this question is asked

Almost every event-driven system meets this problem early. The first version calls kafkaTemplate.send() right after repository.save(), it works in testing, and months later someone notices orders that never reached the warehouse, or a shipment for an order that does not exist. Interviewers ask this design question because it tests whether we understand that two separate systems cannot be updated atomically, and whether we know the standard pattern that solves it. In this answer, we will see exactly how dual writes fail, build the outbox, compare polling and CDC relays, make consumers idempotent, design the event envelope, and look at Spring Modulith as an alternative.

1Why a Dual Write Fails

A dual write is any code path that updates two systems, here PostgreSQL and Kafka, as two separate steps. There is no transaction that spans both, so a crash, a timeout or a deploy between the steps leaves them disagreeing.

Java
@Transactional
public void placeOrder(Order order) {
orders.save(order);
kafka.send("orders", new OrderPlaced(order.id(), ...)); // inside the DB transaction
}
// Case 1: send succeeds, then commit fails -> phantom event for an order that does not exist
// Case 2: commit succeeds, then the process dies before or during send -> lost event
// Case 3: send after commit, Kafka is down -> lost event unless we retry forever

Reordering the steps only changes which failure we get. Kafka transactions do not help either, because they make writes to several Kafka partitions atomic with each other, not with a database commit. So we need a design where only one system is written in the business transaction.

2The Transactional Outbox

The outbox pattern makes the database the only thing we write to in the business transaction. Alongside the order, we insert a row describing the event into an outbox table. Because both inserts are in one local database transaction, they commit or roll back together: if the order exists, its event exists, and if the order was rolled back, so was its event.

Java
CREATE TABLE outbox (
id uuid PRIMARY KEY,
aggregate_id text NOT NULL, -- becomes the Kafka key, keeps per-order ordering
type text NOT NULL, -- OrderPlaced
version int NOT NULL, -- schema version of the payload
payload jsonb NOT NULL,
occurred_at timestamptz NOT NULL,
sent_at timestamptz -- null until the relay publishes it
);
@Transactional
public void placeOrder(Order order) {
orders.save(order);
outbox.save(OutboxRow.of(UUID.randomUUID(), order.id(), "OrderPlaced", 1, json(order), clock.instant()));
} // one commit: order and event together, or neither

Notice that nothing talks to Kafka here. The business transaction is fast and does not depend on Kafka being available.

3Relaying Outbox Rows to Kafka

A separate relay moves events from the outbox to Kafka. There are two common ways to build it. A polling relay is a scheduled job that selects unsent rows in order, publishes them, waits for Kafka's acknowledgement and marks them sent. It is simple and needs no extra infrastructure, but it adds a polling delay and load on the table, and with several instances it needs SELECT ... FOR UPDATE SKIP LOCKED or a single active instance.

A change data capture relay reads the database's transaction log instead. Debezium, running in Kafka Connect, sees each committed insert into the outbox table and publishes it, and its outbox event router can pick the topic, key and payload from the row's columns. It has low latency and no polling load, at the cost of running and monitoring Debezium. With CDC, the outbox rows can simply be deleted after a while, since the log is what is read.

Step throughOrder, outbox and relay
Order serviceDatabaseRelayKafka
BEGIN; insert order; insert outbox row; COMMIT
read new outbox rows (poll or log)
publish OrderPlaced, key = order id
ack
mark row sent
after a crash: publish the same row again

6 messages in order. Play them, or step through them one at a time.

If the relay crashes after publishing but before marking sent, the event is published twice.

4At-Least-Once Delivery and Idempotent Consumers

Look at the last step in the diagram. If the relay publishes the event and crashes before marking the row sent, it will publish it again on restart. That is the price of never losing an event: delivery is at least once, so duplicates are possible, and consumers must be idempotent, meaning that processing the same event twice has the same effect as processing it once.

Java
@KafkaListener(topics = "orders")
@Transactional
public void on(OrderPlacedMessage m) {
if (processed.existsById(m.eventId())) return; // seen before: skip
inventory.reserve(m.orderId(), m.lines());
processed.save(new ProcessedEvent(m.eventId(), clock.instant())); // same transaction as the effect
}

Recording the event id in the same transaction as the effect makes the check reliable. Some effects are naturally idempotent, such as setting a status to SHIPPED, and need no table. Notice also that using the order id as the Kafka key keeps all events for one order in one partition, so they arrive in order.

5Designing the Event Envelope

Each event should carry a unique event id, used for idempotency; a type, such as OrderPlaced; a schema version; and the time it occurred. Kafka record headers are a good place for these, with the payload in the value. The payload holds the business facts, such as the order id, customer id, total and lines, and should be evolved compatibly: adding optional fields is safe, while removing or renaming fields is a breaking change that needs a new version or a new event type. A schema registry with Avro, Protobuf or JSON Schema can check compatibility automatically on every change.

6Spring Modulith as an Alternative

Spring Modulith offers an event publication registry that implements much of this for in-application events. When a Spring application event is published inside a transaction and has transactional listeners, Modulith stores a publication record in an event_publication table in the same transaction, marks it complete when the listener succeeds, and can resubmit incomplete ones after a restart. Its externalization support can forward events annotated with @Externalized to Kafka. It is a good fit for a modular monolith or a single service already using Modulith; a dedicated outbox with Debezium gives more control at larger scale. Check the Modulith version for the exact configuration properties.

7Follow-up questions

Why not just retry the Kafka send until it works?

Retrying covers a Kafka outage while the process is alive, but not a crash, a deploy or a kill. The retry state is in memory and is lost with the process. The outbox keeps the pending event in the database, which survives restarts.

Does the outbox guarantee ordering?

Per aggregate, yes, if the relay publishes rows in commit order and uses the aggregate id as the Kafka key. Across aggregates, ordering is not guaranteed and usually not needed. A polling relay must be careful with rows committed out of id order; CDC follows the log order naturally.

How do you keep the outbox table from growing forever?

Delete or archive sent rows on a schedule, for example after seven days, or partition the table by day and drop old partitions. With Debezium, rows can be deleted right after insert in the same transaction, since the log already holds the change.

8Conclusion

In this answer, we saw that saving an order and sending to Kafka separately is a dual write, where a crash between the steps loses an event or publishes a phantom one. The transactional outbox fixes this by inserting the event into an outbox table in the same transaction as the order, and a relay, polling or change data capture with Debezium, publishes outbox rows to Kafka and marks them sent. Delivery is at least once, so consumers are idempotent by tracking event ids, and events carry an id, type, version and timestamp with compatible schema evolution. Spring Modulith's event publication registry is another option for in-application events.

What to say in the interviewAbout 100 seconds aloud

Open with

The core problem is that writing the order to the database and then sending OrderPlaced to Kafka is a dual write. There is no transaction across both, so if the process dies after the commit but before the send, the event is lost, and if I send inside the transaction and the commit then fails, I have published a phantom event.

Then, if they want more

Reordering just swaps which failure I get, and Kafka transactions do not include the database. So I would use a transactional outbox. In the same local transaction that inserts the order, I insert a row into an outbox table with an event id, the order id, the type, a schema version, the payload and a timestamp.

Now the order and its event commit or roll back together. A separate relay publishes those rows to Kafka. It can be a polling job using SKIP LOCKED that publishes, waits for the ack and marks the row sent, or change data capture with Debezium and its outbox router, which reads the log with low latency.

I use the order id as the key so events for one order stay in order. If the relay crashes after publishing but before marking sent, it will publish again, so delivery is at least once and consumers must be idempotent, typically by storing processed event ids in the same transaction as their effect.

I would evolve the payload compatibly, ideally checked by a schema registry. And inside a Spring Modulith application, its event publication registry and externalization to Kafka can do much of this for me.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Order service must publish OrderPlaced to Kafka whenever an order is saved, with no lost...": https://scrivio-interview-library.netlify.app/java/domain-driven-design/b5b15a404a/