Scrivio Interview library
DesignAdvanced6 min read · updated 12 November 2026

Several teams use @TransactionalEventListener(AFTER_COMMIT) to send Kafka messages after database commits, and incidents show occasional lost messages. What standard would you set for reliable post-commit publishing across services?

AFTER_COMMIT listeners run in memory after the database commit, so a crash, a deploy or a broker error at that moment loses the Kafka message even though the data is saved. The standard I would set is a transactional outbox: write the event as a row in the same transaction as the business change, and let a relay publish it to Kafka, using a polling publisher, change data capture with Debezium, or Spring Modulith's publication registry with externalization. Delivery becomes at least once, so consumers must be idempotent, and a shared starter with outbox-lag monitoring keeps every team from rebuilding it.

Why this question is asked

Lost messages are the kind of incident that erodes trust slowly: a few orders never reach the warehouse, a few payments never reach accounting, and each team has a different explanation. The common root here is a pattern that looks right, sending to Kafka from an after-commit listener, but has a gap no amount of retrying can close. Interviewers ask this design question at a senior level to see whether we can name the gap, choose a pattern that removes it, and turn the choice into a standard for many teams. In this answer, we will look at why the current approach loses messages, design the outbox, compare relay options, cover idempotent consumers, and finish with what the standard and its tooling look like.

1Why AFTER_COMMIT Publishing Loses Messages

The current pattern looks like this: the service commits its database transaction, and an AFTER_COMMIT listener then calls kafkaTemplate.send(). The two operations are separate, and nothing ties them together. The database commit is durable; the pending send exists only in the JVM's memory.

So every moment between the commit and Kafka acknowledging the send is a window for loss. A pod killed by a deploy, an out-of-memory crash, a broker that is unavailable for a minute while the producer's retries run out, or a send() whose returned future nobody checks: any of these leaves the database saying an order exists while no event about it was ever published. Reversing the order, sending first and committing second, just creates the opposite problem, an event for data that was rolled back. This is the dual-write problem: two systems cannot be updated atomically without a shared transaction, and Kafka and our database do not share one.

2The Transactional Outbox

The outbox removes the dual write by making the event part of the database transaction. Instead of sending to Kafka, the service inserts a row into an outbox table in the same transaction as the business change. Either the order and its event commit together, or neither does. A separate relay then reads committed outbox rows and publishes them to Kafka, marking each as sent once Kafka acknowledges it.

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, -- e.g. OrderPlaced.v1
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz -- null until the relay has sent it
);
@Transactional
public void place(Order order) {
orders.save(order);
outbox.save(OutboxRow.of(order.id(), "OrderPlaced.v1", toJson(new OrderPlaced(order.id()))));
} // one commit: order and event row together
Step throughOutbox publishing
OrderServiceDatabaseRelayKafka
insert order + outbox row, one commit
read unpublished rows
send(key = order id, payload)
ack
set published_at

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

A crash at any point leaves either nothing committed or an unsent row that will be retried.

Notice that the relay can crash too, but now nothing is lost: an unsent row stays in the table and is published after restart. The price is that the relay may publish a row, crash before marking it sent, and publish it again. So the outbox gives at-least-once delivery, never exactly once by itself.

3Choosing a Relay

There are three common ways to move outbox rows to Kafka, and the standard should name a default while allowing the others where they fit.

Outbox relay options
RelayHow it worksStrengthsCosts
Polling publishera scheduled job selects unsent rowssimple, no extra infrastructurepolling load, seconds of latency
CDC with Debeziumreads the database log, emits rows to Kafkalow latency, no polling queriesKafka Connect to run and monitor
Spring Modulith registrystores publications, externalizes to Kafkalittle code in Spring servicesSpring-only, check version features
Any of the three gives at-least-once delivery; pick by latency needs and operational skills.

4Making Consumers Idempotent

Since every relay can deliver a message twice, consumers must handle duplicates. An idempotent consumer is one where processing the same message twice has the same effect as processing it once. The usual way is to record the id of each processed event in the consumer's database, in the same transaction as its own change, and skip ids it has already seen.

Java
@KafkaListener(topics = "orders")
@Transactional
public void on(OrderPlacedMessage m) {
if (!processed.insertIfAbsent(m.eventId())) return; // duplicate: already handled
shipments.create(m.orderId());
}
// first delivery -> shipment created
// second delivery -> skipped, still one shipment

Where the business operation is naturally idempotent, such as setting a status to SHIPPED, the check can be lighter, but the standard should require each consumer to state how it handles duplicates. Using the aggregate id as the Kafka key also matters: it sends all events for one order to the same partition, so they arrive in order.

5Turning It Into a Standard

A pattern that every team implements by hand will be implemented five different ways. So the standard comes with a shared library or Spring Boot starter that provides the outbox table migration, the writer API used inside transactions, a default polling relay, and configuration for teams that use Debezium instead. The starter also exposes metrics: the number of unpublished rows and the age of the oldest one. Outbox lag is the key health signal; an alert when the oldest unpublished row is older than, say, five minutes catches a stuck relay before customers notice.

The written standard itself is short: no direct sends to Kafka from after-commit listeners for events that must not be lost; every such event goes through the outbox; every consumer documents its idempotency; and teams migrate their existing listeners within a set time, starting with the flows involved in the incidents.

6Follow-up questions

How do you clean up the outbox table without hurting write throughput?

Delete published rows in small batches from a scheduled job, for example a few thousand rows at a time with a short pause, using an index on published_at so the delete does not scan the table. For high volumes, partition the table by day and drop whole old partitions, which is far cheaper than row deletes. Keep a few days of published rows for debugging and replay before removing them.

Why not use Kafka transactions instead of an outbox?

Kafka transactions make writes to several Kafka topics atomic, but they do not include our database. A database commit and a Kafka transaction still cannot be committed together, so the dual-write gap remains. The outbox moves the event into the database transaction, which is the part that solves it.

Does the outbox guarantee ordering?

Per key, if the relay publishes rows for one aggregate in creation order and uses the aggregate id as the Kafka key. Across different aggregates there is no global order, and consumers should not need one.

7Conclusion

In this answer, we saw that AFTER_COMMIT listeners sending to Kafka have a dual-write gap: the commit is durable but the send lives in memory, so crashes, deploys and broker errors lose messages. The standard is a transactional outbox written in the same transaction, relayed by polling, Debezium or Spring Modulith's registry, with at-least-once delivery that requires idempotent consumers, and a shared starter with outbox-lag monitoring so every team uses one well-tested implementation.

What to say in the interviewAbout 100 seconds aloud

Open with

The root cause is a dual write. The database commit is durable, but the Kafka send in an after-commit listener exists only in the JVM's memory. If the pod is killed by a deploy, crashes, or the broker is unavailable longer than the producer retries, the data is saved and the message is never sent, and nothing records the loss.

Then, if they want more

Sending before the commit just creates the opposite problem. So the standard I would set is a transactional outbox. The service writes the event as a row in an outbox table in the same transaction as the business change, so they commit together or not at all. A relay then publishes committed rows to Kafka and marks them sent.

The relay can be a polling publisher, which is simple; change data capture with Debezium, which has lower latency but needs Kafka Connect; or Spring Modulith's event publication registry with externalization, for Spring services.

All of them deliver at least once, because the relay can send a row and crash before marking it, so every consumer must be idempotent, typically by recording processed event ids in its own transaction. I would use the aggregate id as the Kafka key to keep per-entity order.

To make it stick, I would provide a shared starter with the table migration, the writer API and a default relay, and expose metrics for outbox lag, with an alert when the oldest unsent row is older than a few minutes.

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 "Several teams use @TransactionalEventListener(AFTER_COMMIT) to send Kafka messages after...": https://scrivio-interview-library.netlify.app/spring-boot/spring-events/389a9b34b1/