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.
J Ananthakrishnan
Developer · SAP Labs India
The Dual-Write Trap
One of the most common failure modes in backend services hides inside ten innocent-looking lines of code:
- Persist a domain state change inside a relational database transaction.
- 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.
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:
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:
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)
| Dimension | SKIP LOCKED Poller | Log-Based CDC (e.g., Debezium) |
|---|---|---|
| Operational Footprint | Minimal (just a stateless worker) | Higher (requires WAL connectors & Kafka Connect) |
| Publish Latency | 100ms – 1s depending on interval | Sub-100ms near real-time |
| Database Load | Modest if partial-indexed | Minimal read load on primary tables |
| Best Fit | Early-to-mid scale, fast iteration | High-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:
- Natural Domain Guards: Structure state transitions as compare-and-swap checks (e.g.,
UPDATE invoices SET status = 'PAID' WHERE id = $1 AND status = 'PENDING'). - Processed-Event Ledger: Record every consumed
event_idin aprocessed_eventstable inside the same database transaction as the side effect.
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 TrueKey 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_idfrom day one and test duplicate delivery explicitly in integration suites.
Continue Reading
Related Articles
Database Performance · 4 min read
Reading Execution Plans Like a Detective: Indexes, Cardinality, and Silent N+1 Traps
A systematic approach to diagnosing slow backend endpoints by inspecting EXPLAIN ANALYZE plans, designing composite B-Tree indexes around actual access patterns, and fixing hidden N+1 loops.
Mar 22, 2026
AI & Tooling · 4 min read
AI-Assisted Code Review Workflows That Actually Help Engineers
Practical engineering lessons on pairing deterministic static checks with scoped LLM review prompts to cut review turnaround without flooding pull requests with noisy comments.
Jun 12, 2026
AI & Tooling · 3 min read
Exploring the Wonders of ChatGPT: A Glimpse into Conversational AI
Turn your GitHub Issues into a powerful Next.js blog to write more and publish faster!
Apr 2, 2024