pattern/messaging/amqp-message-handler
- Bun
- RabbitMQ
- TypeScript
- amqplib
- Docker
Consumer RabbitMQ que não perde mensagem: ack após o efeito, retry por fila com TTL e DLQ para falha permanente.
pattern/messaging/amqp-message-handler
Cenário
Liquidação de PIX: PIX-001 liquida, PIX-002 liquida no retry, PIX-BLOCKED (fraude) vai para a DLQ.
Planta
Fluxo7 passos — reproduza para seguir o fluxo
Como funciona
4passos
Consumer RabbitMQ que não perde mensagem: ack após o efeito, retry por fila com TTL e DLQ
Esconde cada passo: lembre antes de tocar para revelar.
Vocabulário compartilhado
ack só após liquidar; prefetch limita mensagens sem ack
Falha transitóriaCópia na fila de retry com x-attempt + 1, depois ack
O TTL devolve a cópia à fila principal
Falha permanente ou tentativas esgotadasnack sem requeue → DLQ
Trade-offs
O que se ganha, o que se paga
Vantagens
Nenhuma mensagem perdida
Retry sem bloquear o consumer
Custos
Reentrega exige efeito idempotente
Uma fila de retry por atraso
Código
pattern/messaging/amqp-message-handler
6 arquivos./
src/
Executar com Docker
./docker.shuntil docker exec --user rabbitmq amqp-message-handler-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 amqp-message-handler-brokerSaída: PIX-001 liquidado; PIX-BLOCKED vai para a DLQ; PIX-002 falha na 1ª tentativa e liquida no retry; payments.dlq com 1 mensagem.
Código
src/demo.ts// Demo: a PIX consumer that acks after settling, retries through a TTL queue and dead-letters permanent failures.
import amqplib, { type ConfirmChannel, type ConsumeMessage } from "amqplib";
const PAYMENT_EXCHANGE = "payments.exchange";
const PAYMENT_QUEUE = "payments.queue";
const PAYMENT_RETRY_QUEUE = "payments.queue.retry";
const PAYMENT_DLX = "payments.dlx";
const PAYMENT_DLQ = "payments.dlq";
const PAYMENT_RETRY_DELAY_MS = 300;
const PAYMENT_ATTEMPTS_MAX = 3;
const PAYMENT_PREFETCH_COUNT = 10;
interface InterfacePayment {
id: string;
amountCents: number;
}
class ErrorPaymentPermanent extends Error {}
const payments: InterfacePayment[] = [
{ id: "PIX-001", amountCents: 50_000 },
{ id: "PIX-002", amountCents: 125_000 },
{ id: "PIX-BLOCKED", amountCents: 999_999 },
];
// PIX-002 fails on the first attempt (transient); PIX-BLOCKED never settles (permanent).
async function paymentSettle(payment: InterfacePayment, attempt: number): Promise<void> {
if (payment.id === "PIX-BLOCKED") throw new ErrorPaymentPermanent("blocked by fraud detection");
if (payment.id === "PIX-002" && attempt === 1) throw new Error("payment service unavailable");
console.log(` [PIX] ${payment.id} settled R$ ${(payment.amountCents / 100).toFixed(2)}`);
}
async function topologyAssert(channel: ConfirmChannel): Promise<void> {
await channel.assertExchange(PAYMENT_EXCHANGE, "topic", { durable: true });
await channel.assertExchange(PAYMENT_DLX, "direct", { durable: true });
// Rejected without requeue → DLX → DLQ.
await channel.assertQueue(PAYMENT_QUEUE, { durable: true, deadLetterExchange: PAYMENT_DLX, deadLetterRoutingKey: PAYMENT_DLQ });
await channel.bindQueue(PAYMENT_QUEUE, PAYMENT_EXCHANGE, "payments.#");
await channel.assertQueue(PAYMENT_DLQ, { durable: true });
await channel.bindQueue(PAYMENT_DLQ, PAYMENT_DLX, PAYMENT_DLQ);
// Expired copies return to the work queue: a delayed retry without blocking the consumer.
await channel.assertQueue(PAYMENT_RETRY_QUEUE, { durable: true, messageTtl: PAYMENT_RETRY_DELAY_MS, deadLetterExchange: "", deadLetterRoutingKey: PAYMENT_QUEUE });
await Promise.all([PAYMENT_QUEUE, PAYMENT_RETRY_QUEUE, PAYMENT_DLQ].map((queue) => channel.purgeQueue(queue)));
}
// Ack only after the effect; the attempt travels in a header so it survives a worker restart.
async function messageHandle(channel: ConfirmChannel, message: ConsumeMessage): Promise<void> {
const attempt = Number(message.properties.headers?.["x-attempt"] ?? 1);
const payment = JSON.parse(message.content.toString()) as InterfacePayment;
try {
await paymentSettle(payment, attempt);
channel.ack(message);
} catch (error) {
if (error instanceof ErrorPaymentPermanent || attempt >= PAYMENT_ATTEMPTS_MAX) {
channel.nack(message, false, false);
console.log(` [DLQ] ${payment.id}: ${(error as Error).message}`);
return;
}
// Publish the confirmed copy first, then ack the original: a crash in between duplicates, never loses.
channel.sendToQueue(PAYMENT_RETRY_QUEUE, message.content, { persistent: true, headers: { "x-attempt": attempt + 1 } });
await channel.waitForConfirms();
channel.ack(message);
console.log(` [RETRY] ${payment.id} attempt ${attempt} failed: ${(error as Error).message}`);
}
}
async function queuesDrainWait(channel: ConfirmChannel): Promise<void> {
for (let i = 0; i < 100; i++) {
const [work, retry, dlq] = await Promise.all([PAYMENT_QUEUE, PAYMENT_RETRY_QUEUE, PAYMENT_DLQ].map((queue) => channel.checkQueue(queue)));
if (work!.messageCount === 0 && retry!.messageCount === 0 && dlq!.messageCount === 1) return;
await Bun.sleep(100);
}
}
async function main(): Promise<void> {
const connection = await amqplib.connect(Bun.env.AMQP_MESSAGE_HANDLER_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createConfirmChannel();
await topologyAssert(channel);
// prefetch caps unacked messages per consumer.
await channel.prefetch(PAYMENT_PREFETCH_COUNT);
await channel.consume(PAYMENT_QUEUE, (message) => message && void messageHandle(channel, message));
for (const payment of payments) {
channel.publish(PAYMENT_EXCHANGE, "payments.transfer", Buffer.from(JSON.stringify(payment)), { persistent: true });
}
await channel.waitForConfirms();
await queuesDrainWait(channel);
const dlq = await channel.checkQueue(PAYMENT_DLQ);
console.log(` [QUEUE] ${PAYMENT_DLQ}: ${dlq.messageCount} message`);
await connection.close();
}
await main();
Nível
intermediário
4/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-management-alpine:5672:15672
Variáveis de ambiente
Parecidos
Por que se relacionam
Teste rápido
Qual destes combina com AMQP Message Handler?
Requeue exige consumo idempotente. Abrir Idempotency
Seu progresso
0/157 estudados
Fica salvo só neste navegador.