← Blog

Distributed Systems · Kafka · Transactional Outbox

How Do You Commit a Database Change and Publish an Event Without Lying to Either System?

Saving to a database and publishing to Kafka look like one step in code, but they're two separate commits that can disagree. This article explains the dual-write problem and how the transactional outbox, idempotent consumers and reconciliation make it recoverable.

Aashaya Aryal

May 6, 2026 · 15 min read

Updated November 17, 2026

Reflective segmented head sculpture standing in front of a large city building.

An order service processes a successful payment and needs two things to become true: the order is marked PAID in PostgreSQL, and an OrderPaid event exists in Kafka. In code, the two operations sit side by side and look almost atomic:

JAVA
orderRepository.markPaid(orderId);

kafkaTemplate.send(
    "orders",
    orderId,
    new OrderPaid(orderId)
);

The lines are adjacent. The commits aren't. PostgreSQL can commit the order update and then the process can die before Kafka receives anything. Swap the order and Kafka can receive OrderPaid before the database transaction commits. Either way, both systems are behaving correctly by their own rules while the overall system tells two different stories about the same payment.

This is the dual-write problem. It's tempting to treat it as a question of ordering (publish before or after the commit?), but neither order fixes it. The real issue is that two independent systems are being asked to take part in one logical operation without sharing a transaction. The more useful question is: how can the database transaction durably record that an event still needs to be published? That's where the transactional outbox pattern starts.

The dual-write problem

PostgreSQL has transactions. Kafka has its own durability and transaction mechanisms. But "commit to PostgreSQL and publish to Kafka" isn't automatically one transaction, so there are four possible outcomes:

DatabaseKafkaMeaning
Not updatedNo eventNothing happened
UpdatedEvent publishedThe state we want
UpdatedNo eventDownstream misses a real change
Not updatedEvent publishedDownstream believes a change that never committed

The last two are the dangerous ones.

If you commit first and publish second, the process can die between the two. PostgreSQL says the order is paid; downstream systems never heard about it. Fulfilment never starts, analytics never sees the payment, and the customer never gets the confirmation email. The local database is right; the workflow is incomplete.

If you publish first and commit second, the process can die after the publish. Downstream services receive OrderPaid while the source of truth still says PENDING. You haven't removed the inconsistency, just flipped its direction.

AWS's transactional outbox guidance describes the same gap: updating a database and notifying another system separately leaves a window where one succeeds and the other doesn't. So the design needs to either make the inconsistent states impossible, or make them durably detectable and repairable.

Why retrying doesn't close the gap

The natural first fix is to retry the Kafka publish:

JAVA
try {
    kafkaTemplate.send(event);
} catch (Exception e) {
    retry();
}

That helps when Kafka is briefly unavailable or the network blips. It doesn't help with a crash. If the database commit succeeds and the process dies before the retry is recorded anywhere, what tells the restarted service that order 42 still needs an event? Nothing. The intention to retry lived only in memory.

That's the key idea behind the outbox: the fact that an event still needs publishing must itself be durable. Instead of trying to make PostgreSQL and Kafka commit together, record the future publication inside the one transaction PostgreSQL already knows how to make atomic.

Writing the event in the same transaction

Instead of updating the order inside the transaction and publishing afterwards, the transaction does both writes to the database: update the order, and insert a row describing the event into an outbox table.

Diagram

One Database Transaction

Application

orders

outbox_events

A simple outbox table:

SQL
CREATE TABLE outbox_events (
    id UUID PRIMARY KEY,
    aggregate_type VARCHAR(100) NOT NULL,
    aggregate_id VARCHAR(255) NOT NULL,
    event_type VARCHAR(150) NOT NULL,
    payload JSONB NOT NULL,
    aggregate_version BIGINT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    published_at TIMESTAMPTZ
);

The service makes the business change and records the event together:

JAVA
@Transactional
public void markOrderPaid(
    UUID orderId,
    Payment payment
) {
    Order order =
        orderRepository.findById(orderId)
            .orElseThrow();

    order.markPaid(payment.id());

    orderRepository.save(order);

    OutboxEvent event =
        OutboxEvent.create(
            UUID.randomUUID(),
            "order",
            orderId.toString(),
            "OrderPaid",
            order.version(),
            serialize(
                new OrderPaid(
                    orderId,
                    payment.id(),
                    order.version()
                )
            )
        );

    outboxRepository.save(event);
}

Now the database guarantees that either the order update and the outbox row both commit, or neither does. Kafka hasn't become part of the PostgreSQL transaction. What's changed is that a successful commit can no longer leave the system with no record that an event still needs to go out.

Publishing from the outbox

After the commit, the order is PAID and the outbox holds OrderPaid(order_42). Kafka may know nothing yet, and that's fine. The guarantee we wanted is that if the database says the change happened, durable evidence exists that the event must be published. A separate process, the relay, handles delivery:

Diagram

one transaction

same transaction

Order Service

Business Tables

Outbox

Outbox Relay

Kafka

Consumers

Publishing is no longer a fragile continuation of the original request; it's durable work. The simplest relay polls for unpublished rows:

SQL
SELECT *
FROM outbox_events
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 100;

and publishes each one, marking it published afterwards:

TS
for (const event of events) {
  await kafka.send({
    topic: topicFor(event.eventType),
    messages: [
      {
        key: event.aggregateId,
        value: event.payload,
      },
    ],
  });

  await markPublished(event.id);
}

If Kafka is down, the rows wait in the database; when Kafka recovers, the relay carries on. The database has become a durable handoff point between the synchronous business transaction and asynchronous messaging.

One relay may eventually become a bottleneck, and several relays running the same query would pick the same rows. In PostgreSQL, FOR UPDATE SKIP LOCKED lets workers split the work, each skipping rows another transaction has already locked:

SQL
SELECT *
FROM outbox_events
WHERE published_at IS NULL
ORDER BY created_at
FOR UPDATE SKIP LOCKED
LIMIT 100;

That scales the relay. It still doesn't make publishing exactly once.

Duplicates are the price

Look at the relay's steps: read the event, publish it, Kafka acknowledges, then update published_at. If the relay crashes after Kafka acknowledges but before the database update, the row still looks unpublished, and after a restart the relay publishes it again.

Diagram
KafkaRelayOutboxKafkaRelayOutboxCrash before DB updateevt_892Publish evt_892ACKevt_892 againPublish evt_892 again

The outbox solved "event permanently lost", not "event published more than once". AWS's guidance says the same and recommends making consumers idempotent. So the practical delivery contract is at least once. That's not a flaw in the pattern; it's the intended trade. A duplicate you can detect is much better than a state change whose event silently vanished.

Note

The outbox turns an ambiguous dual-write failure into a durable retry. Idempotent consumers are what make that retry safe.

Idempotent consumers

Every outbox event needs a stable ID, created once with the row and reused on every publish attempt. Never generate a new ID per delivery.

JSON
{
  "eventId": "evt_892",
  "eventType": "OrderPaid",
  "aggregateId": "order_42",
  "aggregateVersion": 7,
  "payload": {
    "orderId": "order_42",
    "paymentId": "pay_81"
  }
}

A consumer can then recognise that it has already processed evt_892 instead of treating each delivery as a new event. A common way to do this is an inbox table on the consumer side:

SQL
CREATE TABLE processed_events (
    consumer_name VARCHAR(100) NOT NULL,
    event_id UUID NOT NULL,
    processed_at TIMESTAMPTZ NOT NULL DEFAULT now(),
    PRIMARY KEY (
        consumer_name,
        event_id
    )
);

The consumer records the event ID and makes its own change in the same local transaction:

JAVA
@Transactional
public void handle(OrderPaid event) {
    boolean inserted =
        inboxRepository.insertIfAbsent(
            "fulfillment",
            event.eventId()
        );

    if (!inserted) {
        return;
    }

    fulfillmentRepository.createFor(
        event.orderId()
    );
}

What matters isn't the table name but that the "processed" marker and the business change commit together. Then one, two or three deliveries all end with exactly one fulfilment record. Outbox on the producer side, inbox (or another idempotent effect) on the consumer side.

Event identity isn't always business identity, though. Two different events, evt_A and evt_B, might both say RefundRequested(refund_42). Deduplicating on event ID alone would let both refunds run. For irreversible or financial effects you often also need a stable business identifier, which the database can enforce:

SQL
CREATE UNIQUE INDEX uniq_refund_operation
ON refunds(external_refund_id);

Event deduplication answers "have I processed this message?" Business idempotency answers "have I already done this action?" Robust systems often need both.

Ordering

Reliable delivery doesn't guarantee useful order. If one order produces OrderPaid (version 5) and then OrderCancelled (version 6), but a consumer receives them the other way round, a simple consumer ends up in the wrong state. AWS's guidance calls out ordering as a separate concern for this reason.

Two things help. First, use the aggregate ID (here, the order ID) as the Kafka key, so all events for one order land on the same partition, where Kafka preserves their order:

Diagram

order_42 v5

order_42 v6

order_77 v3

Kafka Partition 1

Kafka Partition 2

That doesn't give a global order across every event, but it gives something usually more useful: ordered changes per order.

Second, include the aggregate version in each event so consumers can defend themselves. If a consumer already has version 7 for order_42 and receives version 6, it can ignore the stale event:

TS
if (event.aggregateVersion <= current.version) {
  return;
}

A gap is meaningful too: holding version 5 and receiving version 7 suggests version 6 is missing or delayed. Depending on the design, the consumer can wait, fetch the current state from the source, or reconcile. Ordering correctness shouldn't rely entirely on every delivery path behaving perfectly; put the information in the event itself.

Polling versus change data capture

Polling works, but it keeps asking the database "anything new?" The alternative is change data capture (CDC): reading committed changes from the database's own log (PostgreSQL's write-ahead log, or WAL) and turning outbox inserts into messages.

Diagram

business + outbox transaction

Application

PostgreSQL

WAL / Change Log

Debezium

Kafka

Debezium's Outbox Event Router is built for this. The application still writes the business change and the outbox row in one transaction; Debezium relays committed outbox rows to Kafka.

CDC moves complexity rather than removing it. A polling relay means a scheduler, row claiming, relay workers and checkpoints. CDC means the WAL, a Debezium connector and its offsets, Kafka Connect and connector configuration. That's often a good trade, especially if you already run CDC infrastructure, but the real question is which delivery mechanism you can operate, observe, recover and replay with confidence.

CDC also makes it tempting to publish raw row changes, such as before: {status: PENDING}, after: {status: PAID}. Sometimes that's the right contract. Often it leaks the producer's table design into every consumer. A semantic event says a business fact (OrderPaid) rather than a storage fact (orders.status changed from PENDING to PAID). Debezium's outbox router supports the semantic approach: the application writes an explicit event, and CDC just carries it.

Running the outbox in production

Once important transactions write outbox rows, the table is production infrastructure. It affects write throughput, indexes, storage growth, replication, vacuuming, relay throughput and cleanup. At 10,000 events per second, cleanup stopping means 864 million rows a day.

Watch age, not just count. 100,000 unpublished events isn't necessarily bad if the relay publishes 200,000 a second. If the oldest has been waiting 45 minutes, something is stuck. Useful metrics:

  • pending count and age of the oldest pending event
  • creation rate and publish rate
  • publish failures and duplicate publications

A backlog is a rate imbalance, so the relationship between creation rate and publish rate tells you more than either alone.

The relay is allowed to fall behind. That's one of the benefits. If Kafka is down for 30 seconds, orders still commit and their events wait, so a broker blip doesn't become an order outage. But the buffer isn't infinite: the database needs space and write headroom for realistic interruptions, and operators should know how long the relay can be down before the backlog becomes dangerous.

Cleanup is part of the design. Published rows can be deleted straight away, kept for a while, archived, or moved into audit history. Deleting aggressively keeps the table small; keeping rows helps debugging and reconciliation. At high volume, partitioning the table by time often makes cleanup safer than running huge DELETEs.

Why not Kafka transactions or two-phase commit?

Kafka transactions can atomically combine consuming records, producing records and committing consumer offsets, as long as everything stays inside Kafka. They don't make a PostgreSQL commit part of the same transaction. Confluent's Transactions in Apache Kafka is explicit: if processing has side effects on other storage systems, the transaction APIs alone aren't enough for exactly-once processing. A Kafka transaction plus a PostgreSQL transaction is still two independently committing systems.

Two-phase commit (2PC) coordinates multiple resources: a coordinator asks each participant to prepare, and only if all are ready does it tell them to commit. That gives stronger atomicity when every participant supports the same protocol, but many brokers, cloud services, NoSQL databases and third-party APIs don't take part in XA-style transactions, and 2PC couples participants tightly with more complicated recovery when the coordinator fails.

So for many event-driven systems, the preferred model is: a local ACID transaction, durable event intent, asynchronous publication and idempotent consumption. It gives up instant cross-system atomicity in exchange for recoverability and looser coupling.

Outbox and sagas

Extend the workflow: order service, then payment, inventory and shipping, each owning its own data.

Diagram

Order Created

Payment Authorized

Inventory Reserved

Shipment Created

An outbox ensures each service reliably publishes the changes it commits locally. It doesn't make the whole workflow one transaction. If payment authorisation succeeds and inventory reservation fails later, rolling back the order service's database can't undo the authorisation at the payment provider. The workflow needs a compensating action, such as releasing the authorisation. That's the job of a saga: a sequence of local transactions where each failure step triggers compensation for the steps before it. The outbox makes each service's part reliable; the saga coordinates the business outcome across services over time.

Compensation also isn't rollback. Charging a customer and then refunding them leaves a balance similar to never charging them, but the history records two facts, "charged" and "refunded". That matters for audit, notifications, financial reporting, support and compliance. Distributed workflows usually move forward through compensation rather than pretending the past didn't happen.

Reconciliation

Even with an outbox, idempotency, CDC and sagas, I still want reconciliation, because complex systems eventually fail in ways nobody listed in advance. If 10,000 orders are PAID but only 9,998 OrderPaid events were observed, the system should be able to say which two, and repair them.

Stripe's article on Ledger, their system for tracking money movement, is a strong example. Ledger keeps immutable records and runs explicit completeness checks to catch cases where its data diverges from what producer systems actually did. Correctness isn't only preventing divergence; it's also detecting, explaining and repairing it when prevention fails.

Reconciliation can be simple. If every paid order should have an outbox event, a periodic query finds the exceptions:

SQL
SELECT o.id
FROM orders o
LEFT JOIN outbox_events e
    ON e.aggregate_id = o.id::text
   AND e.event_type = 'OrderPaid'
WHERE o.status = 'PAID'
  AND e.id IS NULL;

Anything other than zero rows should alert someone. The same idea continues downstream: paid orders against fulfilment records, refunds against the payment provider's refund IDs.

The repair path has to be safe too. If fixing a missing event means re-emitting it, and replay could charge a customer twice or create duplicate fulfilment, the system isn't really repairable. That's why stable event IDs and business IDs matter in practice: they let you say "we can safely replay this" without starting a second incident.

Designing the events

Outbox rows can outlive deployments, so producers and consumers from different versions may see the same backlog. If version 1 writes {"eventType": "OrderPaid", "orderId": "42"} and version 2 also expects paymentId and currency, a backlog that survives the deploy means new consumer code reading old events. Event schemas need the same compatibility care as database schemas or public APIs. A useful envelope:

JSON
{
  "eventId": "evt_892",
  "eventType": "OrderPaid",
  "schemaVersion": 2,
  "aggregateId": "order_42",
  "aggregateVersion": 7,
  "occurredAt": "2026-10-02T23:43:00Z",
  "payload": {}
}

Keep event time separate from publish time. If something happens at 10:00:00 but Kafka is down and the event is published at 10:02:30, occurredAt is when the business fact happened and the publish time is when transport finished. Collapsing them makes downstream analytics mistake delivery delay for business timing. The outbox gives you a natural place to keep both.

Name events after business facts (OrderPaid, InvoiceIssued, ShipmentCreated, SubscriptionCancelled), not table changes like orders_row_updated. Consumers learn what happened without depending on how the producer stores it, so the producer's schema can change without breaking them.

Commands and events are different, too. A command like PayOrder means "please try to do this". An event like OrderPaid means "this already happened". An event describing a committed fact shouldn't escape before that fact has actually committed, and the outbox enforces exactly that by writing both in the same transaction.

Putting it together

The most useful mental model is the boundary of the local transaction:

Diagram

Local ACID Transaction

Business State

Outbox Event

Relay / CDC

Kafka

Consumer

Consumer Database

Inside the boundary, things are atomic. Outside it, they're asynchronous, retryable, possibly duplicated and eventually consistent. The outbox doesn't guarantee exactly-once delivery or effects, global ordering, instant publication, correct schemas, unlimited backlog or cross-service rollback. It guarantees something narrower and very useful: if the business transaction commits, durable evidence of the event exists in that same transaction. Everything after that still needs engineering.

I like checking a design against each crash point:

FailureIntended result
Crash before the transactionNothing committed
Business write failsOutbox insert rolls back
Outbox insert failsBusiness change rolls back
Crash right after commitOutbox row waits for the relay
Kafka unavailableOutbox backlog builds up
Relay publishes, then crashesEvent may be published twice
Consumer crashes after processingEvent may be redelivered
Duplicate arrivesConsumer handles it idempotently
Events arrive lateVersions and timestamps keep their meaning
Relay stops for hoursBacklog is visible and can be drained

If every row has a deliberate answer, the design is in good shape. For a Spring, PostgreSQL and Kafka service, the whole thing might look like this:

Diagram

HTTP Request

Spring Service

PostgreSQL

orders

outbox_events

Debezium / Outbox Relay

Kafka

Consumer Service

processed_events

Consumer State

Key takeaways

  • Publishing before or after a database commit can't make two systems agree. Write the event into an outbox table in the same transaction as the business change.
  • Publish from the outbox with a relay or CDC, and expect at-least-once delivery. Give every event a stable ID.
  • Make consumers idempotent with an inbox table or business-level unique keys, and commit the dedupe marker with the change.
  • Key events by aggregate ID and include a version so consumers can handle out-of-order or missing events.
  • Treat the outbox as production infrastructure: monitor the oldest pending age and rates, and design cleanup.
  • Use sagas for workflows across services, and run reconciliation so you can find and safely repair whatever slips through.

References