pattern/messaging/message-history
- Bun
- RabbitMQ
- TypeScript
- amqplib
- Docker
O envelope acumula o registro de cada componente por onde a mensagem passou; o caminho sai da mensagem final, sem tracing externo.
pattern/messaging/message-history
Cenário
Proposta de crédito passa por KYC, score e compliance; a mensagem final mostra o caminho e o tempo de cada etapa.
Planta
Sequência4 passos — reproduza para seguir o fluxo
Como funciona
4passos
O envelope acumula o registro de cada componente por onde a mensagem passou
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
A API cria o envelope com a primeira entrada em history
Cada estágio acrescenta só a própria entrada
O envelope segue ao próximo estágio antes do ack
receivedAt em ISO 8601 dá a latência entre estágios
Trade-offs
O que se ganha, o que se paga
Vantagens
Caminho legível na mensagem
Sem backend de tracing
Custos
Payload cresce a cada estágio
Expõe a arquitetura interna
Código
pattern/messaging/message-history
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq message-history-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 message-history-brokerSaída: histórico com 4 entradas na mensagem: credit-api, kyc-service, score-service (835) e compliance-service aprovado.
Código
src/demo.ts// Demo: a credit application crosses KYC, score and compliance; each stage appends its entry to the history inside the message.
import amqplib from "amqplib";
type HistoryEntry = { service: string; receivedAt: string; note: string };
type Envelope = { applicationId: string; amountCents: number; history: HistoryEntry[] };
// Each stage consumes one queue and forwards to the next; credit-decided is the end of the line.
const CREDIT_STAGES = [
{ queue: "credit-kyc", next: "credit-score", service: "kyc-service", note: "identity verified" },
{ queue: "credit-score", next: "credit-compliance", service: "score-service", note: "credit score 835" },
{ queue: "credit-compliance", next: "credit-decided", service: "compliance-service", note: "no AML flags, approved" },
];
// Append-only: previous entries stay untouched and this stage's entry goes at the end.
const historyAppend = (envelope: Envelope, service: string, note: string): Envelope => ({
...envelope,
history: [...envelope.history, { service, receivedAt: new Date().toISOString(), note }],
});
const connection = await amqplib.connect(Bun.env.MESSAGE_HISTORY_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
for (const queue of [...CREDIT_STAGES.map((stage) => stage.queue), "credit-decided"]) {
await channel.assertQueue(queue, { durable: true });
await channel.purgeQueue(queue);
}
for (const stage of CREDIT_STAGES) {
await channel.consume(stage.queue, (message) => {
if (!message) return;
// The whole envelope, history included, goes forward before the consumed message is acked.
const envelope = historyAppend(JSON.parse(message.content.toString()) as Envelope, stage.service, stage.note);
channel.sendToQueue(stage.next, Buffer.from(JSON.stringify(envelope)), { persistent: true });
channel.ack(message);
});
}
const application: Envelope = { applicationId: "CRED-001", amountCents: 1_500_000, history: [] };
channel.sendToQueue("credit-kyc", Buffer.from(JSON.stringify(historyAppend(application, "credit-api", "application received"))), { persistent: true });
// The path and the latency are read from the final message alone, without a tracing backend.
for (let i = 0; i < 100; i++) {
const message = await channel.get("credit-decided", { noAck: true });
if (message) {
const { history } = JSON.parse(message.content.toString()) as Envelope;
for (const [index, entry] of history.entries()) {
const hopMs = index === 0 ? 0 : Date.parse(entry.receivedAt) - Date.parse(history[index - 1]!.receivedAt);
console.log(` [HISTORY] ${entry.service.padEnd(19)} +${hopMs}ms ${entry.note}`);
}
break;
}
await Bun.sleep(50);
}
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
Por que se relacionam
Teste rápido
Qual destes combina com Message History?
Identifica a mensagem em cada salto. Abrir Correlation ID
Seu progresso
0/157 estudados
Fica salvo só neste navegador.