Pular para o conteúdo
  1. Padrões
  2. Dados

outbox

Grava o evento na mesma transação do dado e publica depois, de forma confiável.
Status
Em breve
Categoria
Dados
Implementação em Transações & Consistênciapattern/transactions/outboxintermediário5 passos≈ 3 min

Órbita

  1. Código
  2. Arquitetura
  3. Dados
  4. Integração
  5. Resiliência

Quando usar

Consistência entre banco de dados e broker de mensagens

  1. Problema

    Gravar no banco e publicar evento sem garantia atômica

  2. Quando usar

    Consistência entre banco de dados e broker de mensagens

  3. outbox

    Grava o evento na mesma transação do dado e publica depois, de forma confiável.

Planta de sequência

Reproduzir passo a passo
BEGIN, INSERT transfers, INSERT outbox_messages, COMMIT1SELECT pending FOR UPDATE SKIP LOCKED2XADD com eventId3status published, COMMIT4lê o evento5Serviço de TEDPostgreSQLRelayRedis StreamAntifraude

Como funciona

  1. 1

    TED e transfer.settled na mesma transação

  2. 2

    O relay pega pending com FOR UPDATE SKIP LOCKED

  3. 3

    Publica no Redis Stream com o eventId e marca published

  4. 4

    Broker fora no primeiro ciclo: ROLLBACK, o evento segue pending e o ciclo seguinte publica

  5. 5

    Queda entre publicar e marcar republica: At-least-once, consumidor deduplica pelo eventId

Nível
intermediário
Infraestrutura
B — dois ou mais serviços (docker compose)
Domínio financeiro
TEDAntifraudeLiquidação
Abrir a implementação completa

README.mdpattern/transactions/outbox

thiagoeti/pattern/outbox

O evento entra em outbox_messages na mesma transação do dado; um relay publica depois. Sem dual write, nenhum evento se perde.

Cenário

TED liquidada precisa avisar o antifraude; uma queda entre gravar e publicar não pode perder o aviso.

Como funciona

  1. TED e transfer.settled na mesma transação
  2. O relay pega pending com FOR UPDATE SKIP LOCKED
  3. Publica no Redis Stream com o eventId e marca published
  4. Broker fora no primeiro ciclo: ROLLBACK, o evento segue pending e o ciclo seguinte publica
  5. Queda entre publicar e marcar republica: at-least-once, consumidor deduplica pelo eventId

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 (## Executar, $2, $3) RETURNING id", [accountFromId, accountToId, amountCents]);
    await client.query("INSERT INTO outbox_messages (aggregate_id, event_type, payload) VALUES (## Executar, '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(## Executar)", [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();

Executar

./docker.sh
until docker exec outbox-db pg_isready -h 127.0.0.1 -U postgres -d outbox_db >/dev/null 2>&1; do sleep 1; done
until docker exec outbox-cache redis-cli ping >/dev/null 2>&1; do sleep 1; done
bun install
bun run demo
docker rm -f outbox-db outbox-cache

Saí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.

Trade-offs

Vantagem Desvantagem
Evento nunca se perde Consumidor idempotente obrigatório
Só banco e broker Exige limpeza de published
Esc

↑ ↓ navegarEnter abrir239 resultados