00:00

Transactional Outbox Pattern with Kafka

Last updated:

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:

ApproachFailureResult
Commit the database, then publishKafka is unavailable or the process crashes after the commitOrder saved, event lost; other services never hear about it
Publish inside the transaction, before the commitThe database commit fails after the send succeededEvent published for an order that does not exist
Publish, then retry until it worksThe process restarts while retryingRetry 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

Transactional outbox with KafkaThe order service runs one local database transaction that inserts into the orders table and the outbox_event table and commits. A relay, either Debezium reading the database log or a polling publisher, reads new outbox rows and publishes each to the Kafka topic order-events with the aggregate ID as the key and the event ID in a header. Consumers such as the payment and shipping services read the topic and use the event ID to ignore duplicates. Order serviceplaceOrder() Orders database ordersid 17, status PLACED outbox_eventOrderPlaced, aggregate 17 ① one local transaction, one commit RelayDebezium or poller ② read order-eventsKafka topic ③ publish Payment servicededupe by eventId Shipping servicededupe by eventId ④ consume Kafka record: key = aggregate ID 17 (keeps per-order ordering),header id = outbox row ID, value = payload JSON
The business row and the outbox row commit together. The relay publishes outbox rows to Kafka afterwards, and consumers use the event ID to ignore the occasional duplicate.
  1. Write: the service inserts the business row and the outbox row in one local transaction.
  2. Read: the relay notices the new outbox row, either from the database’s change log (CDC) or by polling the table.
  3. Publish: the relay sends the event to Kafka and waits for the acknowledgement. Only then does it consider the row published.
  4. 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:

outbox.sql (PostgreSQL)
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 columnKafka recordWhy
aggregateidKeyAll events of one order go to the same partition, so consumers see them in order.
aggregatetypeTopic nameOne topic per aggregate type: order-events, customer-events.
idHeader (Debezium uses the header name id)A stable event ID for idempotent consumers; it is the same on every republish.
typeHeader such as eventTypeConsumers can route or filter without parsing the payload.
payloadValueThe 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:

OrderService.java
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:

orders-outbox-connector.json
{
  "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.list limits the connector to the outbox table; the router expects outbox rows only.
  • route.topic.replacement builds the topic from the aggregatetype column (${routedByValue}), so order rows go to order-events. The router’s default would be outbox.event.order.
  • The key is aggregateid and the id column goes into a header named id by default; the extra placement adds the type column as an eventType header.
  • 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:

OutboxPublisher.java
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_at order with the idempotent producer’s defaults (at most 5 in-flight requests, retries enabled).
  • Run one active publisher. FOR UPDATE SKIP LOCKED stops 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_at committed. 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 + relayKafka transactions
Atomic with the database writeYes, the event is a database rowNo
Atomic across Kafka partitionsNot needed for one eventYes
Publishing guaranteeAt least once, consumers deduplicateExactly once inside Kafka
Typical useServices that own a database and emit eventsKafka-to-Kafka stream processing

10. Common Mistakes

  • Calling kafkaTemplate.send() inside the @Transactional method “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=all and idempotence enabled (both defaults), and topics with replication factor 3 and min.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.

14. References