Executive Overview
In modern software engineering, distributed system design is often treated as a solved problem, thanks to the abundance of managed message brokers, container orchestration platforms, and serverless databases. Yet, beneath the polished surfaces of microservices architectures lies a silent, catastrophic failure mode that routinely corrupts state across organizational boundaries: the dual-write problem.
Consider a routine application requirement: an e-commerce backend needs to record a newly created order in a PostgreSQL database and publish an order.created event to an asynchronous queue (such as Redis, RabbitMQ, or Apache Kafka) to trigger downstream billing, inventory adjustment, and notification workflows. To the uninitiated developer, this appears to be a trivial sequential operation. A service saves the entity to the database, and on the very next line of code, pushes a message to the broker.
In local development and automated test suites, this sequence passes seamlessly. Tests run in controlled environments where processes never terminate unexpectedly between execution steps.
Production, however, is relentlessly hostile. Infrastructure encounters SIGTERM signals during rolling deployments, out-of-memory (OOM) operating system kills, intermittent network partitions, and message broker timeouts. When a process dies in the razor-thin window of execution after a database transaction commits but before the message reaches the queue, the system experiences an irrecoverable divergence. An order exists in the database, but the downstream services remain entirely oblivious to its existence. Conversely, attempting to reverse the order—publishing to the broker first—swaps lost events for "phantom" events, generating notifications for orders that ultimately fail database validation and never commit.
This investigative technical report examines why standard retry loops and two-phase commit (2PC) protocols fail to solve this dilemma in cloud-native applications. Furthermore, it details how engineers can implement the Transactional Outbox Pattern—using TypeScript, NestJS, and PostgreSQL—to achieve reliable, at-least-once message delivery, complemented by robust consumer-side deduplication strategies and database health monitoring.
Detailed Chronology: Anatomy of a Dual-Write Failure
To understand the necessity of the transactional outbox pattern, one must dissect the exact mechanics of a dual-write failure in a production environment.
The Illusion of Sequential Consistency
For years, standard enterprise codebases have shipped implementations resembling the following NestJS service pattern:
// orders.service.ts — the classic dual write
async createOrder(input: CreateOrderDto)
// Write 1: PostgreSQL commits the order record
const order = await this.ordersRepo.insert(input);
// Write 2: Redis / Message Broker publication
await this.queue.add('order.created', orderId: order.id );
return order;
On paper, this code reads cleanly. In practice, it assumes a synchronous, monolithic guarantee over two entirely disparate, independent network boundaries and state machines. PostgreSQL and a message broker (like Redis or Kafka) do not share a common transaction log.
When createOrder executes under high concurrency, the failure modes manifest in two distinct directions:
- Lost Events: PostgreSQL successfully commits the
ordersrow. The execution pointer moves tothis.queue.add(...). Before the network packet leaves the application container, the pod receives a SIGTERM signal from Kubernetes due to an auto-scaling event or rolling deployment. The process terminates instantly. The database holds the order, but the event is permanently lost. - Phantom Events: If an engineer attempts to invert the sequence—pushing to the queue first and writing to the database second—a network timeout or database constraint violation (e.g., a duplicate primary key or check constraint failure) causes the database transaction to rollback. Meanwhile, the message has already been broadcast to the broker. Downstream consumers process an event for an order that was never actually persisted.
Why Retries and Two-Phase Commits Fall Short
A common knee-jerk reaction is to wrap the second call in a retry loop. However, logic dictates that the process attempting to perform the retry is the exact process that crashed. If the container experiences an unhandled exception, a memory exhaustion termination, or a host node failure, the local execution context vanishes entirely. The retry loop never gets the chance to iterate.
Embedding the message publication inside the database transaction—attempting to connect the broker call directly to the SQL transaction context—introduces an even graver architectural anti-pattern. While it prevents lost events, it forces the database transaction to remain open while executing an arbitrary, high-latency network call to an external broker. This ties up database connection pools, elevates lock contention, and drastically reduces system throughput.
In academic computer science, Two-Phase Commit (2PC) or XA transactions are touted as the definitive solution for distributed atomicity. In reality, modern cloud architectures render 2PC largely impractical. Redis, Apache Kafka, AWS SQS, and the vast majority of managed messaging infrastructure do not support distributed XA transactions and cannot natively enlist in a PostgreSQL transaction lifecycle.
Supporting Context & Metrics: The Transactional Outbox Pattern
The transactional outbox pattern solves the atomicity dilemma by fundamentally changing the nature of the write operation. Instead of writing to a database and a message broker simultaneously, the application writes both the business entity and the corresponding event payload into the same relational database within a single, atomic transaction.
Designing the Outbox Schema
The foundation of this architecture is an outbox table residing directly within the primary PostgreSQL database.
CREATE TABLE outbox (
id uuid PRIMARY KEY,
aggregate_type text NOT NULL, -- e.g., 'order'
aggregate_id text NOT NULL, -- e.g., the specific order ID
event_type text NOT NULL, -- e.g., 'order.created'
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
attempts int NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
last_error text
);
-- The relay only ever reads pending rows; a partial index keeps that scan cheap
CREATE INDEX outbox_pending_idx ON outbox (created_at) WHERE published_at IS NULL;
By utilizing a partial index (WHERE published_at IS NULL), PostgreSQL maintains an exceptionally lightweight index containing only unprocessed messages. As the relay publishes messages and marks them as completed, the index footprint remains minimal, preventing performance degradation even tables scale into tens of millions of rows.
Executing the Atomic Write in NestJS
Using modern TypeScript ORMs such as Drizzle, Prisma, or TypeORM, developers can wrap the order insertion and outbox event creation within a single transactional boundary:
// orders.service.ts — the outbox write
import randomUUID from 'node:crypto';
async createOrder(input: CreateOrderDto)
return this.db.transaction(async (tx) =>
// 1. Insert the business entity
const [order] = await tx.insert(orders).values(input).returning();
// 2. Insert the outbox event in the exact same transaction
await tx.insert(outbox).values(
id: randomUUID(),
aggregateType: 'order',
aggregateId: order.id,
eventType: 'order.created',
// Snapshot what consumers need now; a later read could see a newer state
payload:
version: 1,
orderId: order.id,
customerId: order.customerId,
totalCents: order.totalCents
,
);
return order;
);
A critical design consideration embedded here is the inclusion of a explicit version field within the JSON payload. Because outbox records outlive the immediate code execution context and may be replayed or processed across schema evolution cycles, explicitly versioning the event contract shields downstream consumers from breaking changes.
Official Implementation: Safe Relay Processing and Concurrency
With events safely persisted to the outbox table, a background worker process—known as the Relay—is responsible for reading pending rows, pushing them to the message broker, and marking them as published.
Scaling the Relay with SKIP LOCKED
When running multiple API replicas or background worker pods in a horizontally scaled Kubernetes cluster, multiple relay instances will attempt to read the outbox table concurrently. Without proper row-level locking, race conditions will cause duplicate message publications.
PostgreSQL solves this cleanly via the SELECT ... FOR UPDATE SKIP LOCKED clause. This allows multiple workers to poll the same table simultaneously without blocking each other; rows locked by one worker are instantly bypassed by all others.
// outbox.relay.ts
import Inject, Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown from '@nestjs/common';
import setTimeout as sleep from 'node:timers/promises';
import and, asc, eq, inArray, isNull, lte, sql from 'drizzle-orm';
@Injectable()
export class OutboxRelay implements OnApplicationBootstrap, OnApplicationShutdown
private readonly logger = new Logger(OutboxRelay.name);
private running = true;
constructor(@Inject(DB) private readonly db: Database, private readonly publisher: EventPublisher)
onApplicationBootstrap() void this.loop();
onApplicationShutdown() this.running = false;
private async loop()
while (this.running)
const claimed = await this.drainBatch().catch((err) =>
this.logger.error(err);
return 0;
);
if (claimed === 0) await sleep(500); // Idle: poll every 500ms; a busy relay loops immediately
private drainBatch(): Promise<number>
return this.db.transaction(async (tx) =>
// Claim a batch of rows safely across distributed workers
const rows = await tx.select().from(outbox)
.where(and(isNull(outbox.publishedAt), lte(outbox.nextAttemptAt, sql`now()`)))
.orderBy(asc(outbox.createdAt))
.limit(50)
.for('update', skipLocked: true );
const sent: string[] = [];
for (const row of rows)
try
// The outbox row id travels with the message as the deduplication key
await this.publisher.publish(row.eventType, eventId: row.id, payload: row.payload );
sent.push(row.id);
catch (err)
// Exponential backoff per row: 1s, 2s, 4s... capped at 5 minutes
await tx.update(outbox).set(
attempts: sql`$outbox.attempts + 1`,
nextAttemptAt: sql`now() + least(power(2, $outbox.attempts), 300) * interval '1 second'`,
lastError: String(err),
).where(eq(outbox.id, row.id));
if (sent.length > 0)
await tx.update(outbox).set( publishedAt: new Date() ).where(inArray(outbox.id, sent));
return rows.length;
);
Consumer-Side Deduplication (The Inbox Pattern)
Because the relay can occasionally crash after successfully dispatching a message to the broker but before the local published_at database update commits, the architectural delivery guarantee of the outbox pattern is at-least-once.
To prevent downstream systems from processing duplicate business logic (such as charging a customer’s credit card twice), consumers must implement idempotent processing via an Inbox Pattern:
CREATE TABLE processed_events (
event_id uuid PRIMARY KEY,
processed_at timestamptz NOT NULL DEFAULT now()
);
// invoice.consumer.ts — handler processes each event ID exactly once
async handleOrderCreated(event: OutboxMessage<OrderCreatedV1>)
await this.db.transaction(async (tx) =>
const fresh = await tx.insert(processedEvents)
.values( eventId: event.eventId )
.onConflictDoNothing()
.returning();
if (fresh.length === 0) return; // Duplicate delivery: already handled successfully
// Execute core business logic safely
await tx.insert(invoices).values(
orderId: event.payload.orderId,
totalCents: event.payload.totalCents
);
);
By leveraging ON CONFLICT DO NOTHING RETURNING, the database acts as an atomic guard. Duplicate deliveries result in an immediate, safe no-op.
Future Outlook: Architectural Trade-offs and Maintenance
When scaling distributed systems, engineers must evaluate alternative delivery topologies. The table below outlines the primary trade-offs between polling relays, notification-driven architectures, and change data capture (CDC) pipelines.
| Relay Strategy | Latency Profile | Extra Infrastructure Required | Primary Operational Catch |
|---|---|---|---|
Polling with SKIP LOCKED |
Up to one poll interval (e.g., 500ms) | None beyond existing application workers | Constant low-level query load against PostgreSQL, even when idle |
Polling + LISTEN / NOTIFY |
Near-immediate | One dedicated persistent database session connection | PostgreSQL notifications are non-durable; polling must remain as a fallback. Transaction-mode PgBouncer does not support LISTEN. |
| Change Data Capture (CDC) | Sub-second, strict commit order | Kafka Connect or Debezium Server, wal_level=logical, active replication slots |
Abandoned or disconnected replication slots will retain Write-Ahead Logs (WAL) until disk storage fills completely. |
Operational Health and Production Monitoring
Running the transactional outbox pattern in production requires rigorous observability. Because API endpoints will continue to return HTTP 201 Created successfully even if the outbox relay completely halts, standard application error tracking will not expose downstream messaging failures.
Engineering teams must implement proactive monitoring tracking the age and volume of unprocessed outbox records:
SELECT count(*) AS pending,
coalesce(max(now() - created_at), interval '0') AS oldest_pending_age,
coalesce(max(attempts), 0) AS max_attempts
FROM outbox
WHERE published_at IS NULL;
An escalating oldest_pending_age serves as an immediate indicator of a stuck relay process, an unresponsive message broker, or a persistent "poison message" throwing unhandled serialization exceptions. Regular maintenance scripts should also purge historical published_at records past a retention threshold (e.g., 7 days) or leverage table partitioning by created_at to ensure high-performance table scans in high-throughput enterprise environments.
By treating event publication with the same transactional rigor as database persistence, engineering organizations can eliminate the phantom inconsistencies of the dual-write problem and build resilient, fault-tolerant distributed architectures.
