Pular para o conteúdo

Saga — Coreografia

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

passos
4
arquivos
7
testes
0
tecnologias
7

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ência
8/8
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
8

8 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.

  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

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 saga-choreography-db pg_isready -h 127.0.0.1 -U postgres -d saga_db >/dev/null 2>&1; do sleep 1; done
  3. until docker exec --user rabbitmq saga-choreography-broker rabbitmq-diagnostics -q check_port_connectivity >/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 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.

Requisitos
BunDocker
Sobe junto
PostgreSQLRabbitMQ

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

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

Domínio financeiro

  • Boleto
  • Crédito/Empréstimo
  • Liquidação
  • Limite

Infraestrutura

  • PostgreSQLbanco relacional

    postgres:16-alpine:5432

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Banco

sql/01_schema.sql

  • boleto_payments
  • credit_limits
  • settlements

Variáveis de ambiente

SAGA_CHOREOGRAPHY_DATABASE_URL
postgres://postgres:postgres@localhost:5432/saga_db
PostgreSQL with one schema per service.
SAGA_CHOREOGRAPHY_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ carrying the saga events between the services.

Trilhapasso 4 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)
Esc

↑ ↓ navegarEnter abrir239 resultados