Replacing distributed two-phase commit with Saga workflows is the standard recipe for microservices consistency. But running a local database transaction alongside a broker publish creates the dual-write problem, and compensating actions that arrive out of order can silently resurrect canceled state. Here is a deep dive into the real failure modes, the transactional outbox, and the idempotent handlers that actually prevent them.

In multi-tenant microservices architectures, keeping cross-service state consistent without a global lock means replacing one monolithic ACID transaction with a distributed Saga: a sequence of local transactions, each with a compensating action that undoes it. Sagas buy you eventual consistency, but when message brokers hit network partitions, worker crashes, or out-of-order delivery during a rollback, a naive Saga can leave services in inconsistent, half-committed states. Here is what actually goes wrong, and the two patterns that fix it.

1. The Dual-Write Problem

The foundational hazard is mutating local database state and publishing a domain event to a broker (Kafka, RabbitMQ) as two separate operations in one request. They are two systems with no shared transaction, so any failure between them leaves the two out of sync.

// NAIVE ANTI-PATTERN: non-atomic dual write export async function createOrderNaive(req: Request, res: Response) { // 1. Local database mutation const order = await db.orders.create({ data: { tenantId: req.body.tenantId, amount: req.body.amount, status: 'PENDING' } }); // FAILURE VECTOR: if the broker times out or the process crashes HERE, // the order exists but no event is ever published. await kafkaProducer.send({ topic: 'order-events', messages: [{ key: order.id, value: JSON.stringify({ event: 'ORDER_CREATED', orderId: order.id }) }] }); return res.status(201).json(order); } 

The Two Failure Directions

  • DB commits, broker never gets the event: The row is written, the send times out or the process dies. Payment and Inventory never hear about the order, which sits in limbo forever.
  • Broker gets the event, DB rolls back: If you publish before committing, a later constraint error aborts the local transaction after consumers have already received an event for an order ID that no longer exists. Downstream services act on a ghost.

2. Out-of-Order Compensations

When a later step fails (Payment declines the card), the orchestrator sends compensating actions backward to undo earlier steps (cancelOrder, releaseInventory). The trap is that these can arrive out of order relative to the original events.

Kafka preserves order within a single partition, so keying every event for an order by its order ID keeps that order's events in sequence on one partition. But that guarantee does not hold across topics, across services, or through producer retries and redelivery. So you cannot assume a CANCEL_ORDER always lands after its CREATE_ORDER:

  • t1: The Order Service receives CANCEL_ORDER for order_100. There is no such row yet, so a naive handler treats it as a no-op and returns 200.
  • t2: 300 ms later the delayed CREATE_ORDER arrives. A naive handler runs INSERT ... status = 'ACTIVE' and resurrects an order that was already canceled.

3. Fix 1: The Transactional Outbox

Kill the dual write by writing the event into an outbox table in the same local transaction that mutates state. The row and its event commit together or not at all. A separate process (Debezium reading the WAL, or a polling worker) then ships outbox rows to Kafka.

-- One atomic local transaction: state change + event BEGIN; INSERT INTO orders (id, tenant_id, amount, status) VALUES ('order_100', 'tenant_42', 15000, 'PENDING'); INSERT INTO outbox_events (id, aggregate_type, aggregate_id, payload, created_at) VALUES ( gen_random_uuid(), 'ORDER', 'order_100', '{"event_type": "ORDER_CREATED", "tenant_id": "tenant_42", "amount": 15000}'::jsonb, now() ); COMMIT; 

The relay that forwards outbox rows delivers at least once: after it publishes to Kafka it may crash before marking the row done, so the same event can be sent twice. That is fine as long as consumers are idempotent (next section). Have the relay mark rows with a published_at timestamp or delete them once Kafka acks, and index the unprocessed rows so the poller stays cheap.

4. Fix 2: Idempotent, Order-Agnostic Handlers

At-least-once delivery plus possible reordering means every handler must be safe to run more than once and in any order. For the create/cancel pair, a tombstone works: a cancel writes a CANCELED row even if the order was never seen, and a create refuses to overwrite it. The crucial part the naive version misses is that both handlers have to cooperate: a tombstone alone does nothing if the create handler ignores it.

The cancel handler writes (or upserts) a tombstone

// Compensating cancel: idempotent, safe even if CREATE hasn't arrived yet async handleCancelOrder(orderId: string, tenantId: string): Promise { const client = await this.db.connect(); try { await client.query('BEGIN'); // Write a CANCELED tombstone. If the row already exists, force it to // CANCELED, but skip the write when it is already canceled (idempotent). await client.query( `INSERT INTO orders (id, tenant_id, status, updated_at) VALUES ($1, $2, 'CANCELED', now()) ON CONFLICT (id) DO UPDATE SET status = 'CANCELED', updated_at = now() WHERE orders.status <> 'CANCELED'`, [orderId, tenantId] ); await client.query( `INSERT INTO outbox_events (id, aggregate_type, aggregate_id, payload, created_at) VALUES (gen_random_uuid(), 'ORDER', $1, '{"event_type":"ORDER_CANCELED"}', now())`, [orderId] ); await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); } } 

The create handler must respect the tombstone

This is the half the original pattern leaves out. If the create handler runs a plain INSERT ... 'ACTIVE', a pre-existing tombstone makes it fail with a primary-key violation, so the event redelivers and fails forever. If it upserts to ACTIVE, it resurrects the canceled order, the exact bug we are trying to prevent. The create must insert only when no row exists:

// Create handler: never overwrite a tombstone (or any existing row) async handleCreateOrder(orderId: string, tenantId: string, amount: number): Promise { await this.db.query( `INSERT INTO orders (id, tenant_id, amount, status, updated_at) VALUES ($1, $2, $3, 'ACTIVE', now()) ON CONFLICT (id) DO NOTHING`, [orderId, tenantId, amount] ); // If a CANCELED tombstone is already there, DO NOTHING keeps it canceled. // If the create simply arrives twice, the second is a harmless no-op. } 

I tested both orderings on PostgreSQL 16. Cancel-then-create leaves the row CANCELED (the create is a no-op, no error); duplicate deliveries of either event change nothing after the first. For richer state machines where any field can change out of order, carry a monotonically increasing version or sequence number per aggregate in the event and ignore any event whose version is not newer than the row's, which generalizes the tombstone idea to arbitrary updates. Tombstone rows also accumulate, so sweep canceled orders older than your retention window in a background job.

5. Executive Summary & Systems Rules

  • Never dual-write: Don't mutate the database and publish to a broker as two separate steps. Write the event to an outbox in the same local transaction and relay it with CDC or a poller.
  • Assume at-least-once and out-of-order: The outbox relay can send twice and compensations can overtake their originals, so every consumer must be idempotent and order-agnostic.
  • Make the whole pair cooperate: A tombstone only prevents resurrection if the create handler uses ON CONFLICT DO NOTHING (or a version check) to refuse to overwrite it. Fixing one handler is not enough.

Fighting data drift or ghost records across your microservices? I help teams design outbox pipelines, idempotent event handlers, and Saga orchestration that stays consistent under failure. Book a consultation →

Originally published on ctousman.com.