CodeBodh

Transactional Outbox Pattern: Idempotent Queues at Scale

Implement the transactional outbox pattern with PostgreSQL SKIP LOCKED relays, idempotent consumers, and dead-letter recovery in production.

Team CodeBodh By Team CodeBodh
Nov 28, 2026
10 min read
0 views
Transactional Outbox Pattern: Idempotent Queues at Scale

Executive Summary: Eliminating Dual-Write Data Loss in Distributed Backends

Whenever a backend service commits a PostgreSQL order row and then attempts to publish an OrderPaid event to RabbitMQ, Kafka, or Redis Streams in a separate network call, it introduces a classic dual-write race condition. If the worker crashes, hits a network timeout, or gets OOM-killed between the database COMMIT and the broker acknowledgment, the payment is recorded in PostgreSQL while downstream billing, email, and webhook workers never hear about it.

Adopting the transactional outbox pattern guarantees atomic state-and-event persistence without brittle Two-Phase Commit (2PC) protocols. By writing domain events into an outbox_events table inside the exact same ACID transaction as the business mutation—and pairing a concurrent FOR UPDATE SKIP LOCKED relay with idempotent consumers—teams achieve guaranteed at-least-once delivery under high concurrency.


1. Why Naive Dual-Writes and 2PC Break Down at Scale

Reversing the order of operations does not fix the dual-write bug. If you publish to the message broker before committing the database transaction, a subsequent PostgreSQL constraint violation or serialization rollback leaves phantom events flying through your worker fleet for records that do not exist. Worse, holding a database transaction open while waiting on an external broker round-trip starves PgBouncer connection pools during network hiccups.

Traditional distributed Two-Phase Commit (XA/2PC) protocols are rarely viable in cloud-native architectures because modern message brokers (Kafka, SQS, Redis Streams) and managed PostgreSQL services do not share a unified coordinator. As documented in the Microservices.io Transactional Outbox specification, storing the outgoing event in the primary database and relaying it asynchronously decouples availability from consistency.

+-----------------------------------------------------------------------+

|         Transactional Outbox & Idempotent Consumer Architecture       |
|---|
  1. API Request -> Single ACID PostgreSQL Transaction (BEGIN ... COMMIT)
     +--> INSERT INTO orders (...)
     +--> INSERT INTO outbox_events (id, aggregate_id, payload, status)
                                   |
                                   v
+-----------------------------------------------------------------------+
|  2. Concurrent Outbox Relay Workers (SELECT ... FOR UPDATE SKIP LOCKED)|
|     - Claims batch of 50 pending rows without blocking peer relays    |
|     - Injects W3C traceparent + event_id -> Publishes to Broker       |
|     - Marks rows published_at = now() (or increments retry_count)     |
+-----------------------------------------------------------------------+
                                   |
                      (At-Least-Once Delivery)
                                   v
+-----------------------------------------------------------------------+
|  3. Idempotent Downstream Consumer                                    |
|     - INSERT INTO processed_events (event_id) ON CONFLICT DO NOTHING  |
|     - Executes side effect only if row was newly inserted             |
+-----------------------------------------------------------------------+

2. Designing the Outbox Schema & Partial Index Strategy

An outbox table must remain fast for both high-frequency inserts and relay polling even after millions of events have flowed through it. A naive index on (status, created_at) bloats rapidly if you retain published rows for auditing. Instead, isolate the active backlog using a partial index—a core technique from PostgreSQL indexing strategies at scale—so the relay index only tracks unpublished rows.

  • UUIDv7 or Sequence Ordering: Store a monotonically increasing id BIGSERIAL or time-ordered UUID alongside aggregate_id so relays preserve causal event order per aggregate.
  • Scheduled Retry Column (available_at): Include a TIMESTAMPTZ column defaulting to now(). When a broker publish fails, update available_at = now() + backoff so failing events do not block healthy rows at the head of the queue.
  • Partitioning or Aggressive Pruning: Either delete published rows after 24 hours or partition outbox_events daily by created_at so old partitions drop instantaneously via DROP TABLE without triggering heavy VACUUM cycles.

3. Relay Mechanisms: Polling with SKIP LOCKED vs. Log-Tailing CDC

Two relay architectures dominate production systems: concurrent SQL polling relays and Change Data Capture (CDC) log-tailers such as Debezium reading PostgreSQL's Write-Ahead Log (WAL). In PostgreSQL, the SELECT ... FOR UPDATE SKIP LOCKED clause enables multiple stateless relay workers to claim distinct batches concurrently without lock contention or duplicate claims.

Publishing Pattern Atomicity Guarantee Relay Latency Operational Complexity Best Production Fit
Direct Dual-Write None (data loss on crash) < 5 ms Low Non-critical analytics or fire-and-forget logs
Polling Outbox (SKIP LOCKED) ACID Atomic (At-least-once) 20 ms – 250 ms Low–Moderate (no extra infra) PHP 8 / Go modular monoliths & SaaS backends
WAL CDC (Debezium + Kafka) ACID Atomic (At-least-once) < 10 ms High (Kafka Connect + replication slots) High-throughput multi-service Kafka meshes

For most teams running a modern PHP 8 modular monolith, a polling relay using SKIP LOCKED (optionally woken up immediately by PostgreSQL NOTIFY or a 50 ms tick) eliminates the operational overhead of managing Kafka Connect and WAL replication slot retention alerts.


4. Idempotent Consumers & Dead-Letter Quarantine

Because any outbox relay can crash after publishing a message to the broker but before committing published_at in PostgreSQL, the transactional outbox pattern delivers at-least-once—not exactly-once—semantics. Downstream consumers must therefore be strictly idempotent.

Avoid checking-then-inserting in application memory, which fails under concurrent worker retries. Instead, create a processed_events table with a unique constraint on (consumer_name, event_id) and execute INSERT ... ON CONFLICT DO NOTHING RETURNING event_id inside the consumer's own database transaction. If zero rows return, the event was already processed—acknowledge the broker message immediately and skip side effects. Route events exceeding max_attempts to a dead_lettered_at state with full error payloads and OpenTelemetry trace context preserved for operator replay.


5. Production PostgreSQL Schema & PHP 8.3 Outbox Implementation

The following PostgreSQL migration creates the outbox_events table, a tiny partial index covering only active pending rows, and the processed_events deduplication ledger:

-- Outbox & Idempotent Consumer Schema (PostgreSQL 15+)
CREATE TABLE IF NOT EXISTS outbox_events (
    id              BIGSERIAL PRIMARY KEY,
    event_id        UUID NOT NULL UNIQUE,
    aggregate_type  TEXT NOT NULL,
    aggregate_id    TEXT NOT NULL,
    event_type      TEXT NOT NULL,
    payload         JSONB NOT NULL,
    traceparent     TEXT,
    attempts        SMALLINT NOT NULL DEFAULT 0,
    available_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
    published_at    TIMESTAMPTZ,
    dead_lettered_at TIMESTAMPTZ,
    last_error      TEXT,
    created_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

-- Partial index keeps relay polling fast regardless of historical table size
CREATE INDEX IF NOT EXISTS idx_outbox_pending_poll
ON outbox_events (available_at ASC, id ASC)
WHERE published_at IS NULL AND dead_lettered_at IS NULL;

CREATE TABLE IF NOT EXISTS processed_events (
consumer_name   TEXT NOT NULL,
event_id        UUID NOT NULL,
processed_at    TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (consumer_name, event_id)
);

Inside your domain service, persist the business entity and the outbox event in a single atomic transaction. Never call the message broker inside this block:

<?php

declare(strict_types=1);

namespace App\Outbox;

use PDO;
use Throwable;

final readonly class OrderOutboxProducer
{
public function __construct(private PDO $pdo) {}

/**
 * Atomically records an order payment and queues an outbox event.
 *
 * @param array<string, mixed> $metadata
 */
public function markOrderPaid(
    string $orderId,
    int $amountCents,
    string $eventUuid,
    ?string $traceparent = null,
    array $metadata = []
): void {
    $this->pdo->beginTransaction();

    try {
        $orderStmt = $this->pdo->prepare(
            'UPDATE orders SET status = :status, paid_at = now() WHERE id = :id AND status = :expected'
        );
        $orderStmt->execute([
            ':status' => 'paid',
            ':id' => $orderId,
            ':expected' => 'pending',
        ]);

        $payload = json_encode([
            'order_id' => $orderId,
            'amount_cents' => $amountCents,
            'metadata' => $metadata,
        ], JSON_THROW_ON_ERROR);

        $outboxStmt = $this->pdo->prepare(
            'INSERT INTO outbox_events (event_id, aggregate_type, aggregate_id, event_type, payload, traceparent)
             VALUES (:event_id, :agg_type, :agg_id, :event_type, :payload::jsonb, :traceparent)'
        );
        $outboxStmt->execute([
            ':event_id' => $eventUuid,
            ':agg_type' => 'order',
            ':agg_id' => $orderId,
            ':event_type' => 'order.paid',
            ':payload' => $payload,
            ':traceparent' => $traceparent,
        ]);

        $this->pdo->commit();
    } catch (Throwable $e) {
        if ($this->pdo->inTransaction()) {
            $this->pdo->rollBack();
        }

        throw $e
;
}
}
}

Finally, run stateless relay workers that claim batches with FOR UPDATE SKIP LOCKED, publish to the broker, and mark successes or schedule exponential backoff retries—while downstream consumers enforce atomic idempotency via ON CONFLICT DO NOTHING:

<?php

declare(strict_types=1);

namespace App\Outbox;

use PDO;
use Throwable;

final readonly class OutboxRelayAndConsumer
{
public function __construct(private PDO $pdo) {}

/**
 * Claims up to $batchSize pending outbox events without blocking parallel workers.
 *
 * @param callable(array<string, mixed>): void $publishToBroker
 */
public function relayBatch(callable $publishToBroker, int $batchSize = 50, int $maxAttempts = 8): int
{
    $this->pdo->beginTransaction();

    try {
        $claimStmt = $this->pdo->prepare(
            'SELECT id, event_id, aggregate_type, aggregate_id, event_type, payload, traceparent, attempts
             FROM outbox_events
             WHERE published_at IS NULL
               AND dead_lettered_at IS NULL
               AND available_at <= now()
             ORDER BY id ASC
             LIMIT :limit
             FOR UPDATE SKIP LOCKED'
        );
        $claimStmt->bindValue(':limit', $batchSize, PDO::PARAM_INT);
        $claimStmt->execute();
        $events = $claimStmt->fetchAll(PDO::FETCH_ASSOC);

        $publishedIds = [];
        foreach ($events as $event) {
            try {
                $publishToBroker($event);
                $publishedIds[] = (int) $event['id'];
            } catch (Throwable $brokerError) {
                $nextAttempt = ((int) $event['attempts']) + 1;
                $backoffSeconds = min(3600, (int) (2 ** $nextAttempt));

                $failStmt = $this->pdo->prepare(
                    'UPDATE outbox_events
                     SET attempts = :attempts,
                         last_error = :err,
                         available_at = now() + (:backoff || \' seconds\')::interval,
                         dead_lettered_at = CASE WHEN :attempts >= :max_attempts THEN now() ELSE NULL END
                     WHERE id = :id'
                );
                $failStmt->execute([
                    ':attempts' => $nextAttempt,
                    ':err' => substr($brokerError->getMessage(), 0, 500),
                    ':backoff' => (string) $backoffSeconds,
                    ':max_attempts' => $maxAttempts,
                    ':id' => $event['id'],
                ]);
            }
        }

        if ($publishedIds !== []) {
            $placeholders = implode(',', array_fill(0, count($publishedIds), '?'));
            $markStmt = $this->pdo->prepare(
                "UPDATE outbox_events SET published_at = now() WHERE id IN ({$placeholders})"
            );
            $markStmt->execute($publishedIds);
        }

        $this->pdo->commit();
        return count($publishedIds);
    } catch (Throwable $e) {
        if ($this->pdo->inTransaction()) {
            $this->pdo->rollBack();
        }

        throw $e;
    }
}

/**
 * Executes a consumer handler exactly once per event_id within a transaction.
 *
 * @param callable(PDO): void $handler
 */
public function consumeIdempotently(string $consumerName, string $eventUuid, callable $handler): bool
{
    $this->pdo->beginTransaction();

    try {
        $dedupStmt = $this->pdo->prepare(
            'INSERT INTO processed_events (consumer_name, event_id)
             VALUES (:consumer, :event_id)
             ON CONFLICT (consumer_name, event_id) DO NOTHING
             RETURNING event_id'
        );
        $dedupStmt->execute([
            ':consumer' => $consumerName,
            ':event_id' => $eventUuid,
        ]);

        if ($dedupStmt->fetchColumn() === false) {
            $this->pdo->commit();
            return false;
        }

        $handler($this->pdo);
        $this->pdo->commit();
        return true;
    } catch (Throwable $e) {
        if ($this->pdo->inTransaction()) {
            $this->pdo->rollBack();
        }

        throw $e
;
}
}
}

6. Developer FAQs on the Transactional Outbox Pattern

1. How fast does FOR UPDATE SKIP LOCKED scale under multiple relay workers?

FOR UPDATE SKIP LOCKED allows horizontal relay scaling without lock waits because each worker skips rows currently locked by sibling workers. Keep batch sizes modest (25 to 100 rows) so individual relay transactions commit within 10–30 ms and never hold locks long enough to interfere with autovacuum.

2. Should I delete outbox rows immediately after publishing or mark published_at?

Marking published_at = now() makes debugging production incidents far easier during a 24–72 hour retention window. Because our partial index WHERE published_at IS NULL excludes published rows, keeping recent rows does not slow down polling—just run a nightly cleanup job or drop daily partitions to reclaim disk space.

3. How do I preserve strict per-aggregate ordering when scaling relay workers?

If two events for the same aggregate_id sit in the same batch or get claimed by two different workers, out-of-order delivery can occur. Either run a single-threaded relay per shard/partition or route events to Kafka/RabbitMQ partitioned by aggregate_id while ensuring only one relay claims events for a given hashtext(aggregate_id) % worker_count.

4. What happens if the outbox relay publishes to Redis or RabbitMQ inside a long batch and crashes on row 49?

The entire PostgreSQL claim transaction rolls back, leaving rows 1–48 marked unpublished. On the next poll, those 48 events are re-published, and downstream consumers safely discard the duplicates using processed_events with ON CONFLICT DO NOTHING.


7. Summary & Production Rollout Checklist

The transactional outbox pattern eliminates silent event loss between your relational database and asynchronous worker fleets without sacrificing API latency. Persist domain events in the same ACID transaction as business data, relay batches safely using FOR UPDATE SKIP LOCKED, and enforce consumer idempotency at the database constraint layer.

  1. Deploy Schema & Partial Index: Add outbox_events with idx_outbox_pending_poll and processed_events to your primary PostgreSQL database.
  2. Migrate Dual-Writes Incrementally: Move critical financial and webhook emitters into single-transaction outbox writes while preserving W3C traceparent headers across hops.
  3. Alert on Lag & Dead Letters: Export Prometheus metrics for pending outbox depth, oldest unpublished age, and dead_lettered_at IS NOT NULL counts alongside your containerized relay workers.

Related Architectural & Engineering Guides

Team CodeBodh

CodeBodh Team creates high quality scripts, SaaS applications and developer tools to help you build faster.

Comments (0)

Security check against automated spam
10 + 8 = ?