Headline: Saving a row in Postgres and then publishing a message to a queue is a dual write, and it loses or invents events whenever the process dies between the two calls. The transactional outbox pattern fixes it by inserting the event into an
outboxtable in the same Postgres transaction as the business change, then letting a relay publish pending rows withSELECT … FOR UPDATE SKIP LOCKED. Delivery becomes at-least-once, so consumers deduplicate by event ID.
For a long time my NestJS services created an order and then pushed an order.created job to a queue on the next line. It passed every test, because tests never kill the process between two awaits. Production does: SIGTERM during deploys, OOM kills, broker timeouts. These are my notes from replacing that code with a transactional outbox.
Key takeaways
- A dual write is one operation that writes to two systems with no shared transaction, such as a Postgres row plus a Redis, RabbitMQ or Kafka message; a crash between the writes leaves the systems disagreeing.
- The transactional outbox stores each event as a row in the same database transaction as the state change, so the commit makes both durable or neither.
-
A relay claims unpublished rows with
FOR UPDATE SKIP LOCKED, publishes them and marks them published; several relay instances never claim the same row. - The outbox gives at-least-once delivery, not exactly-once, so consumers record processed event IDs under a unique constraint and skip repeats.
- Polling is the simplest relay; change data capture with Debezium removes polling latency but adds Kafka Connect and a replication slot to operate.
What is the dual-write problem, and why don't retries fix it?
The dual-write problem is that two independent writes cannot be made atomic from application code, so a failure between them produces an inconsistency that no retry can see. This is the code I used to ship:
// orders.service.ts — the dual write
async createOrder(input: CreateOrderDto) {
const order = await this.ordersRepo.insert(input); // write 1: Postgres commits here
await this.queue.add('order.created', { orderId: order.id }); // write 2: Redis
return order;
}
It fails in two directions:
- Lost event: Postgres commits, then the process dies or the queue call times out. The order exists, but no confirmation email, invoice or stock reservation ever follows.
-
Phantom event: the message is published first, or inside the transaction before
COMMIT, and the transaction rolls back. A consumer receivesorder.createdfor an order that does not exist.
A retry loop cannot fix the dual write, because the process that would retry is the process that crashed. Publishing inside the transaction only swaps lost events for phantom events while holding a transaction open across a network call. Two-phase commit (XA) would solve it on paper, but Redis, Kafka and most managed brokers cannot join a Postgres transaction.
How does the transactional outbox pattern work?
The transactional outbox pattern turns "publish a message" into "insert a row", which Postgres commits atomically with the business change. A separate relay reads committed rows later and does the actual publishing. This is my table:
CREATE TABLE outbox (
id uuid PRIMARY KEY,
aggregate_type text NOT NULL, -- e.g. 'order'
aggregate_id text NOT NULL, -- e.g. the 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;
The write side is one Drizzle transaction in the NestJS service, so the order and its event commit together or not at all:
// orders.service.ts — the outbox write
import { randomUUID } from 'node:crypto';
async createOrder(input: CreateOrderDto) {
return this.db.transaction(async (tx) => {
const [order] = await tx.insert(orders).values(input).returning();
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;
});
}
The same shape works with Prisma's interactive prisma.$transaction(async (tx) => …) and TypeORM's dataSource.transaction(async (manager) => …). I put a version field in every payload because the outbox row outlives the code that wrote it.
How does the relay publish outbox rows safely with several workers?
The relay claims a batch of pending rows with SELECT … FOR UPDATE SKIP LOCKED, publishes each one, and marks the successes as published before committing. FOR UPDATE locks the claimed rows; SKIP LOCKED makes a second relay skip those rows instead of waiting, so I run the relay in every API replica.
// outbox.relay.ts — DB, Database, EventPublisher and the outbox table come from this app's own modules
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; } // requires app.enableShutdownHooks()
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 500 ms; a busy relay loops immediately
}
}
private drainBatch(): Promise<number> {
return this.db.transaction(async (tx) => {
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) {
// Back off this row only: 1 s, 2 s, 4 s … 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;
});
}
}
Three details took me more than one attempt:
-
Per-row error handling. My first version let one failing publish roll back the whole batch, so one poison row blocked everything behind it. Now a failure only bumps that row's
attemptsandnext_attempt_at, and a broker outage delays delivery without losing anything. -
Publish timeouts. The claim transaction stays open while the relay talks to the broker, so the publisher needs a short timeout. For slow targets such as third-party webhooks, I use a lease instead: set
locked_until, commit, publish outside the transaction, then mark the rows published. -
Ordering. Postgres
now()returns the transaction's start time, so an event whose transaction commits late can be published after a newer one. The relay never skips that row, because it re-queries every pending row, but several relays remove global ordering entirely. For per-aggregate order I run one relay or shard relays byaggregate_id, and consumers discard stale versions.
Why is outbox delivery at-least-once, and how do consumers deduplicate?
Outbox delivery is at-least-once because the relay can crash after the broker accepts a message but before published_at commits, so the next run publishes that row again. The fix lives in the consumer: an inbox table keyed by event ID, written in the same transaction as the consumer's work.
CREATE TABLE processed_events (
event_id uuid PRIMARY KEY,
processed_at timestamptz NOT NULL DEFAULT now()
);
// invoice.consumer.ts — the handler's work runs once per event ID, however often it is delivered
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
await tx.insert(invoices).values({ orderId: event.payload.orderId, totalCents: event.payload.totalCents });
});
}
INSERT … ON CONFLICT DO NOTHING RETURNING returns no row for a known event ID, so a duplicate becomes a no-op. For side effects outside the database, such as charging a card, I pass the event ID as the provider's idempotency key; Stripe's Idempotency-Key header is the standard example.
Should the relay poll, use LISTEN/NOTIFY, or use change data capture?
Polling is the right default; change data capture pays off when you already run Kafka or need sub-second latency at high volume:
| Relay strategy | Latency | Extra infrastructure | Main catch |
|---|---|---|---|
Polling with SKIP LOCKED
|
Up to one poll interval | None beyond a worker | Constant small query load, even when idle |
Polling plus LISTEN/NOTIFY wake-ups |
Near-immediate | One dedicated session connection | Notifications are not durable, so keep the poll as a fallback; transaction-mode PgBouncer does not support LISTEN
|
| CDC with Debezium's outbox event router | Near-immediate, in commit order | Kafka Connect or Debezium Server, wal_level=logical, a replication slot |
An abandoned replication slot retains WAL until the disk fills |
Change data capture (CDC) reads row changes from the Postgres write-ahead log through logical replication instead of querying the table; Debezium ships an outbox event router transform for this table shape. NOTIFY is transactional, delivered only if the sending transaction commits, so it is a safe wake-up signal for a poller.
How do I keep the outbox table healthy in production?
Keep the outbox small and alert on its lag. A scheduled job deletes published rows older than a few days, in batches; at higher volumes, partitioning by created_at and dropping old partitions is cheaper. The alert I would not ship without tracks the oldest pending row:
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;
A growing oldest_pending_age means a stuck relay, a down broker or a poison row. None of these is visible from the API, which keeps returning 201 because the order itself was saved.
FAQ
Q: Do I still need an outbox if my queue is BullMQ on Redis?
A: Yes. Writing a Postgres row and enqueuing a BullMQ job in Redis is a dual write. The alternative is a Postgres-backed queue such as Graphile Worker, whose graphile_worker.add_job() SQL function enqueues a job inside your own transaction, making the job table the outbox.
Q: Does the transactional outbox give exactly-once delivery?
A: No. The transactional outbox gives at-least-once delivery; exactly-once processing comes from consumers that deduplicate by event ID.
Q: Can I write to the broker first and to the database second?
A: No. Reversing the order still leaves two independent writes and turns lost events into phantom events for rows that never commit.
Q: Should the outbox payload contain the full entity or only its ID?
A: A versioned snapshot of the fields consumers need. An ID-only event forces every consumer to call back to the producer, which may already hold a newer state.
Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.
Top comments (2)
The per-row backoff breaks per-aggregate order even with one relay. I ran your loop with three events for one order and a single broker timeout on order.created: it went out third, after paid and shipped. What fixed it for me was
AND NOT EXISTS (an older unpublished row with the same aggregate_id)in the claim query, plus skipping that aggregate's remaining rows in the batch once one fails.This is the clearest explanation of the outbox pattern I have read in a while — especially the part most write-ups skip: that a retry loop cannot fix a dual write because the process that would retry is the one that crashed.
Two details landed for me. First, the poison-row lesson: one failing publish rolling back the whole batch is exactly the kind of bug that only shows up in production, and per-row attempts with next_attempt_at is the honest fix. Second, the alert on oldest pending age — a stuck relay is invisible from the API, so without that alert you find out from users, not from monitoring.
I am thinking about this from the Android side, where my app queues work offline and the same question appears: the write happened locally, but did the event ever reach the server? Your version field for ordering caught my eye too — do you version the whole payload snapshot, or just the aggregate, when a consumer only needs a few fields?