Skip to content
Veltoryx Technologies
Distributed SystemsKafkaPostgreSQLSystem Design·7 min read

The Dual-Write Trap: Why Transactional Outbox is Mandatory in Event-Driven Systems

Why updating a database and publishing a message to Kafka in the same HTTP handler inevitably corrupts your data, and how to implement the Transactional Outbox pattern with zero message loss.

V

Vivek Adarsh

Founder & Systems Architect, Veltoryx Technologies · Published November 4, 2026

In modern backend engineering, few architecture bugs cause more catastrophic data discrepancies than the dual-write anti-pattern.

Consider a standard e-commerce or food delivery order placement service. An HTTP request arrives from a customer. The application must perform two simple tasks:

  1. Insert the new order into a relational database (PostgreSQL).
  2. Publish an OrderPlaced event to an Apache Kafka topic so inventory, notification, and dispatch microservices can start processing.

Almost every junior and mid-level engineer starts with code that looks like this:

java
@Transactional
public void placeOrder(OrderRequest request) {
    // Step 1: Save to PostgreSQL
    Order order = orderRepository.save(new Order(request));

    // Step 2: Publish event to Kafka
    kafkaTemplate.send("order-events", order.getId(), new OrderPlacedEvent(order));
}

This code looks clean. In unit tests, it passes with 100 percent flying colors. In low-traffic staging environments, it appears flawless.

In production at scale, this code is a ticking time bomb. It will silently drop events, create phantom orders, and desynchronize your database from downstream services.

Here is why dual writes fail, why traditional distributed transactions are not the answer, and how to implement the Transactional Outbox Pattern to achieve bulletproof reliability.

The Dual-Write Trap: The Four Failure Modes

When your application attempts to mutate two separate stateful systems (a database and a message broker) without a distributed consensus protocol, failure is mathematically guaranteed.

text
                  [ Application Service ]
                     /                \
         (Write 1)  /                  \  (Write 2)
                   ▼                    ▼
          [ PostgreSQL DB ]       [ Apache Kafka ]

Let us examine the four failure modes that occur in production:

1. Database Commits, Kafka Crashes

The order is successfully saved to PostgreSQL. The code proceeds to line 6 to publish to Kafka. At that exact microsecond:

  • The network drops between the application server and the Kafka broker.
  • The Kafka cluster experiences an in-flight partition rebalance.
  • The JVM process runs out of memory (OOM) or is terminated by a Kubernetes rolling deployment.

The result: The customer has been charged, and the order exists in PostgreSQL. However, the event was never published to Kafka. The kitchen never receives the ticket, the delivery fleet is never notified, and the customer waits indefinitely for food that will never arrive.

2. Kafka Publishes, Database Fails to Commit

What if we reverse the order? What if we publish to Kafka first, and then commit to the database?

java
public void placeOrder(OrderRequest request) {
    // Anti-pattern variant: Publish first, save second
    kafkaTemplate.send("order-events", request.getId(), new OrderPlacedEvent(request));
    orderRepository.save(new Order(request)); // What if this throws an exception?
}

If the PostgreSQL transaction fails (for example, due to a unique constraint violation, a dead lock, or an exhausted connection pool), the event is already flying across Kafka. Downstream inventory services decrement stock, payment is captured, and warehouse workers begin packaging an order that does not exist in the primary database.

3. The Hidden Rollback Trap

Notice the @Transactional annotation on the initial Java snippet:

java
@Transactional
public void placeOrder(OrderRequest request) {
    orderRepository.save(new Order(request));
    kafkaTemplate.send("order-events", order.getId(), new OrderPlacedEvent(order));
    // The database transaction only commits AFTER this method exits!
}

In Spring Boot and most ORM frameworks, the actual database COMMIT command executes when the method completes, after the Kafka message has already been written to the socket.

If the database commit fails during the commit phase (for instance, a deferred constraint check fails or the database connection drops during commit), the message is already in Kafka, but the database rolled back.

4. Downstream Race Conditions

Even if both operations succeed, downstream consumer race conditions occur. A downstream service receiving the Kafka event might immediately execute an HTTP callback to GET /orders/{id} before the upstream database transaction has finished committing, resulting in a spurious 404 Not Found.

The Solution: The Transactional Outbox Pattern

The Transactional Outbox pattern guarantees that a database write and an event publication succeed or fail together as a single atomic unit, without using distributed transactions.

The core insight is simple: Do not write to Kafka directly in the business transaction. Instead, write the event into an outbox table inside the exact same local database transaction.

text
[ Incoming Request ]
         │
         ▼
[ Begin ACID Transaction ]
 ├─► INSERT INTO orders (...)
 └─► INSERT INTO outbox_events (...)
[ Commit ACID Transaction ] ──► (Guaranteed 100% Atomic)
         │
         ▼ (Asynchronous Reliable Relay)
[ Debezium CDC or Outbox Poller ] ──► [ Publish to Kafka ]

Because both the business entity (orders) and the event record (outbox_events) reside in the same relational database, the local ACID transaction guarantees that either both are saved, or neither is saved.

The Outbox Schema (PostgreSQL)

sql
CREATE TABLE orders (
    id UUID PRIMARY KEY,
    customer_id UUID NOT NULL,
    total_amount_cents INT NOT NULL,
    status VARCHAR(32) NOT NULL,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

CREATE TABLE outbox_events (
    id UUID PRIMARY KEY,
    aggregate_type VARCHAR(64) NOT NULL,    -- e.g. "Order"
    aggregate_id VARCHAR(64) NOT NULL,      -- e.g. Order UUID
    event_type VARCHAR(64) NOT NULL,        -- e.g. "OrderPlaced"
    payload JSONB NOT NULL,                 -- Full event JSON
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Index for polling relay engines (if not using CDC)
CREATE INDEX idx_outbox_unprocessed ON outbox_events(created_at ASC);

The Refactored Application Service

java
@Transactional
public Order placeOrder(OrderRequest request) {
    // 1. Create and persist business aggregate
    Order order = new Order(UUID.randomUUID(), request.getCustomerId(), request.getAmount());
    orderRepository.save(order);

    // 2. Persist outbox event in the EXACT SAME local transaction
    OutboxEvent event = new OutboxEvent(
        UUID.randomUUID(),
        "Order",
        order.getId().toString(),
        "OrderPlaced",
        toJson(new OrderPlacedPayload(order))
    );
    outboxRepository.save(event);

    // Both inserts commit atomically. Zero partial writes possible.
    return order;
}

Relaying Events to Kafka: CDC vs Polling

Once the event is safely committed to the outbox_events table, an asynchronous process relays the records to Kafka. There are two primary architectural strategies:

In high-throughput distributed systems, querying the database repeatedly (SELECT * FROM outbox_events ...) introduces unnecessary query load and database lock contention.

Debezium solves this by reading the database transaction commit log directly (PostgreSQL Write-Ahead Log / WAL):

text
[ Application ] ──► [ PostgreSQL ] ──► [ WAL (Write-Ahead Log) ]
                                                │
                                                ▼
                                    [ Debezium Kafka Connect ]
                                                │
                                                ▼
                                    [ Apache Kafka Topic ]
  • Zero Database Query Overhead: Debezium streams directly from the WAL at the filesystem level.
  • Sub-10ms Latency: Events appear on Kafka partitions almost immediately after the database commit completes.
  • Guaranteed In-Order Processing: Events are emitted in the exact chronological sequence in which the transactions committed.

Strategy 2: Scheduled Polling Publisher (Simpler for Small Teams)

For teams without Kafka Connect or Debezium infrastructure, a background worker process can poll the table:

java
@Scheduled(fixedDelay = 500)
public void relayOutboxEvents() {
    List<OutboxEvent> events = outboxRepository.fetchBatch(100);
    for (OutboxEvent event : events) {
        kafkaTemplate.send(event.getAggregateType().toLowerCase() + "-events", event.getAggregateId(), event.getPayload())
            .whenComplete((result, ex) -> {
                if (ex == null) {
                    outboxRepository.deleteById(event.getId());
                }
            });
    }
}

The Golden Invariant: At-Least-Once Delivery and Consumer Idempotency

The Transactional Outbox pattern guarantees At-Least-Once Delivery. It ensures that no event is ever lost.

However, in distributed networks, at-least-once delivery implies that duplicate events can occur (for example, if Debezium publishes an event to Kafka, but the offset commit fails before acknowledgment).

Therefore, every downstream consumer must implement Consumer Idempotency:

sql
CREATE TABLE processed_events (
    event_id UUID PRIMARY KEY,
    processed_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

When a downstream microservice consumes an OrderPlaced event:

  1. It checks if the event_id exists in its processed_events table.
  2. If the event_id is already present, it acknowledges the message and safely ignores the duplicate payload.
  3. If new, it processes the business logic and inserts the event_id within its local database transaction.

Summary Checklist for System Design Interviews

When answering distributed transaction questions in system design interviews, walk the interviewer through this concise architectural checklist:

  • State the dual-write flaw immediately: Never claim that calling repository.save() and kafka.send() in the same method is safe. Call out the crash boundaries and rollback risks.
  • Introduce the Transactional Outbox: Explain that saving business state and event state in the same relational ACID transaction guarantees atomicity.
  • Describe the relay pipeline: Differentiate between Debezium CDC reading the PostgreSQL WAL versus a polling publisher using SKIP LOCKED.
  • Emphasize idempotency: Remind the interviewer that outbox architectures provide at-least-once delivery, making consumer deduplication mandatory.
Interactive Engineering Platform

Experiment with Kafka Partitions & Topologies

Calculate consumer lag, broker throughput, and replication quotas with our free browser calculators.

Written by Vivek Adarsh, Founder & Systems Architect, Veltoryx Technologies.

Related Engineering Articles