Skip to main content
Back to Knowledge Library
Distributed Systems5 min read

Designing Idempotent Asynchronous Pipelines: Transactional Outbox & Retry Budgets

Why naive 'write to database, then publish to queue' fails in production, how the Transactional Outbox pattern closes the dual-write gap, and how to design consumers that survive duplicate deliveries gracefully.

AK

J Ananthakrishnan

Developer · SAP Labs India

Distributed SystemsEvent-Driven ArchitectureBackend EngineeringPostgreSQLPython

The Dual-Write Trap

One of the most common failure modes in backend services hides inside ten innocent-looking lines of code:

  1. Persist a domain state change inside a relational database transaction.
  2. Publish a domain event to a message broker so downstream services can react asynchronously.

In local testing, this works every single time. In production, the process crashes, the network blips, or the broker times out between step 1 and step 2. Now your database says a shipment or order was confirmed, while downstream billing, notifications, and analytics never heard about it.

Reversing the order (publishing before committing) merely trades a silent drop for a phantom event: downstream systems act on state that was rolled back.

Architecture: Closing the Gap with a Transactional Outbox

The Transactional Outbox pattern eliminates the dual-write race by making the database the single commit boundary. Instead of calling the broker inline inside your request handler, you write the domain row and an outbox_events row inside the same ACID transaction.

Transactional Outbox + Idempotent Consumer Flow

Command Service

Single DB Transaction

Domain + Outbox Table

Atomic Commit

Outbox Relay / CDC

SKIP LOCKED Poller

Message Broker

At-Least-Once Delivery

Idempotent Consumer

Dedup Key + State Guard

Because both rows commit or roll back together, an event can never exist without its corresponding state change, and no committed state change can silently lose its event.

Schema Design

Keep the outbox table lean and indexed for fast polling:

migrations/001_outbox.sql
CREATE TABLE outbox_events (
    event_id       UUID PRIMARY KEY,
    aggregate_type VARCHAR(64) NOT NULL,
    aggregate_id   VARCHAR(64) NOT NULL,
    event_type     VARCHAR(128) NOT NULL,
    payload        JSONB NOT NULL,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    published_at   TIMESTAMPTZ NULL,
    attempts       INT NOT NULL DEFAULT 0
);
 
-- Partial index keeps the hot unpublished set tiny and fast to scan
CREATE INDEX idx_outbox_unpublished
    ON outbox_events (created_at)
    WHERE published_at IS NULL;

Notice the partial index (WHERE published_at IS NULL). Even if you retain millions of historical rows for auditing before archiving them, the relay worker only ever scans the small slice of pending events.

Polling Safely Across Multiple Workers

When scaling horizontally, multiple relay instances may query outbox_events concurrently. PostgreSQL's FOR UPDATE SKIP LOCKED lets workers claim disjoint batches cleanly without blocking one another:

worker/outbox_relay.py
from dataclasses import dataclass
from typing import Protocol
import psycopg
 
 
class BrokerPublisher(Protocol):
    def publish(self, topic: str, key: str, payload: dict) -> None: ...
 
 
@dataclass(frozen=True)
class RelayConfig:
    batch_size: int = 50
    max_attempts: int = 8
 
 
def relay_batch(conn: psycopg.Connection, broker: BrokerPublisher, cfg: RelayConfig) -> int:
    with conn.transaction():
        rows = conn.execute(
            """
            SELECT event_id, aggregate_id, event_type, payload
            FROM outbox_events
            WHERE published_at IS NULL AND attempts < %s
            ORDER BY created_at ASC
            LIMIT %s
            FOR UPDATE SKIP LOCKED
            """,
            (cfg.max_attempts, cfg.batch_size),
        ).fetchall()
 
        if not rows:
            return 0
 
        published_ids = []
        for event_id, aggregate_id, event_type, payload in rows:
            broker.publish(
                topic=event_type,
                key=aggregate_id,
                payload={"event_id": str(event_id), **payload},
            )
            published_ids.append(event_id)
 
        conn.execute(
            """
            UPDATE outbox_events
            SET published_at = NOW(), attempts = attempts + 1
            WHERE event_id = ANY(%s)
            """,
            (published_ids,),
        )
        return len(published_ids)

Trade-offs: Polling vs. Change Data Capture (CDC)

DimensionSKIP LOCKED PollerLog-Based CDC (e.g., Debezium)
Operational FootprintMinimal (just a stateless worker)Higher (requires WAL connectors & Kafka Connect)
Publish Latency100ms – 1s depending on intervalSub-100ms near real-time
Database LoadModest if partial-indexedMinimal read load on primary tables
Best FitEarly-to-mid scale, fast iterationHigh-throughput event backbones

Starting with a partial-indexed poller and migrating to CDC only when throughput or latency demands it keeps operational complexity proportionate to actual scale.

Designing Consumers for At-Least-Once Delivery

Even with a rock-solid outbox, if the relay publishes a message and crashes before marking published_at = NOW(), the next relay cycle will publish the same event_id again. At-least-once delivery is inevitable, which means idempotent consumers are mandatory.

There are two complementary layers of consumer idempotency:

  1. Natural Domain Guards: Structure state transitions as compare-and-swap checks (e.g., UPDATE invoices SET status = 'PAID' WHERE id = $1 AND status = 'PENDING').
  2. Processed-Event Ledger: Record every consumed event_id in a processed_events table inside the same database transaction as the side effect.
consumer/idempotent_handler.py
import psycopg
 
 
def handle_order_confirmed(conn: psycopg.Connection, event: dict) -> bool:
    """Returns True if processed, False if safely deduplicated."""
    with conn.transaction():
        inserted = conn.execute(
            """
            INSERT INTO processed_events (event_id, processed_at)
            VALUES (%s, NOW())
            ON CONFLICT (event_id) DO NOTHING
            RETURNING event_id
            """,
            (event["event_id"],),
        ).fetchone()
 
        if inserted is None:
            # Duplicate delivery: already applied atomically
            return False
 
        apply_fulfillment_side_effect(conn, event)
        return True

Key Lessons Learned

  • Atomicity beats optimism: Never assume two independent networked systems will succeed together.
  • Keep the outbox thin: Store immutable event payloads and archive published rows on a schedule so table bloat never creeps in.
  • Idempotency is a design invariant, not an afterthought: Pass a deterministic event_id from day one and test duplicate delivery explicitly in integration suites.
Found this engineering note useful? Share it with a teammate.
LinkedInX

Continue Reading

Related Articles