pattern/messaging/priority-queue
Priority Queue
Mensagem de prioridade maior é processada primeiro, independentemente da chegada; o RabbitMQ entrega sempre o nível mais alto disponível.
- passos
- 4
- arquivos
- 6
- testes
- 0
- tecnologias
- 5
Cenário
Boleto agendado, fornecedor, PIX emergencial e câmbio chegam juntos; câmbio não espera atrás do boleto.
Planta
Fluxo2 passos — reproduza para seguir o fluxo
- chamada
- resposta ou assíncrono
- falha
- passo
- toque num nó para focar
- Outras plantas de fluxo
Como funciona
4passos
Mensagem de prioridade maior é processada primeiro, independentemente da chegada
Esconde cada passo: lembre antes de tocar para revelar.
- 1
Fila com
x-max-priority: 10 - 2
Prioridade derivada do tipo de pagamento, nunca do chamador
- 3
Maior prioridade primeiro; empate por chegada
- 4
Worker com
prefetch(1)para não segurar baixa prioridade
Trade-offs
O que se ganha, o que se paga
Vantagens
Crítico não espera o rotineiro
Prioridade resolvida pelo broker
Custos
Baixa prioridade pode esperar indefinidamente
prefetchbaixo reduz a vazão
Código
pattern/messaging/priority-queue
6 arquivos./
- .env.exampleinfra
- docker.shinfra
- package.jsoninfra
- README.md
- tsconfig.jsoninfra
src/
- demo.tsdemo
Executar com Docker
./docker.shuntil docker exec --user rabbitmq priority-queue-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 priority-queue-broker
Saída: chegada na ordem 1, 5, 7, 10; liquidação na ordem 10 → 7 → 5 → 1.
- Requisitos
- BunDocker
- Sobe junto
- RabbitMQ
Código
src/demo.ts
// Demo: payments arrive in any order; the worker settles them by priority, derived from the payment type.
import amqplib from "amqplib";
const PAYMENT_QUEUE = "payment-priority";
const PAYMENT_PRIORITY_MAX = 10;
// Priority comes from what the payment is, never from what the caller asks for.
const PAYMENT_PRIORITY = { "fx-settlement": 10, "pix-emergency": 7, supplier: 5, "bill-scheduled": 1 } as const;
const arrivals: [string, keyof typeof PAYMENT_PRIORITY][] = [
["PAY-001", "bill-scheduled"],
["PAY-002", "supplier"],
["PAY-003", "pix-emergency"],
["PAY-004", "fx-settlement"],
];
const connection = await amqplib.connect(Bun.env.PRIORITY_QUEUE_RABBITMQ_URL ?? "amqp://guest:guest@localhost:5672");
const channel = await connection.createChannel();
// Without x-max-priority the queue ignores every priority and is plain FIFO.
await channel.assertQueue(PAYMENT_QUEUE, { durable: true, maxPriority: PAYMENT_PRIORITY_MAX });
await channel.purgeQueue(PAYMENT_QUEUE);
for (const [paymentId, type] of arrivals) {
channel.sendToQueue(PAYMENT_QUEUE, Buffer.from(JSON.stringify({ paymentId, type })), { persistent: true, priority: PAYMENT_PRIORITY[type] });
console.log(` [ARRIVED] ${paymentId} ${type.padEnd(14)} priority ${PAYMENT_PRIORITY[type]}`);
}
await Bun.sleep(100);
// prefetch 1: a larger buffer would hold low-priority payments before a critical one arrives.
await channel.prefetch(1);
const stats = { settled: 0 };
await channel.consume(PAYMENT_QUEUE, (message) => {
if (!message) return;
const { paymentId, type } = JSON.parse(message.content.toString()) as { paymentId: string; type: string };
console.log(` [SETTLED] ${paymentId} ${type.padEnd(14)} priority ${message.properties.priority}`);
channel.ack(message);
stats.settled++;
});
for (let i = 0; i < 100 && stats.settled < arrivals.length; i++) await Bun.sleep(25);
await connection.close();
Nível
introdutório
3/13
- Linhas de TypeScript
- 34
- Tipo
- B — um serviço (docker.sh)
Domínio financeiro
- PIX
- Boleto
- Câmbio
Padrões do catálogo que implementa
- Priority Queue
Infraestrutura
RabbitMQmessage broker
rabbitmq:3-alpine:5672
Variáveis de ambiente
- PRIORITY_QUEUE_RABBITMQ_URL
- amqp://guest:guest@localhost:5672
- RabbitMQ of the payment queue.
Por que se relacionam
Teste rápido
Qual destes combina com Priority Queue?
Mesma fila, urgente na frente. Abrir Point-to-Point
Seu progresso
0/157 estudados
Fica salvo só neste navegador.