pattern/transactions/choreography-vs-orchestration
- Bun
- ElysiaJS
- RabbitMQ
- TypeScript
- amqplib
- Docker
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.
pattern/transactions/choreography-vs-orchestration
Cenário
PIX de R$ 150,00 passa por limite, antifraude e liquidação, via RabbitMQ (coreografia) e via HTTP (orquestração).
Planta
Fluxo8 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.
Regras iguais em STEP_RULES
CoreografiaFila por serviço ligada ao evento que o acorda
Estado na coreografia exige observador de pix.#
OrquestraçãoUma função chama as etapas em sequência
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar com Docker
./docker.shuntil docker exec -u rabbitmq choreography-vs-orchestration-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 choreography-vs-orchestration-brokerSaída: a coreografia imprime pix.requested → pix.validated → pix.fraud-approved → pix.settled e a orquestração termina em settled.
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
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Coreografia vs Orquestração?
O lado orquestrado da comparação. Abrir Process Orchestrator
Seu progresso
0/157 estudados
Fica salvo só neste navegador.