Órbita
- Código
- Arquitetura
- Dados
- Integração
- Resiliência
Quando usar
Consistência entre banco de dados e broker de mensagens
Órbita
Quando usar
Consistência entre banco de dados e broker de mensagens
Problema
Gravar no banco e publicar evento sem garantia atômica
Quando usar
Consistência entre banco de dados e broker de mensagens
outbox
Grava o evento na mesma transação do dado e publica depois, de forma confiável.
Relacionados
2Planta de sequência
Reproduzir passo a passoComo funciona
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 ciclo: ROLLBACK, o evento segue pending e o ciclo seguinte publica
Queda entre publicar e marcar republica: At-least-once, consumidor deduplica pelo eventId
README.mdpattern/transactions/outbox
thiagoeti/pattern/outboxO evento entra em outbox_messages na mesma transação do dado; um relay publica depois. Sem dual write, nenhum evento se perde.
TED liquidada precisa avisar o antifraude; uma queda entre gravar e publicar não pode perder o aviso.
transfer.settled na mesma transaçãopending com FOR UPDATE SKIP LOCKEDeventId e marca publishedROLLBACK, o evento segue pending e o ciclo seguinte publicaeventIdsrc/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();
./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.
| Vantagem | Desvantagem |
|---|---|
| Evento nunca se perde | Consumidor idempotente obrigatório |
| Só banco e broker | Exige limpeza de published |