Pular para o conteúdo

Async Messaging

O produtor enfileira e recebe um id na hora; um worker processa no seu ritmo e o cliente consulta depois. Produtor e consumidor escalam separados.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

Pedido de crédito de R$ 15.000,00 aceito na hora com jobId; o worker aprova em background.

Planta

Sequência
5/5
add com jobId credit-REQ-0011jobId na hora2pega o job e decide3completed com a decisão4consulta o estado do job5ProdutorFila credit-approval (BullMQ/Redis)Worker de crédito
5

5 passos — reproduza para seguir o fluxo

Como funciona

4passos

O produtor enfileira e recebe um id na hora, e um worker processa no seu ritmo

Esconde cada passo: lembre antes de tocar para revelar.

Vocabulário compartilhado

  1. 1

    jobId = id do pedido; reenvio devolve o mesmo job

  2. 2

    Worker com concurrency: 3

  3. 3

    Aprova até R$ 50.000,00; acima, análise manual

  4. 4

    O cliente lê estado e decisão no job

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Produtor não bloqueia

  • Consumidor absorve picos

Custos

  • Resultado só por consulta posterior

  • Fila é mais uma peça de infraestrutura

Código

pattern/messaging/async-messaging

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 async-messaging-broker redis-cli ping >/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 async-messaging-broker

Saída: REQ-001 aceito sem esperar a análise; o reenvio cai no mesmo job credit-REQ-001; cliente recebe approved; 1 análise executada.

Requisitos
BunDocker
Sobe junto
Redis

Código

src/demo.ts

// Demo: the producer enqueues a credit request and moves on; a worker decides it in the background and the client reads the result later.
import { RedisClient } from "bun";
import { Queue, Worker, createBunRedisClient } from "bullmq";

const CREDIT_QUEUE = "credit-approval";
const CREDIT_LIMIT_AUTOMATIC_CENTS = 5_000_000;
const CREDIT_ANALYSIS_MS = 300;
const CREDIT_WORKER_CONCURRENCY = 3;
const REDIS_URL = Bun.env.ASYNC_MESSAGING_REDIS_URL ?? "redis://localhost:6380";

type CreditRequest = { requestId: string; amountCents: number };

// Bun's native client wrapped for BullMQ; the queue and the worker each get their own connection.
const queue = new Queue<CreditRequest>(CREDIT_QUEUE, { connection: createBunRedisClient(new RedisClient(REDIS_URL)) });

const stats = { analyses: 0 };
// Consumer: runs at its own pace; the analysis (bureau and score) takes time the producer never waits for.
const worker = new Worker<CreditRequest, { status: string }>(
  CREDIT_QUEUE,
  async (job) => {
    stats.analyses++;
    await Bun.sleep(CREDIT_ANALYSIS_MS);
    return { status: job.data.amountCents <= CREDIT_LIMIT_AUTOMATIC_CENTS ? "approved" : "manual_review" };
  },
  { connection: createBunRedisClient(new RedisClient(REDIS_URL)), concurrency: CREDIT_WORKER_CONCURRENCY },
);

// jobId = business id: resending the same request returns the existing job instead of analysing twice.
const startedAt = Date.now();
const job = await queue.add("credit.approve", { requestId: "REQ-001", amountCents: 1_500_000 }, { jobId: "credit-REQ-001" });
console.log(`  [PRODUCER] REQ-001 accepted as ${job.id} in ${Date.now() - startedAt} ms, not waiting for the analysis`);
// The client retries after a timeout: same jobId, so the queue returns the job it already has.
const resent = await queue.add("credit.approve", { requestId: "REQ-001", amountCents: 1_500_000 }, { jobId: "credit-REQ-001" });
console.log(`  [PRODUCER] REQ-001 resent → ${resent.id}`);

for (let i = 0; i < 50; i++) {
  const current = await queue.getJob("credit-REQ-001");
  const state = await current?.getState();
  if (state === "completed") {
    console.log(`  [CLIENT] REQ-001 ${state}: ${JSON.stringify(current?.returnvalue)} after ${Date.now() - startedAt} ms`);
    break;
  }
  await Bun.sleep(100);
}

console.log(`  [WORKER] analyses run: ${stats.analyses}`);

await queue.obliterate({ force: true });
await worker.close();
await queue.close();

Nível

introdutório

3/13

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

Domínio financeiro

  • Crédito/Empréstimo

Padrões do catálogo que implementa

Infraestrutura

  • Rediscache / estrutura de dados

    redis:7-alpine:6380

Variáveis de ambiente

ASYNC_MESSAGING_REDIS_URL
redis://localhost:6380
Redis backing the BullMQ credit-approval queue (docker.sh publishes it on 6380).

Por que se relacionam

Teste rápido

Qual destes combina com Async Messaging?

Próximo projeto, Mensageria & EventosAsync Request-Reply
Esc

↑ ↓ navegarEnter abrir239 resultados