pattern/messaging/scatter-gather
Scatter-Gather
Envia a mesma requisição em paralelo a vários destinatários e consolida as respostas ao receber todas ou no timeout.
- passos
- 4
- arquivos
- 6
- testes
- 0
- tecnologias
- 5
Cenário
Score consultado em Serasa, Boa Vista e SPC; com o SPC fora, decide com quem respondeu e informa o ausente.
Planta
Sequência6 passos — reproduza para seguir o fluxo
- chamada
- resposta ou assíncrono
- falha
- passo
- toque num participante para focar
- Outras plantas de sequência
Como funciona
4passos
Envia a mesma requisição em paralelo a vários destinatários e consolida as respostas ao receber todas ou no timeout
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
replyTo+2
expiration+1
- 1
Consulta publicada numa exchange fanout ligada à fila de cada bureau
- 2
Leva
replyTo,correlationIdeexpiration= timeout - 3
Cada bureau responde ecoando o
correlationId - 4
Fecha com todas ou no timeout; decide pela média e lista ausentes
Trade-offs
O que se ganha, o que se paga
Vantagens
Bureau fora não trava a decisão
Latência = mais lento ou timeout
Custos
Decisão parcial precisa ser aceitável
Respostas tardias descartadas
Código
pattern/messaging/scatter-gather
6 arquivos./
- .env.exampleinfra
- docker.shinfra
- package.jsoninfra
- README.md
- tsconfig.jsoninfra
src/
- demo.tsdemo
Executar com Docker
./docker.shuntil docker exec --user rabbitmq scatter-gather-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 scatter-gather-broker
Saída: Serasa 720 e Boa Vista 690; SPC não responde a tempo; média 705, aprovado, missing [spc].
- Requisitos
- BunDocker
- Sobe junto
- RabbitMQ
Código
src/demo.ts
// Demo: one credit query fans out to three bureaus; the gather decides with whoever answered before the timeout.
import amqplib from "amqplib";
const SCORE_REQUEST_EXCHANGE = "credit.score.request";
const BUREAUS = ["serasa", "boa-vista", "spc"] as const;
const GATHER_TIMEOUT_MS = 1_000;
const APPROVAL_SCORE_MIN = 650;
type ScoreReply = { bureau: string; score: number };
const connection = await amqplib.connect(Bun.env.SCATTER_GATHER_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
await channel.assertExchange(SCORE_REQUEST_EXCHANGE, "fanout", { durable: true });
for (const bureau of BUREAUS) {
await channel.assertQueue(`credit-score-${bureau}`, { durable: true });
await channel.purgeQueue(`credit-score-${bureau}`);
await channel.bindQueue(`credit-score-${bureau}`, SCORE_REQUEST_EXCHANGE, "");
}
// Serasa and Boa Vista answer with their own latency; SPC is down, so its copy waits in the queue and expires.
for (const [bureau, score, latencyMs] of [["serasa", 720, 60], ["boa-vista", 690, 150]] as const) {
await channel.consume(`credit-score-${bureau}`, async (message) => {
if (!message) return;
await Bun.sleep(latencyMs);
const reply: ScoreReply = { bureau, score };
channel.sendToQueue(message.properties.replyTo, Buffer.from(JSON.stringify(reply)), { correlationId: message.properties.correlationId });
channel.ack(message);
console.log(` [${bureau.toUpperCase()}] score ${score}`);
});
}
// One exclusive reply queue; the correlationId tells this batch's replies apart.
const { queue: replyQueue } = await channel.assertQueue("", { exclusive: true, autoDelete: true });
const correlationId = crypto.randomUUID();
const replies: ScoreReply[] = [];
const gathered = Promise.withResolvers<void>();
const timer = setTimeout(gathered.resolve, GATHER_TIMEOUT_MS);
await channel.consume(replyQueue, (message) => {
if (message?.properties.correlationId !== correlationId) return;
replies.push(JSON.parse(message.content.toString()) as ScoreReply);
if (replies.length < BUREAUS.length) return;
clearTimeout(timer);
gathered.resolve();
}, { noAck: true });
// expiration = the gather timeout: a bureau that comes back later never answers a batch nobody waits for.
channel.publish(SCORE_REQUEST_EXCHANGE, "", Buffer.from(JSON.stringify({ customerId: "CUST-12345678900" })), { replyTo: replyQueue, correlationId, expiration: String(GATHER_TIMEOUT_MS) });
await gathered.promise;
const averageScore = Math.round(replies.reduce((sum, reply) => sum + reply.score, 0) / Math.max(replies.length, 1));
const bureausMissing = BUREAUS.filter((bureau) => !replies.some((reply) => reply.bureau === bureau));
console.log(` [DECISION] average ${averageScore}, ${replies.length > 0 && averageScore >= APPROVAL_SCORE_MIN ? "approved" : "denied"}, missing [${bureausMissing.join(", ")}]`);
await connection.close();
Nível
introdutório
3/13
- Linhas de TypeScript
- 46
- Tipo
- B — um serviço (docker.sh)
Domínio financeiro
- Crédito/Empréstimo
Padrões do catálogo que implementa
- Scatter-Gather
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Variáveis de ambiente
- SCATTER_GATHER_RABBITMQ_URL
- amqp://guest:guest@localhost:5672
- RabbitMQ of the bureau queries.
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com Scatter-Gather?
O gather é um aggregator. Abrir Aggregator
Seu progresso
0/157 estudados
Fica salvo só neste navegador.