pattern/transactions/outbox
- Bun
- Bun RedisClient
- PostgreSQL
- Redis
- TypeScript
- node-postgres
- Docker
O evento entra em outbox_messages na mesma transação do dado; um relay publica depois. Sem dual write, nenhum evento se perde.
pattern/transactions/outbox
Cenário
TED liquidada precisa avisar o antifraude; uma queda entre gravar e publicar não pode perder o aviso.
Planta
Sequência5 passos — reproduza para seguir o fluxo
Como funciona
5passos
O evento entra em outbox_messages na mesma transação do dado e um relay publica depois
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
TED e transfer.settled na mesma transação
O relay pega pending com FOR UPDATE SKIP LOCKED
Publica no Redis Stream com o eventId e marca published
Broker fora no primeiro cicloROLLBACK, o evento segue pending e o ciclo seguinte publica
Queda entre publicar e marcar republicaAt-least-once, consumidor deduplica pelo eventId
Trade-offs
O que se ganha, o que se paga
Vantagens
Evento nunca se perde
Só banco e broker
Custos
Consumidor idempotente obrigatório
Exige limpeza de published
Código
pattern/transactions/outbox
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec outbox-db pg_isready -h 127.0.0.1 -U postgres -d outbox_db >/dev/null 2>&1; do sleep 1; doneuntil docker exec outbox-cache redis-cli ping >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f outbox-db outbox-cacheSaída: TED e evento commitam juntos; com o broker fora, o ciclo falha e 1 evento segue pendente; com o broker de volta, 1 evento é publicado e o antifraude lê transfer.settled com 250000 centavos.
Código
src/demo.ts// Demo: the TED and its outbox event commit in one transaction; a separate relay publishes the event to a Redis Stream.
import { RedisClient } from "bun";
import pg from "pg";
const TRANSFER_STREAM = "transfer_events";
const pool = new pg.Pool({ connectionString: Bun.env.OUTBOX_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/outbox_db" });
const redis = new RedisClient(Bun.env.OUTBOX_REDIS_URL ?? "redis://localhost:6379");
// Service: never a dual write — if the COMMIT fails, the transfer and its event disappear together.
async function transferSettle(accountFromId: string, accountToId: string, amountCents: number): Promise<string> {
const client = await pool.connect();
try {
await client.query("BEGIN");
const { rows: [transfer] } = await client.query<{ id: string }>("INSERT INTO transfers (account_from_id, account_to_id, amount_cents) VALUES ($1, $2, $3) RETURNING id", [accountFromId, accountToId, amountCents]);
await client.query("INSERT INTO outbox_messages (aggregate_id, event_type, payload) VALUES ($1, 'transfer.settled', $2)", [transfer!.id, { transferId: transfer!.id, accountFromId, amountCents }]);
await client.query("COMMIT");
return transfer!.id;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
// Relay: claims pending events with SKIP LOCKED (several relays get disjoint batches), publishes, then marks them published.
// A crash between XADD and the mark republishes: delivery is at-least-once and the consumer deduplicates by eventId.
async function relayCycle(brokerIsDown = false): Promise<number> {
const client = await pool.connect();
try {
await client.query("BEGIN");
const { rows } = await client.query<{ id: string; event_type: string; payload: unknown }>("SELECT id, event_type, payload FROM outbox_messages WHERE status = 'pending' ORDER BY created_at LIMIT 10 FOR UPDATE SKIP LOCKED");
for (const row of rows) {
// Simulated outage after the claim: the transaction rolls back and the event stays pending for the next cycle.
if (brokerIsDown) throw new Error("broker unreachable");
await redis.send("XADD", [TRANSFER_STREAM, "*", "eventId", row.id, "eventType", row.event_type, "payload", JSON.stringify(row.payload)]);
}
await client.query("UPDATE outbox_messages SET status = 'published', published_at = now() WHERE id = ANY($1)", [rows.map((row) => row.id)]);
await client.query("COMMIT");
return rows.length;
} catch (error) {
await client.query("ROLLBACK");
throw error;
} finally {
client.release();
}
}
await redis.send("DEL", [TRANSFER_STREAM]);
const transferId = await transferSettle("0001-1", "0002-2", 250_000);
console.log(` [SERVICE] TED ${transferId.slice(0, 8)} and its outbox event committed together`);
const failure = await relayCycle(true).catch((error: Error) => error.message);
const { rows: [outbox] } = await pool.query<{ pending: number }>("SELECT count(*)::int AS pending FROM outbox_messages WHERE status = 'pending'");
console.log(` [RELAY] ${failure}: nothing lost, ${outbox!.pending} event pending in the outbox`);
console.log(` [RELAY] broker back: ${await relayCycle()} event published to ${TRANSFER_STREAM}`);
// Fraud monitor reads the stream, without ever touching the transfers database.
const reply = (await redis.send("XRANGE", [TRANSFER_STREAM, "-", "+"])) as [string, string[]][];
for (const [, fields] of reply) console.log(` [FRAUD] ${fields[fields.indexOf("eventType") + 1]} ${fields[fields.indexOf("payload") + 1]}`);
await pool.end();
redis.close();
Nível
intermediário
7/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
Rediscache / estrutura de dados
redis:7-alpine:6379
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 2 de 7
Consistência sem transação distribuída
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Combina com
Teste rápido
Qual é o próximo passo depois de Outbox?
Consumidor deduplica a entrega. Abrir Inbox
Seu progresso
0/157 estudados
Fica salvo só neste navegador.