Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A listener writes an order row to PostgreSQL and then sends an event with a transactional KafkaTemplate. Someone proposes chaining the JPA and Kafka transaction managers so both commit together. What actually happens, and what would you recommend?

Chaining the JPA and Kafka transaction managers does not create a distributed transaction: the two commits still happen one after the other, so a crash between them leaves PostgreSQL and Kafka inconsistent. Spring's own guidance is to synchronise the two transactions so one commits right after the other, accept the small window and handle the resulting duplicates, and to choose the commit order by which failure is easier to repair. The robust recommendation is a transactional outbox, which writes the event in the same database transaction and publishes it later, with idempotent consumers because redelivery and republishing are always possible.

Why this question is asked

Writing a row and publishing an event about it is one of the most common things a service does, and wanting both to happen or neither is natural. Chaining transaction managers sounds like it delivers that, which is why the proposal comes up often. Interviewers ask this to see whether we know what a chained manager really does and what the honest options are. In this answer, we will see what chaining actually does, walk through the failure window, look at Spring's recommended synchronisation and how to pick the commit order, and then build the outbox, with idempotent consumers as the final safety net.

1What Chaining Really Does

Spring once offered ChainedTransactionManager, and Spring Kafka a ChainedKafkaTransactionManager, to start several transactions together and commit them in sequence. Both are deprecated; check your versions, as they may be removed. Whatever the mechanism, the effect is the same: the JPA transaction commits, and then the Kafka transaction commits, or the reverse. They are two independent commit protocols, PostgreSQL's and Kafka's, and nothing coordinates them.

A real distributed transaction would need two-phase commit through XA, where a coordinator first asks every resource to prepare and then tells all to commit. Kafka does not support XA, so no configuration of Spring can make these two commits atomic. Chaining only orders them, which is also called best-effort one-phase commit.

2The Failure Window

Suppose the order is database first. The listener inserts the order row and sends the event through the transactional KafkaTemplate. PostgreSQL commits. Before the Kafka commit, the pod is killed. The Kafka transaction is aborted by the coordinator after its timeout, so the event never becomes visible, and because the consumed offset was part of the Kafka transaction, the input record is redelivered. The listener runs again and inserts the order a second time, unless the insert is idempotent.

Now suppose the order is Kafka first. The event is committed and visible, then the database commit fails, perhaps on a constraint or a lost connection. Downstream services now act on an order that does not exist. The window between commits is small, milliseconds, but over millions of messages and some crashes, it will be hit.

Step throughDatabase commits, then the pod dies
ListenerPostgreSQLKafka
INSERT order 42
send OrderCreated (in Kafka tx)
COMMIT: row is durable
pod killed before Kafka commit
transaction aborted, input offset not committed
input record redelivered after restart
INSERT order 42 again: duplicate unless idempotent

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

3Spring's Recommendation: Synchronise and Handle Duplicates

The Spring Kafka documentation's approach is to let the listener container run the Kafka transaction with a KafkaTransactionManager and put @Transactional with the JPA transaction manager on the listener. The JPA transaction then commits when the method returns, and the container commits the Kafka transaction immediately afterwards. This is the database-first order, synchronised so the window is as small as possible.

Java
@KafkaListener(topics = "order-requests") // container runs the Kafka transaction
@Transactional("transactionManager") // JPA transaction around the method
public void handle(OrderRequest req) {
if (orders.existsByRequestId(req.requestId())) return; // idempotent: redelivery is harmless
orders.save(Order.from(req));
template.send("orders", req.orderId(), new OrderCreated(req.orderId()));
}
// JPA commits when the method returns, then the container commits Kafka

The duplicate check is what makes the window acceptable. If the pod dies between the commits, the redelivered request finds its order already saved and does nothing, but notice the catch: the event was aborted with the failed Kafka transaction, and the second run returns early, so the event is never sent. To be correct, the redelivered run must send the event again when the row exists but the event may be missing. This subtlety is why the outbox is simpler to get right.

4Choosing the Commit Order

When we keep two commits, we choose the order by which failure we can repair more easily. Database first means the failure mode is 'row saved, event missing or duplicated'. That is usually repairable: redelivery retries it, and a reconciliation job can republish events for rows that lack them. Kafka first means the failure mode is 'event published about a row that does not exist'. Other services may already have acted on it, sent an email or reserved stock, and an event cannot be unpublished. So for most business data, database first is the safer order, because the database is the source of truth and missing events can be regenerated from it.

5The Recommendation: a Transactional Outbox

The outbox removes the second commit from the request entirely. In the same database transaction as the order row, we insert a row into an outbox table holding the event's topic, key and payload. One commit, one system, fully atomic: either both rows exist or neither does. A separate relay then reads committed outbox rows and publishes them to Kafka, marking or deleting each row after Kafka acknowledges it. The relay can be a scheduled poller, or change data capture with Debezium reading the outbox table from the write-ahead log.

Java
@Transactional
public void handle(OrderRequest req) {
Order order = orders.save(Order.from(req));
outbox.save(new OutboxEvent("orders", order.getId().toString(),
json(new OrderCreated(order.getId()))));
} // one PostgreSQL commit covers the order and its event
// Relay, separately: read unsent rows in order, send, mark as sent after the ack
Step throughThe outbox flow
  1. Business transactioninsert order and outbox row, one commit
  2. Relay reads unsent rowspoller or Debezium on the WAL
  3. Publish to Kafkaidempotent producer, acks=all
  4. Mark row as senta crash here means a republish
  5. Consumers deduplicateby event id or business key

5 steps in order. Play them, or step through them one at a time.

If the relay crashes after Kafka acknowledged an event but before marking the row, it publishes that event again on restart. So the outbox gives at-least-once publishing: events are never lost, but may be duplicated. That is acceptable because, as the next section explains, consumers must handle duplicates anyway.

6Consumers Must Be Idempotent

Every option above can deliver an event more than once: redelivery after a crash, a relay republishing, a consumer reprocessing after a rebalance. So consumers are written to make duplicates harmless. Each event carries a unique id, and the consumer records processed ids in its own database in the same transaction as its own changes, skipping ids it has seen. Or the consumer's writes are naturally idempotent, such as upserts keyed by order id or 'set status to SHIPPED' rather than 'increment shipped count'. This is the real foundation of reliability in event-driven systems; atomic commits across systems are not available, so we design for at-least-once delivery and idempotent processing.

7Follow-up questions

Why not use XA with a JTA transaction manager?

Because Kafka does not support XA. Even for resources that do, two-phase commit adds latency, needs a coordinator that can recover in-doubt transactions, and couples the availability of the systems involved. For databases plus Kafka, the outbox gives the needed consistency without it.

Does the outbox table grow for ever?

No. The relay deletes rows after publishing them, or a cleanup job removes sent rows older than a few days. With Debezium, rows can even be deleted right after insert, since Debezium reads the insert from the write-ahead log, not from the table.

8Conclusion

In this answer, we saw that chaining JPA and Kafka transaction managers only orders two independent commits, so a crash between them leaves the database and Kafka inconsistent. Spring's guidance is to synchronise the transactions, usually database first, accept the small window and handle duplicates, choosing the order by which failure is easier to repair. The recommended design is a transactional outbox that writes the event in the database transaction and publishes it afterwards, with idempotent consumers because redelivery and republishing are always possible.

What to say in the interviewAbout 90 seconds aloud

Open with

Chaining the managers does not give us a distributed transaction. Kafka does not support XA, so the chained manager just commits one transaction after the other; Spring's chained managers are deprecated for that reason.

Then, if they want more

There is always a window: if the database commits and the pod dies before the Kafka commit, the event is aborted and the input is redelivered, and if Kafka commits first and the database fails, other services act on an order that does not exist.

Spring Kafka's guidance is to let the container run the Kafka transaction and put @Transactional with the JPA manager on the listener, so the database commits and the Kafka transaction commits right after, accepting the small window and making the listener idempotent.

If I keep two commits, I would choose database first, because a missing event can be republished from the database, while a published event about a row that never committed cannot be taken back.

My actual recommendation would be a transactional outbox: insert the order and an outbox row in one PostgreSQL transaction, and have a relay, a poller or Debezium on the WAL, publish the outbox rows to Kafka and mark them sent. That makes the business change and the event atomic, with at-least-once publishing.

And consumers must be idempotent regardless, using event ids or upserts by business key, because redelivery and republishing can always happen.

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 "A listener writes an order row to PostgreSQL and then sends an event with a...": https://scrivio-interview-library.netlify.app/spring-boot/kafka/1d82497b10/