Transactional Outbox Pattern with Kafka
The transactional outbox pattern with Kafka solves a problem every event-driven service meets sooner or later: the service saves data in its database and must also publish an event to Kafka, but the two writes cannot be made atomic. If the database commit succeeds and the Kafka publish fails, the event is lost. The outbox pattern stores the event in the same database transaction as the data, and a separate relay publishes it to Kafka afterwards.
The general pattern is covered in Transactional Outbox Pattern in Microservices. This tutorial focuses on the Kafka side: how outbox rows map to Kafka records, how to publish them with Debezium and Kafka Connect or with a Spring Boot polling relay, which producer settings the relay needs, and what delivery guarantee consumers actually get.
1. What Is the Transactional Outbox Pattern with Kafka?
An outbox is a table in the service’s own database. When the service changes its business data, it inserts a row describing the event into the outbox in the same local transaction. A relay process then reads new outbox rows and publishes them to Kafka. Because the business change and the event commit together, an event is never lost and never published for a change that was rolled back.
The pattern uses nothing special from Kafka. It combines a database transaction, an idempotent Kafka producer in the relay, and idempotent consumers on the receiving side.
2. The Problem: Database and Kafka Are Two Systems
The naive approach saves the order and then calls kafkaTemplate.send(). Every ordering of these two steps has a failure case:
| Approach | Failure | Result |
|---|---|---|
| Commit the database, then publish | Kafka is unavailable or the process crashes after the commit | Order saved, event lost; other services never hear about it |
| Publish inside the transaction, before the commit | The database commit fails after the send succeeded | Event published for an order that does not exist |
| Publish, then retry until it works | The process restarts while retrying | Retry state is lost with the process; the event is lost again |
This is the dual-write problem. A database transaction cannot include a Kafka write, and a Kafka transaction cannot include a database write, so the event has to be stored in the database first.
3. How the Outbox Works with Kafka
- Write: the service inserts the business row and the outbox row in one local transaction.
- Read: the relay notices the new outbox row, either from the database’s change log (CDC) or by polling the table.
- Publish: the relay sends the event to Kafka and waits for the acknowledgement. Only then does it consider the row published.
- Consume: consumers process the event and use its ID to skip duplicates.
4. Mapping Outbox Rows to Kafka Records
The outbox table is designed around the Kafka record it will become. The column names below are the defaults expected by Debezium’s outbox event router, which makes switching relays easy:
CREATE TABLE outbox_event (
id UUID PRIMARY KEY,
aggregatetype VARCHAR(100) NOT NULL, -- decides the topic, e.g. 'order' -> order-events
aggregateid VARCHAR(100) NOT NULL, -- becomes the Kafka record key
type VARCHAR(100) NOT NULL, -- event type, e.g. OrderPlaced
payload JSONB NOT NULL, -- becomes the record value
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ -- used only by a polling relay
);
CREATE INDEX outbox_unpublished ON outbox_event (created_at) WHERE published_at IS NULL;
| Outbox column | Kafka record | Why |
|---|---|---|
aggregateid | Key | All events of one order go to the same partition, so consumers see them in order. |
aggregatetype | Topic name | One topic per aggregate type: order-events, customer-events. |
id | Header (Debezium uses the header name id) | A stable event ID for idempotent consumers; it is the same on every republish. |
type | Header such as eventType | Consumers can route or filter without parsing the payload. |
payload | Value | The event itself. |
5. Writing to the Outbox in Spring Boot
The service never calls Kafka directly. It writes the order and the outbox row with the same @Transactional method, so they commit or roll back together:
package com.javabytechie.orders;
import java.math.BigDecimal;
import java.util.UUID;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tools.jackson.databind.json.JsonMapper;
record OrderPlaced(String eventId, String orderId, String customerId, BigDecimal total) {}
@Service
public class OrderService {
private final JdbcTemplate jdbc;
private final JsonMapper jsonMapper; // Jackson 3, auto-configured by Spring Boot 4
public OrderService(JdbcTemplate jdbc, JsonMapper jsonMapper) {
this.jdbc = jdbc;
this.jsonMapper = jsonMapper;
}
@Transactional
public String placeOrder(String customerId, BigDecimal total) {
String orderId = UUID.randomUUID().toString();
jdbc.update("INSERT INTO orders (id, customer_id, total, status) VALUES (?, ?, ?, 'PLACED')",
orderId, customerId, total);
UUID eventId = UUID.randomUUID();
var event = new OrderPlaced(eventId.toString(), orderId, customerId, total);
jdbc.update("""
INSERT INTO outbox_event (id, aggregatetype, aggregateid, type, payload)
VALUES (?, 'order', ?, 'OrderPlaced', CAST(? AS JSONB))
""", eventId, orderId, jsonMapper.writeValueAsString(event));
return orderId; // both rows commit together, or neither does
}
}
6. Relay Option 1: Debezium and Kafka Connect
With change data capture, a Debezium source connector running in Kafka Connect reads inserts from the database’s write-ahead log, not from the table, and its outbox event router transformation turns each outbox row into a clean Kafka record:
{
"name": "orders-outbox-connector",
"config": {
"connector.class": "io.debezium.connector.postgresql.PostgresConnector",
"plugin.name": "pgoutput",
"database.hostname": "orders-db",
"database.port": "5432",
"database.user": "debezium",
"database.password": "${file:/opt/kafka/secrets/orders-db.properties:password}",
"database.dbname": "orders",
"topic.prefix": "orders-db",
"table.include.list": "public.outbox_event",
"transforms": "outbox",
"transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
"transforms.outbox.route.topic.replacement": "${routedByValue}-events",
"transforms.outbox.table.fields.additional.placement": "type:header:eventType",
"transforms.outbox.table.expand.json.payload": "true",
"key.converter": "org.apache.kafka.connect.storage.StringConverter",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": "false"
}
}
table.include.listlimits the connector to the outbox table; the router expects outbox rows only.route.topic.replacementbuilds the topic from theaggregatetypecolumn (${routedByValue}), soorderrows go toorder-events. The router’s default would beoutbox.event.order.- The key is
aggregateidand theidcolumn goes into a header namedidby default; the extra placement adds thetypecolumn as aneventTypeheader. - The password is read with Kafka Connect’s
FileConfigProvider, which must be enabled on the Connect worker, instead of being stored in the connector configuration.
Register the connector with curl -X POST -H "Content-Type: application/json" --data @orders-outbox-connector.json http://connect:8083/connectors. Because Debezium reads the log, the relay adds no query load to the outbox table, keeps the commit order of the database, and outbox rows can be removed by a cleanup job shortly after they are written.
7. Relay Option 2: Polling Publisher with KafkaTemplate
Without CDC infrastructure, a scheduled job in the service can poll the outbox and publish with KafkaTemplate. The essential rule is to mark a row as published only after Kafka has acknowledged it:
package com.javabytechie.orders;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
public class OutboxPublisher {
record OutboxRow(UUID id, String aggregateType, String aggregateId, String type, String payload) {}
private final JdbcTemplate jdbc;
private final KafkaTemplate<String, String> kafka; // idempotent producer, acks=all
public OutboxPublisher(JdbcTemplate jdbc, KafkaTemplate<String, String> kafka) {
this.jdbc = jdbc;
this.kafka = kafka;
}
@Scheduled(fixedDelay = 500)
@Transactional
public void publishBatch() {
List<OutboxRow> rows = jdbc.query("""
SELECT id, aggregatetype, aggregateid, type, payload::text
FROM outbox_event
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 100
FOR UPDATE SKIP LOCKED
""", (rs, i) -> new OutboxRow(rs.getObject(1, UUID.class), rs.getString(2),
rs.getString(3), rs.getString(4), rs.getString(5)));
List<CompletableFuture<SendResult<String, String>>> sends = rows.stream().map(row -> {
var record = new ProducerRecord<>(row.aggregateType() + "-events", row.aggregateId(), row.payload());
record.headers().add("id", row.id().toString().getBytes(StandardCharsets.UTF_8));
record.headers().add("eventType", row.type().getBytes(StandardCharsets.UTF_8));
return kafka.send(record);
}).toList();
// Throws if any send failed: the transaction rolls back and the rows stay unpublished
CompletableFuture.allOf(sends.toArray(CompletableFuture[]::new)).join();
for (OutboxRow row : rows) {
jdbc.update("UPDATE outbox_event SET published_at = now() WHERE id = ?", row.id());
}
}
}
- Sends are asynchronous but awaited: the batch is sent in parallel, then
join()waits for every acknowledgement before rows are marked. - The producer keeps per-key order because records are sent in
created_atorder with the idempotent producer’s defaults (at most 5 in-flight requests, retries enabled). - Run one active publisher.
FOR UPDATE SKIP LOCKEDstops two instances from sending the same rows, but two instances sending different batches in parallel can reorder events of the same order. Use a lock so only one instance publishes, or use CDC. - Keep batches small, because the database transaction stays open while Kafka acknowledges.
Enable scheduling with @EnableScheduling on a configuration class. Compared with Debezium, polling adds latency (up to the polling interval) and load on the database, but needs no Kafka Connect cluster.
8. Delivery Guarantees and Duplicates
The outbox gives at-least-once publishing, never exactly-once. Both relays can publish an event twice:
- Polling relay: Kafka acknowledged the batch, but the process crashed before the
UPDATE ... published_atcommitted. The next run sends the same rows again. - Debezium: the connector publishes records and periodically stores its position in the database log in Kafka Connect’s offsets topic. After a crash it resumes from the last stored position and re-emits the changes after it.
The idempotent producer cannot remove these duplicates, because they are new send() calls, not internal retries. Consumers must deduplicate by the event ID header, as described in Idempotent Consumer in Kafka. The outbox and the idempotent consumer are two halves of the same design.
9. Why Kafka Transactions Do Not Replace the Outbox
Kafka transactions make writes to several Kafka partitions, together with consumer offsets, atomic. They cannot include a PostgreSQL or MySQL commit. Spring can synchronise a Kafka transaction with a database transaction, but it commits them one after the other; a crash between the two commits still leaves one done and the other not. The outbox avoids the problem because there is only one transaction: the database one.
| Outbox + relay | Kafka transactions | |
|---|---|---|
| Atomic with the database write | Yes, the event is a database row | No |
| Atomic across Kafka partitions | Not needed for one event | Yes |
| Publishing guarantee | At least once, consumers deduplicate | Exactly once inside Kafka |
| Typical use | Services that own a database and emit events | Kafka-to-Kafka stream processing |
10. Common Mistakes
- Calling
kafkaTemplate.send()inside the@Transactionalmethod “as well”, which reintroduces the dual write. - Marking rows as published before the acknowledgement, which loses events when the send fails.
- Using a random or null Kafka key, so events of one aggregate land on different partitions and arrive out of order.
- Running several polling relays in parallel and breaking per-aggregate order.
- Assuming no duplicates because the relay uses an idempotent producer.
- Letting the outbox table grow forever, which slows down polling queries.
11. Best Practices
- Use the aggregate ID as the Kafka key and a stable UUID as the event ID header.
- Prefer Debezium when you already run Kafka Connect or need low latency; use polling for small services.
- Configure the relay producer for durability:
acks=alland idempotence enabled (both defaults), and topics with replication factor 3 andmin.insync.replicas=2. - Delete published rows regularly with a cleanup job, keeping a short history for troubleshooting.
- Monitor outbox lag: the age of the oldest unpublished row, or the connector’s lag behind the database log.
- Version the payload schema so consumers can evolve independently.
12. Summary
The transactional outbox pattern with Kafka writes each event into an outbox table in the same database transaction as the business change, and a relay publishes it to Kafka afterwards, so a committed change never loses its event. Design the outbox around the Kafka record: aggregate ID as the key, event ID as a header, aggregate type as the topic. Use Debezium’s outbox event router or a single polling publisher that marks rows only after Kafka acknowledges them. Publishing is at-least-once, so pair the outbox with idempotent consumers.
13. Related Reading
- Transactional Outbox Pattern in Microservices
- How Kafka Transactions Work Internally
- Kafka Delivery Semantics: At-Most-Once, At-Least-Once and Exactly-Once
- Kafka Message Ordering and Concurrent Processing
14. References
Kafka Transactional Outbox Interview Questions and Answers
Common interview questions on Kafka Transactional Outbox, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. Your application commits a database transaction but fails to publish the corresponding event to Kafka. How do you handle this without losing the event?
Answer: Stop publishing directly from the business code. Insert the event into an outbox table in the same database transaction as the business change, so a committed change always has its event stored. A relay, either Debezium reading the database log or a scheduled poller, publishes outbox rows to Kafka and only marks them done after Kafka acknowledges. If Kafka is down, events wait in the table and are published when it comes back; nothing is lost, and nothing depends on the original request thread surviving.
Q. Which outbox columns become the key, value and headers of the Kafka record, and why does the key matter?
Answer: The aggregate ID (for example the order ID) becomes the key, the payload becomes the value, the event ID and event type go into headers, and the aggregate type usually selects the topic. The key matters because Kafka orders records only within a partition and the key decides the partition: with the aggregate ID as key, OrderPlaced, OrderPaid and OrderShipped for one order reach consumers in the order they were written.
Intermediate questions
Q. How does Debezium’s outbox event router decide the topic, key and headers of each record?
Answer: It is a single message transformation that runs in the Debezium source connector. By default it routes by the aggregatetype column to a topic named outbox.event.<aggregatetype>, which route.topic.replacement can change. It uses aggregateid as the record key, payload as the value, and puts the id column into a header named id. Other columns can be added as headers or envelope fields with table.fields.additional.placement.
Q. Why can consumers still receive duplicate events with an outbox, even when the relay uses an idempotent producer?
Answer: Because the relay itself can publish a row twice. A polling relay may get Kafka’s acknowledgement and crash before it marks the row as published; Debezium resumes from its last stored log position after a restart and re-emits later changes. These are new send() calls, not producer-internal retries, so the idempotent producer cannot detect them. The outbox therefore guarantees at-least-once publishing, and consumers deduplicate by the event ID header.
Q. When would you choose a polling relay over Debezium for a Kafka outbox?
Answer: Polling suits small services, low event volumes, or teams without a Kafka Connect cluster: it is plain application code with a scheduler, FOR UPDATE SKIP LOCKED and a published_at column. Debezium suits higher volumes and lower latency: it reads the database log instead of querying the table, preserves commit order and adds no polling load. It needs logical replication on the database and a Connect cluster to operate.
Tricky and scenario questions
Q. A polling relay marks rows as published right after calling kafkaTemplate.send(). What can go wrong?
Answer: send() is asynchronous: it returns as soon as the record is in the producer’s buffer. If the send later fails after its retries, or the process dies before the buffer is flushed, the row is already marked and the event is lost, which is the exact problem the outbox is meant to solve. Wait for the send futures to complete successfully, then mark the rows; if a send fails, leave the rows unpublished so the next run tries again.
Q. The order service is scaled to three instances, each running the polling relay. Consumers see OrderShipped before OrderPaid. Why, and how do you fix it?
Answer: SKIP LOCKED prevents two instances from sending the same row, but each instance locks a different batch and sends it in parallel. If OrderPaid is in one instance’s batch and OrderShipped in the next instance’s batch, the second can reach Kafka first, even though both have the same key. Fix it by allowing only one active publisher, for example with a database lock or leader election, by splitting the outbox by aggregate ID hash so each instance owns its own keys, or by switching to Debezium, which reads changes in commit order.