A database transaction commits, then the Node.js process crashes before publishing to Kafka. The order exists, but downstream systems never learn about it. Publish first and you risk the opposite: an event describes a database change that rolled back. Two independent writes cannot be made atomic with a simple retry loop. The transactional outbox makes publication intent part of the database transaction.
1. Record intent in the same transaction
Write both the business mutation and an outbox event using the same PostgreSQL connection and transaction. A successful commit means both exist; a rollback means neither exists. A separate publisher can deliver events asynchronously.
CREATE TABLE outbox_events (
id uuid PRIMARY KEY,
aggregate_id uuid NOT NULL,
event_type text NOT NULL,
payload jsonb NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz,
attempts integer NOT NULL DEFAULT 0,
claimed_until timestamptz,
claim_token uuid
);
CREATE INDEX outbox_pending_idx
ON outbox_events (created_at, id)
WHERE published_at IS NULL;
Keep the payload versioned and minimal. Avoid credentials, huge snapshots and accidental coupling to internal database columns. An event ID must remain stable across retries. Plan a retention policy for published rows from the beginning.
2. Use one checked-out PostgreSQL client
This example uses pg and a single client. Calling pool.query inside a transaction would risk executing statements on different connections.
import { randomUUID } from 'node:crypto';
import type { Pool } from 'pg';
async function createOrder(pool: Pool, customerId: string) {
const client = await pool.connect();
const orderId = randomUUID();
try {
await client.query('BEGIN');
await client.query(
'INSERT INTO orders (id, customer_id, status) VALUES ($1, $2, $3)',
[orderId, customerId, 'CREATED']
);
await client.query(
`INSERT INTO outbox_events
(id, aggregate_id, event_type, payload)
VALUES ($1, $2, $3, $4::jsonb)`,
[randomUUID(), orderId, 'order.created.v1',
JSON.stringify({ orderId, customerId, version: 1 })]
);
await client.query('COMMIT');
return orderId;
} catch (error) {
await client.query('ROLLBACK');
throw error;
} finally {
client.release();
}
}
The outbox closes the atomic recording gap. It does not guarantee exactly-once Kafka delivery. If Kafka acknowledges a message but the publisher crashes before recording success, the event will be sent again.
3. Claim a bounded batch without locking Kafka into the transaction
Multiple publishers can coordinate using short database leases. FOR UPDATE SKIP LOCKED lets workers skip rows another transaction already holds. Claim rows inside a short transaction, commit the claim, then publish outside that transaction. Do not hold PostgreSQL row locks while waiting for the broker.
WITH picked AS (
SELECT id FROM outbox_events
WHERE published_at IS NULL
AND (claimed_until IS NULL OR claimed_until < now())
ORDER BY created_at, id
FOR UPDATE SKIP LOCKED
LIMIT 100
)
UPDATE outbox_events AS o
SET claimed_until = now() + interval '60 seconds',
claim_token = $1,
attempts = attempts + 1
FROM picked
WHERE o.id = picked.id
RETURNING o.id, o.aggregate_id, o.event_type, o.payload;
Use a fresh UUID as the claim token for each batch. After Kafka confirms delivery, update published_at only if the event ID and claim token still match. If a worker dies, the lease expires and another worker retries. Set the lease based on measured publish latency or renew it while publishing. Two workers can still send the same event when leases expire, so the consumer must handle duplicates.
4. Preserve entity ordering explicitly
Polling with SKIP LOCKED does not by itself guarantee strict per-entity publication order across several workers. Include a monotonically increasing aggregate version, use aggregate_id as the Kafka key, and validate the version at the consumer. For strict order, consider sharded single dispatchers or a change-data-capture architecture. Partition keys help Kafka preserve order within a partition, but they cannot fix an already reordered publisher.
5. Deduplicate with a database constraint
Keep an inbox table for each logical consumer. Insert the event ID and perform the business side effect in one consumer-side transaction. A unique constraint turns a replay into a safe no-op.
CREATE TABLE consumed_events (
consumer_name text NOT NULL,
event_id uuid NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer_name, event_id)
);
-- Execute inside the same transaction as the business update.
INSERT INTO consumed_events (consumer_name, event_id)
VALUES ($1, $2)
ON CONFLICT DO NOTHING
RETURNING event_id;
If no row is returned, the event has already been recorded by this consumer. Otherwise perform the mutation and commit both changes. This does not make external HTTP side effects atomic: use a provider idempotency key or an effect ledger for payments, email and other remote actions.
6. Measure freshness and failure, not just throughput
- Oldest unpublished age: alert when it exceeds the business freshness objective.
- Pending count: watch backlog growth during broker outages and traffic spikes.
- Attempt count and lease age: identify poison events and stuck workers.
- Commit-to-publish latency: report p50, p95 and p99, not just average.
- Duplicate and version-gap rates: distinguish expected retries from ordering defects.
- Table growth: archive or purge acknowledged events after the audit window.
7. Failure tests worth running
- Crash immediately after the business commit. The event should still publish.
- Crash after Kafka acknowledges but before
published_at. Duplicate delivery must be harmless. - Kill a publisher mid-lease. Another worker should reclaim the row after expiry.
- Disconnect Kafka for ten minutes. Check backlog limits and database write latency.
- Run multiple publishers, then replay events. Verify versions and consumer idempotency.
A transactional outbox trades a fragile dual write for explicit operational work: queue storage, cleanup, publisher capacity and observability. Polling is often enough for moderate throughput. Change data capture may be preferable for higher throughput or lower publication delay, but adds its own dependencies. Choose based on measured requirements rather than architecture fashion.