Scrivio Interview library
InternalsIntermediate6 min read · updated 12 November 2026

In a Spring Boot service, a method annotated with @Transactional saves an entity with JPA and sends a Kafka message with a KafkaTemplate. Describe what happens when the database commit fails after the send, and how Spring's Kafka transaction support and the outbox pattern change this.

Without coordination, KafkaTemplate.send() is independent of the database transaction, so the message can be published even though the database rolls back. A transactional Kafka producer lets Spring synchronize a Kafka transaction with the database transaction, so a failed database commit aborts the Kafka transaction and read_committed consumers never see it, but these are still two separate commits, not XA, and a crash between them can still diverge. The outbox pattern writes the event in the same database transaction and publishes it afterwards via a relay or CDC, giving at-least-once delivery that consumers must handle idempotently.

Why this question is asked

Saving an entity and announcing it with a Kafka message is the most common thing an event-driven Spring service does, and it is easy to get subtly wrong. Interviewers ask about it at the ten-year level because the answer requires knowing exactly when each side commits, what Spring's Kafka transaction support really guarantees, and why the outbox pattern is the usual recommendation anyway. In this answer, we will look at the naive version and its failure, then see how a Kafka transaction synchronized with the database transaction changes it and where it still leaks, and finally walk through the outbox pattern and what it asks of consumers.

1The Naive Version and Its Failure

Here is the method. It saves an order with JPA and sends OrderCreated with a non-transactional KafkaTemplate.

Java
@Transactional
public void create(Order order) {
orderRepository.save(order);
kafkaTemplate.send("orders", order.id().toString(), OrderCreated.of(order));
// send() is asynchronous; the producer may deliver the record within milliseconds
}
// commit at method exit -> fails: unique constraint detected at flush
// DB: no order Kafka: OrderCreated already in the log, visible to every consumer

The database transaction and the Kafka producer know nothing about each other. The send goes to the producer's buffer and is delivered to the broker almost immediately. When the JPA flush at commit time hits a constraint violation, Hibernate and the database roll back, but the event is already in the topic. Every consumer now believes in an order that does not exist. The opposite failure is possible too: the database commits, the pod dies before the buffered record is sent, and the order exists with no event.

2Synchronizing a Kafka Transaction With the Database

Kafka has its own transactions. A transactional producer, configured with a transactional id, can begin a transaction, send records, and then commit or abort them as a unit. In Spring Boot we enable it by setting spring.kafka.producer.transaction-id-prefix. When such a KafkaTemplate is used inside a method that already has a database transaction, Spring Kafka starts a Kafka transaction and registers it with the current transaction synchronization, so it completes together with the database transaction.

Concretely, Spring commits the database transaction first and then commits the Kafka transaction; if the database commit fails, the Kafka transaction is aborted. The records were written to the log, but they are marked as aborted.

YAML
spring:
kafka:
producer:
transaction-id-prefix: order-tx- # makes KafkaTemplate transactional
consumer:
isolation-level: read_committed # consumers skip aborted records
// same create() method, now:
// DB commit fails -> Kafka transaction aborted, read_committed consumers never see it
// DB commit succeeds -> Kafka transaction committed right after
Step throughTwo commits, one after the other
ServiceDatabaseKafka
begin, insert order
begin Kafka tx, send OrderCreated
commit
committed
crash possible here
commit Kafka tx
committed

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

If the service dies between the two commits, the order exists and the Kafka transaction times out and aborts.

Notice the consumer side. A Kafka consumer reads uncommitted and aborted records by default, isolation.level=read_uncommitted, so the abort only protects consumers configured with read_committed. Forgetting that setting quietly brings back the original bug.

3Why This Is Still Not Atomic

This is best-effort one-phase commit, not XA. There is no coordinator and no prepare phase, so there is a window between the two commits. If the process crashes after the database commit and before the Kafka commit, the order is saved and the Kafka transaction is eventually aborted by the broker's transaction timeout. The event is lost. The window is small, but at scale small windows happen every week.

Kafka transactions are designed for read-process-write inside Kafka: consume from one topic, produce to another and commit the consumer offsets in the same Kafka transaction. That is where they give exactly-once processing. Synchronizing with a database narrows the gap, but it cannot close it.

4The Outbox Pattern

The transactional outbox removes the second commit from the business transaction. Instead of sending to Kafka, the method inserts the event into an outbox table in the same database. The order and the event commit together or not at all, because it is one local transaction.

Java
@Transactional
public void create(Order order) {
orderRepository.save(order);
outboxRepository.save(new OutboxEvent(
UUID.randomUUID(), "Order", order.id().toString(), "OrderCreated", toJson(order)));
} // one commit: both rows, or neither
// relay, separate from the request
@Scheduled(fixedDelay = 500)
@Transactional
public void relay() {
for (OutboxEvent e : outboxRepository.lockNextBatch(100)) { // FOR UPDATE SKIP LOCKED
kafkaTemplate.send("orders", e.aggregateId(), e.payload()).join(); // wait for the ack
e.markSent();
}
}

A relay then publishes the rows. It can be a scheduled poller like this one, which locks a batch, sends each record and marks it as sent, or a change data capture tool such as Debezium, which reads the database's write-ahead log and turns each inserted outbox row into a Kafka record, without polling the table.

Either way the guarantee is at-least-once. If the relay sends a record and crashes before marking it sent, it sends it again after restart. A message is never lost while its row exists, but it may be delivered twice.

5What Consumers Must Do

Because duplicates are possible, consumers must be idempotent, meaning that processing the same event twice has the same effect as processing it once. The outbox row's UUID travels with the event as its id, and the consumer records processed ids in a table in the same transaction as its own change, skipping ids it has seen. Alternatively, the consumer's update is naturally idempotent, such as an upsert guarded by a version number.

The outbox also preserves order per aggregate if the relay publishes rows in insertion order and uses the aggregate id as the message key, which is another reason to key by entity id.

6Follow-up questions

Where would you put the outbox relay: in the service, or in a CDC platform?

For a few services, a relay inside the service is simplest: no new infrastructure, easy to test, and it scales with the service, though we must make sure only one instance works on a row, for example with SKIP LOCKED. Once many teams need it, a CDC platform such as Debezium on Kafka Connect is usually better: one operated component, lower latency because it reads the log, and no polling load on the database. The cost is a platform someone has to own, with its own monitoring of connector lag and failures.

Does read_committed slow consumers down?

A little. A read_committed consumer can only read up to the last stable offset, the point before which every transaction is decided. A long-running open transaction holds that point back and delays consumers on that partition, so producers should keep Kafka transactions short.

Is ChainedKafkaTransactionManager still the way to do this?

It was the older approach and has been deprecated in Spring Kafka in favour of transaction synchronization with the primary transaction manager. The idea and the limitation are the same either way: two commits in sequence, not one atomic commit.

7Conclusion

In this answer, we saw that a plain KafkaTemplate send inside @Transactional publishes independently, so a failed database commit leaves an event for an order that does not exist. A transactional producer synchronized with the database transaction aborts the Kafka transaction when the database commit fails, provided consumers read with read_committed, but it is still two commits, and a crash between them loses the event. The outbox pattern writes the event in the same database transaction and publishes it through a relay or CDC such as Debezium, giving at-least-once delivery that consumers handle with idempotent processing.

What to say in the interviewAbout 80 seconds aloud

Open with

Without any coordination, the Kafka send is independent of the database transaction. The record goes into the producer buffer and reaches the broker within milliseconds, so if the database commit then fails, for example on a constraint at flush time, consumers see an OrderCreated for an order that does not exist.

Then, if they want more

If I make the producer transactional with a transaction-id-prefix, Spring Kafka starts a Kafka transaction and synchronizes it with the database transaction: it commits the database first, then Kafka, and if the database commit fails it aborts the Kafka transaction. Consumers must use isolation level read_committed, otherwise they still see aborted records. But this is two separate commits, not XA.

If the pod dies between the database commit and the Kafka commit, the order is saved and the event is lost.

So for this case I would use the transactional outbox: the method saves the order and an outbox row in the same database transaction, and a relay, either a poller with SKIP LOCKED or CDC with Debezium reading the WAL, publishes it afterwards, keyed by the aggregate id.

That gives at-least-once delivery, because the relay can resend after a crash, so consumers must be idempotent, for example by recording processed event ids or by doing versioned upserts.

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 "In a Spring Boot service, a method annotated with @Transactional saves an entity with...": https://scrivio-interview-library.netlify.app/spring-boot/distributed-data/8886d0a2d7/