pattern/messaging/splitter
- Bun
- RabbitMQ
- TypeScript
- amqplib
- Docker
Decompõe uma mensagem composta em mensagens individuais processadas de forma independente. Inverso do Aggregator.
pattern/messaging/splitter
Cenário
Remessa com PIX, TED, boleto e um PIX de valor zero vira uma mensagem por pagamento; o inválido não derruba os outros.
Planta
Fluxo3 passos — reproduza para seguir o fluxo
Como funciona
4passos
Decompõe uma mensagem composta em mensagens individuais processadas de forma independente
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
Uma mensagem persistente por pagamento
Cada item leva batchId, sequence e total
waitForConfirms garante todos no broker
O worker liquida um item por vez com ack; o inválido sai com nack sozinho
Trade-offs
O que se ganha, o que se paga
Vantagens
Falha de um item não afeta os outros
Itens em paralelo
Custos
Fim do lote exige Aggregator
Mais mensagens no broker
Código
pattern/messaging/splitter
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq splitter-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 splitter-brokerSaída: REM-2026-10-10-1 dividida em 4 itens: PIX, TED e boleto liquidados; PIX de valor zero rejeitado; lote com 3 liquidados e 1 rejeitado.
Código
src/demo.ts// Demo: a remittance file is split into one message per payment; the settlement worker sees one item at a time, never the batch.
import amqplib from "amqplib";
const REMITTANCE_ITEM_QUEUE = "remittance-item";
type RemittanceItem = { batchId: string; sequence: number; total: number; accountId: string; amountCents: number; rail: string };
const connection = await amqplib.connect(Bun.env.SPLITTER_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createConfirmChannel();
await channel.assertQueue(REMITTANCE_ITEM_QUEUE, { durable: true });
await channel.purgeQueue(REMITTANCE_ITEM_QUEUE);
const batch = {
batchId: "REM-2026-10-10-1",
payments: [
{ accountId: "ACC-1001", amountCents: 125_000, rail: "pix" },
{ accountId: "ACC-1002", amountCents: 89_050, rail: "ted" },
{ accountId: "ACC-1003", amountCents: 340_000, rail: "boleto" },
// Invalid on purpose: as its own message it is rejected alone, the rest of the batch still settles.
{ accountId: "ACC-1004", amountCents: 0, rail: "pix" },
],
};
// Each item carries batchId, sequence and total: enough for an aggregator to tell when the batch is complete.
for (const [index, payment] of batch.payments.entries()) {
const item: RemittanceItem = { batchId: batch.batchId, sequence: index + 1, total: batch.payments.length, ...payment };
channel.sendToQueue(REMITTANCE_ITEM_QUEUE, Buffer.from(JSON.stringify(item)), { persistent: true, correlationId: batch.batchId });
}
// Confirmed by the broker: if the splitter dies after this, every item is already safe.
await channel.waitForConfirms();
console.log(` [SPLITTER] ${batch.batchId} split into ${batch.payments.length} items`);
const stats = { settled: 0, rejected: 0 };
await channel.consume(REMITTANCE_ITEM_QUEUE, (message) => {
if (!message) return;
const item = JSON.parse(message.content.toString()) as RemittanceItem;
if (item.amountCents <= 0) {
console.log(` [SETTLEMENT] ${item.sequence}/${item.total} ${item.rail.toUpperCase()} → ${item.accountId} rejected: amount must be positive`);
channel.nack(message, false, false);
stats.rejected++;
return;
}
console.log(` [SETTLEMENT] ${item.sequence}/${item.total} ${item.rail.toUpperCase()} R$ ${(item.amountCents / 100).toFixed(2)} → ${item.accountId}`);
channel.ack(message);
stats.settled++;
});
for (let i = 0; i < 100 && stats.settled + stats.rejected < batch.payments.length; i++) await Bun.sleep(50);
console.log(` [BATCH] ${batch.batchId}: ${stats.settled} settled, ${stats.rejected} rejected`);
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
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Splitter?
Completa cada parte. Abrir Content Enricher
Seu progresso
0/157 estudados
Fica salvo só neste navegador.