Pular para o conteúdo
  1. Padrões
  2. Integração

saga

Coordena transações distribuídas em passos locais com ações de compensação.
Status
Em breve
Categoria
Integração
Implementação em Transações & Consistênciapattern/transactions/saga-choreographyavançado4 passos≈ 3 min2 implementações

Órbita

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

Quando usar

Fluxos longos como pedido, pagamento e estoque

Planta de sequência

Reproduzir passo a passo
boleto.payment.requested1reserva o limite2limit.reserved3liquida o boleto4payment.declined (acima do máximo da câmara)5compensação: libera a reserva6limit.released7pedido cancelled8PedidosRabbitMQ boleto.sagaLimitesPagamentos

Como funciona

  1. 1

    Pedidos grava o pedido e publica boleto.payment.requested

  2. 2

    Limites reserva e publica limit.reserved

  3. 3

    Pagamentos liquida por último (sem compensação); recusa publica payment.declined

  4. 4

    Limites libera a reserva (limit.released); Pedidos cancela

Nível
avançado
Infraestrutura
B — dois ou mais serviços (docker compose)
Domínio financeiro
BoletoCrédito/EmpréstimoLiquidaçãoLimite
Abrir a implementação completa

README.mdpattern/transactions/saga-choreography

thiagoeti/pattern/saga

Sequência de transações locais com compensação, sem coordenador: cada serviço reage ao evento do anterior no RabbitMQ.

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.

Como funciona

  1. Pedidos grava o pedido e publica boleto.payment.requested
  2. Limites reserva e publica limit.reserved
  3. Pagamentos liquida por último (sem compensação); recusa publica payment.declined
  4. Limites libera a reserva (limit.released); Pedidos cancela

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 = ## Executar", [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 = ## Executar", [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 (## Executar, $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 = ## Executar", [event.sagaId])),
  "limit.released": async (event) => void (await pool.query("UPDATE orders.boleto_payments SET status = 'cancelled' WHERE saga_id = ## Executar", [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 (## Executar, 1000000)", [event.accountId]);
await pool.query("INSERT INTO orders.boleto_payments (saga_id, account_id, amount_cents) VALUES (## Executar, $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 = ## Executar", [event.sagaId])).rows[0]!.status;
}
const { rows: [limit] } = await pool.query<{ reserved_cents: string }>("SELECT reserved_cents FROM limits.credit_limits WHERE account_id = ## Executar", [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();

Executar

./docker.sh
until docker exec saga-choreography-db pg_isready -h 127.0.0.1 -U postgres -d saga_db >/dev/null 2>&1; do sleep 1; done
until docker exec --user rabbitmq saga-choreography-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; done
bun install
bun run demo
docker rm -f saga-choreography-db saga-choreography-broker

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

Trade-offs

Vantagem Desvantagem
Sem coordenador nem lock distribuído Fluxo espalhado pelos handlers
Serviço conhece só seus eventos Inconsistência até a compensação
Esc

↑ ↓ navegarEnter abrir239 resultados