Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

An order service writes the order row to PostgreSQL in a @Transactional method and then publishes an OrderCreated event to Kafka inside the same method. In production some events refer to orders that do not exist, and some orders never get an event. Explain why ACID does not help here and how you would fix it.

ACID only covers the PostgreSQL transaction; the Kafka send happens outside it, so the two writes are not atomic together. This is the dual write problem: an event without an order appears when the send succeeds and the database transaction then rolls back, and an order without an event appears when the commit succeeds and the send fails or the process crashes. The fix is the transactional outbox: insert the event into an outbox table in the same transaction as the order, then relay it to Kafka with a poller or CDC such as Debezium, with idempotent consumers because delivery is at least once.

Why this question is asked

Writing to a database and publishing an event in the same method is one of the most common patterns in microservices, and one of the most common sources of quietly inconsistent data. The bug is rare enough to escape testing and frequent enough to hurt in production. Interviewers ask about it because the fix shows whether we understand where a transaction's guarantees stop. In this answer, we will look at the code, see the two failure modes, explain why ACID cannot help, build the outbox, look at partial fixes and XA, and handle deduplication and broker outages.

1The Code and Its Two Failure Modes

Here is the method as described. It looks atomic because it is annotated with @Transactional.

Java
@Transactional
public Order createOrder(NewOrder cmd) {
Order order = orderRepository.save(Order.from(cmd)); // inside the DB transaction
kafkaTemplate.send("orders", order.getId().toString(),
new OrderCreated(order.getId())); // NOT inside it
return order;
} // commit happens here, after the send
Step throughTwo ways the writes come apart
Order servicePostgreSQLKafka
INSERT order (transaction open)
send OrderCreated
ack: event is published
COMMIT fails -> rollback
order does not exist; event already out
next request: INSERT + COMMIT ok
process crashes before the send

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

Case one leaves an event without an order; case two leaves an order without an event.

Notice the order of events. The send runs before the method returns, and the database commits only after the method returns. So there are two windows. If the send succeeds and the commit then fails, because of a constraint checked at flush, a deadlock or a lost connection, Kafka holds an OrderCreated for an order that was rolled back: an event without an order. If the commit succeeds but the send failed, or the process crashed between the two, the order exists and no event was ever published: an order without an event. Even moving the send after the commit only removes the first window.

2Why ACID Does Not Help

ACID properties are guarantees of one database's transaction. Atomicity says that the statements inside that transaction commit or roll back together. Kafka is a different system with its own storage and acknowledgements, and the database knows nothing about it, so a send is not a statement inside the transaction and cannot be rolled back with it. Two separate systems, written one after the other, with no shared commit, can always fail in between. That is the definition of the dual write problem, and no isolation level or annotation changes it.

3The Fix: A Transactional Outbox

The trick is to turn two writes into one. Instead of sending to Kafka, the service inserts the event into an outbox table in the same database transaction as the order. Now atomicity does apply: either both the order and its event row are committed, or neither is.

SQL
CREATE TABLE outbox (
id uuid PRIMARY KEY, aggregate_id text NOT NULL, type text NOT NULL,
payload jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(), sent_at timestamptz);
@Transactional
public Order createOrder(NewOrder cmd) {
Order order = orderRepository.save(Order.from(cmd));
outboxRepository.save(OutboxEvent.of(order.getId(), "OrderCreated", toJson(order)));
return order; // one commit covers both rows
}

A separate relay then moves outbox rows to Kafka. There are two common ways. A poller reads unsent rows, for example with SELECT ... ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED so several relay instances do not take the same rows, publishes them and marks them sent. Change data capture, CDC, uses a tool such as Debezium that reads the database's write-ahead log and publishes new outbox rows as they commit, without polling. Debezium has an outbox event router built for exactly this table shape.

The relay can still crash after publishing and before marking a row sent, so it will publish that event again on restart. Delivery is therefore at least once, never exactly once, and consumers must be idempotent: processing the same event twice must have the same effect as processing it once. The outbox also gives ordering per aggregate if the relay publishes in commit order and uses the order id as the Kafka key, so all events for one order land in one partition.

4Partial Fixes and Why They Are Not Enough

Spring offers ways to send after the commit: a TransactionSynchronization with afterCommit, or @TransactionalEventListener(phase = AFTER_COMMIT) reacting to an application event. These remove the first failure mode, because nothing is sent unless the commit succeeded. But the second remains: if the process crashes, or Kafka is unreachable, after the commit and before or during the send, the event is lost, and nothing records that it was ever owed. They narrow the window; they do not close it.

Distributed transactions with XA and two-phase commit are the classic theoretical answer for atomic writes across systems. In practice Kafka does not take part in XA transactions; Kafka's own transactions cover writes to Kafka, not to an external database. XA also brings a coordinator that can fail while participants hold locks, which is a new failure mode. So the outbox, built only on a local transaction, is the standard answer.

5Follow-up questions

How would consumers deduplicate?

Each event carries a unique id, the outbox row's id. The consumer records processed ids in a table with a unique constraint, in the same database transaction as the effect of the event. If inserting the id fails because it already exists, the event was processed before and the consumer skips it. Alternatively, the effect itself can be naturally idempotent, such as an upsert keyed by order id.

What does the relay do when Kafka is down for an hour?

Nothing is lost. Orders keep committing with their outbox rows, which simply accumulate. The relay retries with backoff, and when Kafka returns it drains the backlog in commit order, so consumers see a delay but no gaps. We monitor outbox lag, the age of the oldest unsent row, alert when it grows, make sure the table and the relay can handle an hour of backlog, and clean up sent rows regularly so the table stays small.

Does the outbox table need cleanup?

Yes. Sent rows are deleted or moved by a scheduled job, or partitioned by day and dropped, otherwise the table grows forever and polling slows down. With Debezium, rows can even be deleted in the same transaction they were inserted, since CDC reads the insert from the log.

6Conclusion

In this answer, we saw that a @Transactional method that also sends to Kafka performs two separate writes, and ACID only covers the database one. Depending on where it fails, we get an event without an order or an order without an event, the dual write problem. Sending after commit narrows the window but still loses events on a crash, and XA is not available with Kafka. The transactional outbox writes the event in the same local transaction and relays it with a poller or Debezium, giving at-least-once delivery that idempotent consumers handle safely.

What to say in the interviewAbout 100 seconds aloud

Open with

ACID only covers the PostgreSQL transaction. kafkaTemplate.send is a write to a different system, so it is not part of the transaction and is not rolled back with it, and the database commit only happens when the method returns, after the send.

Then, if they want more

That gives two failures. If the send succeeds and the commit then fails, we have an event for an order that does not exist. If the commit succeeds but the send fails or the process crashes in between, we have an order with no event. That is the dual write problem.

Moving the send to afterCommit, or using TransactionalEventListener with AFTER_COMMIT, removes the first case but still loses events if we crash after the commit. XA two-phase commit is not an option because Kafka does not participate in XA, and it would add coordinator failures anyway.

The fix I would use is the transactional outbox: in the same transaction as the order, insert an OrderCreated row into an outbox table, so both commit or neither does. A relay then publishes outbox rows to Kafka, either a poller using FOR UPDATE SKIP LOCKED or CDC with Debezium reading the WAL, keyed by order id for ordering.

Since the relay can publish an event twice after a crash, delivery is at least once, so consumers deduplicate by event id in their own transaction. If Kafka is down, the outbox just accumulates and drains later, and we alert on its lag.

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 documentation below. 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 "An order service writes the order row to PostgreSQL in a @Transactional method and then...": https://scrivio-interview-library.netlify.app/databases/acid-and-isolation/327d2d43c1/