← Back to Backend, page 2

backend-0024 · Hard senior

What is the transactional outbox pattern, what problem does it solve, and how do you implement the relay with PostgreSQL?

When a service must update its database and publish an event, doing both separately (dual write) can lose the event or publish an event for a change that rolled back. The outbox pattern writes the business change and an event row in the same database transaction. A separate relay reads unpublished rows (FOR UPDATE SKIP LOCKED), publishes them to the broker, and marks them published. If the relay crashes after publishing but before marking, the event is sent again, so consumers must deduplicate by event id (at-least-once).

Full answer

The dual write problem

  • Save the order, then publish OrderPlaced. If the process dies in between, the order exists and the event never leaves. If you publish first and the database commit fails, you published an event for something that did not happen. There is no transaction across a database and a broker.

Outbox

  1. In one transaction: insert the order and insert a row into an outbox table (event id, type, payload, created_at, published_at null). Either both commit or neither.
  2. A relay process (a poller, or change data capture such as Debezium reading the write-ahead log) reads unpublished rows in order, publishes them, and sets published_at.
  3. The relay selects with FOR UPDATE SKIP LOCKED, so several relay instances can run without taking the same rows.
  4. Delivery is at least once: a crash between publish and update repeats the event. The event id is the deduplication key for consumers (see the idempotent consumer item).

Operations

  • Add an index on unpublished rows (a partial index where published_at is null). Delete or archive old published rows.
  • Preserve order per aggregate by selecting in id order and publishing with the aggregate id as partition key.
  • Monitor the lag (oldest unpublished row).
javascript
const { Client } = require('pg');

(async () => {
  const db = new Client(); await db.connect();
  await db.query(`
    DROP TABLE IF EXISTS bk24_outbox; DROP TABLE IF EXISTS bk24_orders;
    CREATE TABLE bk24_orders (id serial PRIMARY KEY, item text NOT NULL);
    CREATE TABLE bk24_outbox (id serial PRIMARY KEY, event_id uuid NOT NULL DEFAULT gen_random_uuid(), payload jsonb NOT NULL, published_at timestamptz);`);

  async function placeOrder(item, fail = false) {
    try {
      await db.query('BEGIN');
      const { rows } = await db.query('INSERT INTO bk24_orders (item) VALUES ($1) RETURNING id', [item]);
      await db.query('INSERT INTO bk24_outbox (payload) VALUES ($1)', [JSON.stringify({ type: 'OrderPlaced', orderId: rows[0].id, item })]);
      if (fail) throw new Error('payment failed');
      await db.query('COMMIT');
    } catch (err) { await db.query('ROLLBACK'); }
  }
  await placeOrder('book'); await placeOrder('pen'); await placeOrder('lamp', true);
  const count = async (t) => (await db.query(`SELECT count(*)::int AS n FROM ${t}`)).rows[0].n;
  console.log('orders, outbox rows (the failed order left no event):', await count('bk24_orders'), await count('bk24_outbox'));

  const broker = [];
  async function relay({ crashAfterFirstPublish = false } = {}) {
    await db.query('BEGIN');
    const { rows } = await db.query('SELECT id, event_id, payload FROM bk24_outbox WHERE published_at IS NULL ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 10');
    for (const row of rows) {
      broker.push({ eventId: row.event_id, ...row.payload });                        // publish
      if (crashAfterFirstPublish) { await db.query('ROLLBACK'); return 'relay crashed after publishing 1 event, before marking it'; }
      await db.query('UPDATE bk24_outbox SET published_at = now() WHERE id = $1', [row.id]);
    }
    await db.query('COMMIT');
    return `relay published ${rows.length} event(s)`;
  }
  console.log(await relay({ crashAfterFirstPublish: true }));
  console.log(await relay());
  console.log('messages on the broker:', broker.length, '| distinct event ids:', new Set(broker.map((m) => m.eventId)).size);

  // The consumer deduplicates by event id.
  const processed = new Set(); let effects = 0;
  for (const m of broker) if (!processed.has(m.eventId)) { processed.add(m.eventId); effects++; }
  console.log('consumer effects after dedup:', effects);

  await db.query('DROP TABLE bk24_outbox; DROP TABLE bk24_orders');
  await db.end();
})();

Runs on the local PostgreSQL. The broker is an array, and the relay crash is simulated by a rollback after the first publish. Only one relay ran, so the effect of SKIP LOCKED with several relays is described in the text, not run. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): orders, outbox rows (the failed order left no event): 2 2 relay crashed after publishing 1 event, before marking it relay published 2 event(s) messages on the broker: 3 | distinct event ids: 2 consumer effects after dedup: 2

Key points

  • Write the data and the event in one local transaction.
  • A relay publishes outbox rows and marks them done.
  • SKIP LOCKED lets many relays work without conflicts.
  • Publishing is at least once, so consumers deduplicate by event id.
  • Monitor outbox lag and clean old rows.

Common mistakes

  • Publishing to the broker inside the database transaction.
  • Assuming the outbox gives exactly-once delivery.
  • Never cleaning the outbox table.
  • A polling relay with no index, scanning the whole table.
  • Publishing events out of order for one aggregate.

Follow-ups

  • How does change data capture compare with a polling relay?
  • What is the inbox pattern?
  • How do you keep order per aggregate?

Tips

  • Describe the dual write problem first.
  • Explain 'one transaction, two rows'.
  • State that delivery is at least once.