Pular para o conteúdo

Outbox

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

passos
5
arquivos
7
testes
0
tecnologias
7

Cenário

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

Planta

Sequência
5/5
BEGIN, INSERT transfers, INSERT outbox_messages, COMMIT1SELECT pending FOR UPDATE SKIP LOCKED2XADD com eventId3status published, COMMIT4lê o evento5Serviço de TEDPostgreSQLRelayRedis StreamAntifraude
5

5 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

ROLLBACK+2
FOR UPDATE SKIP LOCKED+1
  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 cicloROLLBACK, o evento segue pending e o ciclo seguinte publica

  5. 5

    Queda entre publicar e marcar republicaAt-least-once, consumidor deduplica pelo eventId

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

sql/

  • 01_schema.sqlschema

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. 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
  3. until docker exec outbox-cache redis-cli ping >/dev/null 2>&1; do sleep 1; done
  4. bun install# dependências
  5. bun run demo# roda o cenário
  6. 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.

Requisitos
BunDocker
Sobe junto
PostgreSQLRedis

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

Linhas de TypeScript
56
Tipo
B — dois ou mais serviços (docker compose)

Domínio financeiro

  • TED
  • Antifraude
  • Liquidação

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

  • transfers
  • outbox_messages

Variáveis de ambiente

OUTBOX_DATABASE_URL
postgres://postgres:postgres@localhost:5432/outbox_db
PostgreSQL of transfers and the outbox.
OUTBOX_REDIS_URL
redis://localhost:6379
Redis whose stream carries the published events.

Trilhapasso 2 de 7

Consistência sem transação distribuída

  1. 1Idempotency
  2. 2Outbox
  3. 3Inbox
  4. 4Saga — Coreografia
  5. 5Saga — Orquestração
  6. 6Process Orchestrator
  7. 7Two-Phase Commit (2PC)

Parecidos

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Outbox?

Próximo projeto, Transações & ConsistênciaProcess Orchestrator
Esc

↑ ↓ navegarEnter abrir239 resultados