Pular para o conteúdo

AMQP Message Handler

Consumer RabbitMQ que não perde mensagem: ack após o efeito, retry por fila com TTL e DLQ para falha permanente.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

Liquidação de PIX: PIX-001 liquida, PIX-002 liquida no retry, PIX-BLOCKED (fraude) vai para a DLQ.

Planta

Fluxo
7/7
Publicadorpayments.exchangepayments.queueConsumerpayments.queue.retry (TTL)payments.dlxpayments.dlqpayments.transferfalha transitóriaTTL expirafalhapermanente: nack
7

7 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.

  1. 1

    ack só após liquidar; prefetch limita mensagens sem ack

  2. 2

    Falha transitóriaCópia na fila de retry com x-attempt + 1, depois ack

  3. 3

    O TTL devolve a cópia à fila principal

  4. 4

    Falha permanente ou tentativas esgotadasnack sem requeue → DLQ

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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 amqp-message-handler-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 amqp-message-handler-broker

Saí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.

Requisitos
BunDocker
Sobe junto
RabbitMQ

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

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

Domínio financeiro

  • PIX
  • Antifraude
  • Liquidação

Infraestrutura

  • RabbitMQmessage broker

    rabbitmq:3-management-alpine:5672:15672

Variáveis de ambiente

AMQP_MESSAGE_HANDLER_RABBITMQ_URL
amqp://guest:guest@localhost:5672
RabbitMQ connection used by the publisher and the consumer.

Parecidos

Por que se relacionam

Teste rápido

Qual destes combina com AMQP Message Handler?

Próximo projeto, Mensageria & EventosAsync Messaging
Esc

↑ ↓ navegarEnter abrir239 resultados