pattern/transactions/saga-choreography
- Bun
- PostgreSQL
- RabbitMQ
- TypeScript
- amqplib
- node-postgres
- Docker
Sequência de transações locais com compensação, sem coordenador: cada serviço reage ao evento do anterior no RabbitMQ.
pattern/transactions/saga-choreography
Cenário
Boleto de R$ 6.000,00 pago com limite de crédito; a câmara recusa acima de R$ 5.000,00 e a reserva é devolvida.
Planta
Sequência8 passos — reproduza para seguir o fluxo
Como funciona
4passos
Sequência de transações locais com compensação, sem coordenador, cada serviço reagindo ao evento do anterior
Esconde cada passo: lembre antes de tocar para revelar.
Pedidos grava o pedido e publica boleto.payment.requested
Limites reserva e publica limit.reserved
Pagamentos liquida por último (sem compensação); recusa publica payment.declined
Limites libera a reserva (limit.released); Pedidos cancela
Trade-offs
O que se ganha, o que se paga
Vantagens
Sem coordenador nem lock distribuído
Serviço conhece só seus eventos
Custos
Fluxo espalhado pelos handlers
Inconsistência até a compensação
Código
pattern/transactions/saga-choreography
7 arquivos./
sql/
src/
Executar com Docker
./docker.shuntil docker exec saga-choreography-db pg_isready -h 127.0.0.1 -U postgres -d saga_db >/dev/null 2>&1; do sleep 1; doneuntil docker exec --user rabbitmq saga-choreography-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f saga-choreography-db saga-choreography-brokerSaída: Limites reserva, Pagamentos recusa (payment.declined), Limites libera (limit.released) e Pedidos cancela; o boleto de R$ 6000.00 termina cancelled com R$ 0.00 reservado.
Código
src/demo.ts// Demo: a boleto paid with credit limit crosses three services by events; the clearing house declines it and the reservation is compensated.
import amqplib from "amqplib";
import pg from "pg";
const SAGA_EXCHANGE = "boleto.saga";
// The clearing house declines a boleto above this; it runs last because a settlement has no compensation.
const BOLETO_MAX_CENTS = 500_000;
type SagaEvent = { sagaId: string; accountId: string; amountCents: number };
type HandlerSagaEvent = (event: SagaEvent) => Promise<[string, SagaEvent] | undefined>;
const pool = new pg.Pool({ connectionString: Bun.env.SAGA_CHOREOGRAPHY_DATABASE_URL ?? "postgres://postgres:postgres@localhost:5432/saga_db" });
const connection = await amqplib.connect(Bun.env.SAGA_CHOREOGRAPHY_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertExchange(SAGA_EXCHANGE, "topic", { durable: true });
// Choreography: each service binds only the events it reacts to and publishes its own; nobody coordinates.
async function serviceStart(service: string, handlers: Record<string, HandlerSagaEvent>): Promise<void> {
const queue = `boleto.saga.${service}`;
await channel.assertQueue(queue, { durable: true });
for (const event of Object.keys(handlers)) await channel.bindQueue(queue, SAGA_EXCHANGE, event);
await channel.consume(queue, async (message) => {
if (!message) return;
const outcome = await handlers[message.fields.routingKey]!(JSON.parse(message.content.toString()) as SagaEvent);
if (outcome) channel.publish(SAGA_EXCHANGE, outcome[0], Buffer.from(JSON.stringify(outcome[1])), { persistent: true });
console.log(` [${service.toUpperCase()}] ${message.fields.routingKey}${outcome ? ` → ${outcome[0]}` : ""}`);
channel.ack(message);
});
}
await serviceStart("limits", {
"boleto.payment.requested": async (event) => {
await pool.query("UPDATE limits.credit_limits SET reserved_cents = reserved_cents + $2 WHERE account_id = $1", [event.accountId, event.amountCents]);
return ["limit.reserved", event];
},
// Compensation: a business operation that undoes the reservation, not a rollback.
"payment.declined": async (event) => {
await pool.query("UPDATE limits.credit_limits SET reserved_cents = reserved_cents - $2 WHERE account_id = $1", [event.accountId, event.amountCents]);
return ["limit.released", event];
},
});
await serviceStart("payments", {
"limit.reserved": async (event) => {
const status = event.amountCents > BOLETO_MAX_CENTS ? "declined" : "settled";
await pool.query("INSERT INTO payments.settlements (saga_id, amount_cents, status) VALUES ($1, $2, $3)", [event.sagaId, event.amountCents, status]);
return [`payment.${status}`, event];
},
});
await serviceStart("orders", {
"payment.settled": async (event) => void (await pool.query("UPDATE orders.boleto_payments SET status = 'completed' WHERE saga_id = $1", [event.sagaId])),
"limit.released": async (event) => void (await pool.query("UPDATE orders.boleto_payments SET status = 'cancelled' WHERE saga_id = $1", [event.sagaId])),
});
// The order is committed before the first event leaves: the saga exists before anyone reacts to it.
const event: SagaEvent = { sagaId: crypto.randomUUID(), accountId: crypto.randomUUID(), amountCents: 600_000 };
await pool.query("INSERT INTO limits.credit_limits (account_id, limit_cents) VALUES ($1, 1000000)", [event.accountId]);
await pool.query("INSERT INTO orders.boleto_payments (saga_id, account_id, amount_cents) VALUES ($1, $2, $3)", [event.sagaId, event.accountId, event.amountCents]);
channel.publish(SAGA_EXCHANGE, "boleto.payment.requested", Buffer.from(JSON.stringify(event)), { persistent: true });
const order = { status: "requested" };
for (let i = 0; i < 200 && order.status === "requested"; i++) {
await Bun.sleep(25);
order.status = (await pool.query<{ status: string }>("SELECT status FROM orders.boleto_payments WHERE saga_id = $1", [event.sagaId])).rows[0]!.status;
}
const { rows: [limit] } = await pool.query<{ reserved_cents: string }>("SELECT reserved_cents FROM limits.credit_limits WHERE account_id = $1", [event.accountId]);
console.log(` [SAGA] boleto of R$ ${(event.amountCents / 100).toFixed(2)} → order ${order.status}, limit still reserved R$ ${(Number(limit!.reserved_cents) / 100).toFixed(2)}`);
await connection.close();
await pool.end();
Nível
avançado
8/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
PostgreSQLbanco relacional
postgres:16-alpine:5432
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Banco
sql/01_schema.sql
Variáveis de ambiente
Trilhapasso 4 de 7
Consistência sem transação distribuída
Relações
Onde ele se encaixa
Também implementado em
Por que se relacionam
Combina com
Teste rápido
Qual é o próximo passo depois de Saga — Coreografia?
Estado converge sem trava global. Abrir Eventual Consistency — Anti-Entropy
Seu progresso
0/157 estudados
Fica salvo só neste navegador.