Pular para o conteúdo

Coreografia vs Orquestração

Coreografia: cada serviço reage ao evento anterior e publica o próximo. Orquestração: um orquestrador chama cada serviço em ordem e sabe onde parou. O mesmo PIX roda pelos dois.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

PIX de R$ 150,00 passa por limite, antifraude e liquidação, via RabbitMQ (coreografia) e via HTTP (orquestração).

Planta

Fluxo
8/8
Coreografia: RabbitMQ topic pix.eventsOrquestração: HTTPpix.requestedvalidationantifraudsettlementfimobservador pix.#orquestradorvalidationantifraudsettlementpix.validatedpix.fraud-approvedpix.settled123
8

8 passos — reproduza para seguir o fluxo

Como funciona

4passos

O mesmo PIX por coreografia, com cada serviço reagindo ao evento anterior, e por orquestração, com um coordenador chamando cada serviço

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Regras iguais em STEP_RULES

  2. 2

    CoreografiaFila por serviço ligada ao evento que o acorda

  3. 3

    Estado na coreografia exige observador de pix.#

  4. 4

    OrquestraçãoUma função chama as etapas em sequência

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Coreografia: serviço fora não perde o PIX, o evento espera na fila

  • Orquestração: fluxo e estado num lugar só

Custos

  • Coreografia: fluxo espalhado nos bindings; estado só com observador

  • Orquestração: serviço fora falha na hora

Código

pattern/transactions/choreography-vs-orchestration

6 arquivos

./

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

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until docker exec -u rabbitmq choreography-vs-orchestration-broker rabbitmq-diagnostics -q check_port_connectivity >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f choreography-vs-orchestration-broker

Saída: a coreografia imprime pix.requested → pix.validated → pix.fraud-approved → pix.settled e a orquestração termina em settled.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: the same PIX through choreography (each service reacts to an event on RabbitMQ) and orchestration (one caller over HTTP).
import amqplib from "amqplib";
import { Elysia, t } from "elysia";

type PixRequest = { pixId: string; pixKey: string; amountCents: number };
type StepResult = { ok: boolean; reason?: string };

// The rules are the same on both paths; only who triggers each step changes.
const PIX_LIMIT_CENTS = 500_000;
const STEPS = ["validation", "antifraud", "settlement"] as const;
type Step = (typeof STEPS)[number];
const STEP_RULES: Record<Step, (pix: PixRequest) => StepResult> = {
  validation: (pix) => (pix.amountCents <= PIX_LIMIT_CENTS ? { ok: true } : { ok: false, reason: "limit.exceeded" }),
  antifraud: (pix) => (pix.pixKey === "golpe@fraude.example" ? { ok: false, reason: "fraud.key-blocked" } : { ok: true }),
  settlement: () => ({ ok: true }),
};

// Choreography: which event wakes each service and which one it publishes. The order lives in these bindings.
const EXCHANGE = "pix.events";
const REACTIONS: Record<Step, { on: string; emit: string }> = {
  validation: { on: "pix.requested", emit: "pix.validated" },
  antifraud: { on: "pix.validated", emit: "pix.fraud-approved" },
  settlement: { on: "pix.fraud-approved", emit: "pix.settled" },
};
const connection = await amqplib.connect(Bun.env.CHOREOGRAPHY_VS_ORCHESTRATION_AMQP_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertExchange(EXCHANGE, "topic", { durable: false });
const eventPublish = (type: string, pix: PixRequest) => channel.publish(EXCHANGE, type, Buffer.from(JSON.stringify(pix)));
for (const step of STEPS) {
  const { queue } = await channel.assertQueue(`pix.${step}`, { exclusive: true });
  await channel.bindQueue(queue, EXCHANGE, REACTIONS[step].on);
  await channel.consume(queue, (message) => {
    if (!message) return;
    const pix = JSON.parse(message.content.toString()) as PixRequest;
    eventPublish(STEP_RULES[step](pix).ok ? REACTIONS[step].emit : "pix.rejected", pix);
    channel.ack(message);
  });
}
// Without an orchestrator, "where did this PIX stop?" needs a watcher of every event.
const history: string[] = [];
const { queue: trackerQueue } = await channel.assertQueue("", { exclusive: true });
await channel.bindQueue(trackerQueue, EXCHANGE, "pix.#");
await channel.consume(trackerQueue, (message) => message && history.push(message.fields.routingKey), { noAck: true });

// Orchestration: the same services over HTTP; one function calls each in order and knows where the PIX stopped.
const serviceSteps = new Elysia().post("/:step", ({ params, body }) => STEP_RULES[params.step as Step](body), { body: t.Object({ pixId: t.String(), pixKey: t.String(), amountCents: t.Integer() }) });
async function pixOrchestrate(pix: PixRequest): Promise<string> {
  for (const step of STEPS) {
    const response = await serviceSteps.handle(new Request(`http://localhost/${step}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(pix) }));
    const result = (await response.json()) as StepResult;
    if (!result.ok) return `rejected at ${step} (${result.reason})`;
  }
  return "settled";
}

const pix: PixRequest = { pixId: `PIX-${Date.now().toString(36).toUpperCase()}`, pixKey: "bruno@banco.example", amountCents: 15_000 };
eventPublish("pix.requested", pix);
for (let tries = 0; tries < 200 && !history.some((type) => type === "pix.settled" || type === "pix.rejected"); tries++) await Bun.sleep(10);
console.log(`  [CHOREOGRAPHY]  ${history.join(" → ")}`);
console.log(`  [ORCHESTRATION] ${STEPS.join(" → ")} → ${await pixOrchestrate(pix)}`);
await connection.close();

Nível

introdutório

3/13

Linhas de TypeScript
56
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • Antifraude
  • Liquidação
  • Limite

Padrões do catálogo que implementa

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

CHOREOGRAPHY_VS_ORCHESTRATION_AMQP_URL
amqp://guest:guest@localhost:5672

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com Coreografia vs Orquestração?

Próximo projeto, Transações & ConsistênciaEventual Consistency — Anti-Entropy
Esc

↑ ↓ navegarEnter abrir239 resultados