Pular para o conteúdo

Aggregator

Junta mensagens com o mesmo correlationId numa só quando a condição de conclusão é atingida. Inverso do Splitter.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

As três confirmações de PIX do dia viram um relatório de fechamento (EOD) com o total liquidado.

Planta

Sequência
4/4
confirmações 1..3 (businessDate)1entrega2janela por businessDate3relatório EOD ao completar 34Liquidaçãosettlement-confirmationAggregatorsettlement-report
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Junta mensagens com o mesmo correlationId numa só quando a condição de conclusão é atingida

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    Cada confirmação traz businessDate (correlação), transactionId e valor

  2. 2

    A janela guarda por transactionId: reentrega não infla a contagem

  3. 3

    Total esperado atingidoRelatório em settlement-report

  4. 4

    A janela é descartada

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Consumidor recebe um resultado só

  • Deduplicação natural por chave

Custos

  • Estado da janela vive no aggregator

  • Mensagem que não chega exige timeout

Código

pattern/messaging/aggregator

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 --user rabbitmq aggregator-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 aggregator-broker

Saída: confirmações 1/3, 2/3 e 3/3 de 2026-07-11, a duplicata de PIX-2 ignorada; fechamento EOD com 3 transações e R$ 4250.00.

Requisitos
BunDocker
Sobe junto
RabbitMQ

Código

src/demo.ts

// Demo: settlement confirmations of one business date are aggregated into a single end-of-day report once all of them arrive.
import amqplib from "amqplib";

const SETTLEMENT_CONFIRMATION_QUEUE = "settlement-confirmation";
const SETTLEMENT_REPORT_QUEUE = "settlement-report";
const SETTLEMENT_CONFIRMATION_COUNT_EXPECTED = 3;

type Confirmation = { businessDate: string; transactionId: string; amountCents: number };

const connection = await amqplib.connect(Bun.env.AGGREGATOR_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
for (const queue of [SETTLEMENT_CONFIRMATION_QUEUE, SETTLEMENT_REPORT_QUEUE]) {
  await channel.assertQueue(queue, { durable: true });
  await channel.purgeQueue(queue);
}

// Window per correlation id (businessDate), keyed by transaction id so a redelivery never counts twice.
const windows = new Map<string, Map<string, number>>();

await channel.consume(SETTLEMENT_CONFIRMATION_QUEUE, (message) => {
  if (!message) return;
  const confirmation = JSON.parse(message.content.toString()) as Confirmation;
  const received = windows.get(confirmation.businessDate) ?? new Map<string, number>();
  const duplicate = received.has(confirmation.transactionId);
  windows.set(confirmation.businessDate, received.set(confirmation.transactionId, confirmation.amountCents));
  console.log(`  [AGGREGATOR] ${confirmation.businessDate} ${received.size}/${SETTLEMENT_CONFIRMATION_COUNT_EXPECTED} (${confirmation.transactionId}${duplicate ? " duplicate, ignored" : ""})`);
  // Completion condition: the count; the consolidated report leaves once and the window is dropped.
  if (received.size === SETTLEMENT_CONFIRMATION_COUNT_EXPECTED) {
    const amountCentsTotal = [...received.values()].reduce((sum, amount) => sum + amount, 0);
    channel.sendToQueue(SETTLEMENT_REPORT_QUEUE, Buffer.from(JSON.stringify({ businessDate: confirmation.businessDate, receivedCount: received.size, amountCentsTotal })));
    windows.delete(confirmation.businessDate);
  }
  channel.ack(message);
});

// PIX-2 arrives twice, as after a redelivery: the window must still close at 3 with the right total.
for (const [transactionId, amountCents] of [["PIX-1", 100_000], ["PIX-2", 250_000], ["PIX-2", 250_000], ["PIX-3", 75_000]] as const) {
  const confirmation: Confirmation = { businessDate: "2026-07-11", transactionId, amountCents };
  channel.sendToQueue(SETTLEMENT_CONFIRMATION_QUEUE, Buffer.from(JSON.stringify(confirmation)), { persistent: true, correlationId: confirmation.businessDate });
}

// Waits for the report instead of sleeping a fixed amount.
for (let i = 0; i < 100; i++) {
  const report = await channel.get(SETTLEMENT_REPORT_QUEUE, { noAck: true });
  if (report) {
    const { businessDate, receivedCount, amountCentsTotal } = JSON.parse(report.content.toString()) as { businessDate: string; receivedCount: number; amountCentsTotal: number };
    console.log(`  [EOD] ${businessDate}: ${receivedCount} transactions, R$ ${(amountCentsTotal / 100).toFixed(2)}`);
    break;
  }
  await Bun.sleep(50);
}

await connection.close();

Nível

introdutório

3/13

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

Domínio financeiro

  • PIX
  • Conta corrente
  • Liquidação

Padrões do catálogo que implementa

  • Aggregator

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-alpine:5672

Variáveis de ambiente

AGGREGATOR_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ used by the aggregator and the demo.

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Aggregator?

Próximo projeto, Mensageria & EventosAMQP Message Handler
Esc

↑ ↓ navegarEnter abrir239 resultados