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.
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:
- Insert the new order into a relational database (PostgreSQL).
- Publish an
OrderPlacedevent 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:
@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.
[ 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?
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:
@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.
[ 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)
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
@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:
Strategy 1: Change Data Capture (CDC via Debezium) - Recommended for High Scale
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):
[ 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:
@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:
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:
- It checks if the
event_idexists in itsprocessed_eventstable. - If the
event_idis already present, it acknowledges the message and safely ignores the duplicate payload. - If new, it processes the business logic and inserts the
event_idwithin 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()andkafka.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.
Experiment with Kafka Partitions & Topologies
Calculate consumer lag, broker throughput, and replication quotas with our free browser calculators.
Related Engineering Articles
Java Backend Developer 1st Round Interview: 20 Questions Being Asked in 2026
A battle-tested guide to the top 20 core Java, JVM, Spring Boot, JPA, and distributed systems questions asked in senior first-round technical interviews in 2026—with code examples, root causes, and production fixes.
Vivek Adarsh
Nov 5, 2026
Java DSA Interview – Complete Methods & Syntax Cheat Sheet
The ultimate quick-reference cheat sheet for Java DSA coding interviews — covering essential Java 8+ syntax, collection methods, and LeetCode problem-solving patterns.
Vivek Adarsh
Nov 24, 2026
Building Veltoryx: Next.js 16, OpenNext, and In-Browser WebGPU AI on Cloudflare Workers for $0/mo
How we architected a full-stack engineering platform serving 500+ interactive lessons, 25 developer tools, and an AI suite entirely on Cloudflare edge isolates with zero cloud infrastructure spend.
Vivek Adarsh
Nov 5, 2026