Pular para o conteúdo

Async Request-Reply

A API responde 202 Accepted com Location, um worker processa em background e o cliente consulta por polling. Use quando a operação demora mais que uma requisição HTTP.

passos
4
arquivos
6
testes
0
tecnologias
6

Cenário

PIX com liquidação lenta (clearing e fraude); o app não fica bloqueado.

Planta

Sequência
7/7
POST /pix1job pending + LPUSH pix:queue2202 + Location /status/{id}3BRPOP pix:queue4job completed5GET /status/{id} (backoff)6completed + endToEndId7ClienteAPI PIXRedisWorker
7

7 passos — reproduza para seguir o fluxo

Como funciona

4passos

A API responde 202 Accepted com Location, um worker processa em background e o cliente consulta por polling

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    POST /pix grava o job pending no Redis, enfileira e responde 202 com Location

  2. 2

    O worker liquida e grava completed

  3. 3

    O cliente consulta GET /status/:requestId com backoff exponencial

  4. 4

    O job expira em 5 minutos

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Cliente não fica bloqueado

  • API e worker escalam separados

Custos

  • Cliente precisa fazer polling

  • Estado do job vive fora do processo

Código

pattern/messaging/async-request-reply

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-request-reply-cache 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-request-reply-cache

Saída: 202 com Location; polling devolve pending até o worker liquidar; depois completed com endToEndId.

Requisitos
BunDocker
Sobe junto
Redis

Código

src/demo.ts

// Demo: the PIX API answers 202 + Location at once, a worker settles in background, the client polls the status.
import { RedisClient } from "bun";
import { Elysia, t } from "elysia";

const PIX_QUEUE = "pix:queue";
const PIX_JOB_TTL_S = "300";
const PIX_API_URL = `http://localhost:${Bun.env.ASYNC_REQUEST_REPLY_API_PORT ?? 7010}`;

type PixJob = { requestId: string; status: "pending" } | { requestId: string; status: "completed"; endToEndId: string };

const redis = new RedisClient(Bun.env.ASYNC_REQUEST_REPLY_REDIS_URL ?? "redis://localhost:6379");
// BRPOP blocks its connection: the worker gets its own.
const redisWorker = await redis.duplicate();

const jobSave = (job: PixJob) => redis.set(`pix:job:${job.requestId}`, JSON.stringify(job), "EX", PIX_JOB_TTL_S);

const app = new Elysia()
  .post(
    "/pix",
    async ({ body, set, status }) => {
      const requestId = crypto.randomUUID();
      // Pending first, then enqueue: a fast worker never finds the job missing.
      await jobSave({ requestId, status: "pending" });
      await redis.lpush(PIX_QUEUE, JSON.stringify({ requestId, ...body }));
      set.headers.location = `/status/${requestId}`;
      return status(202, { requestId });
    },
    { body: t.Object({ accountFromId: t.String(), accountToId: t.String(), amountCents: t.Integer({ minimum: 1 }) }) },
  )
  .get("/status/:requestId", async ({ params, status }) => {
    const raw = await redis.get(`pix:job:${params.requestId}`);
    return raw ? (JSON.parse(raw) as PixJob) : status(404, { error: "pix.request.not_found" });
  })
  .listen(Number(Bun.env.ASYNC_REQUEST_REPLY_API_PORT ?? 7010));

// Background settlement: the slow part (clearing, fraud screening) the client must not wait on.
async function workerSettleOne(): Promise<void> {
  const [, raw] = (await redisWorker.send("BRPOP", [PIX_QUEUE, "5"])) as [string, string];
  const { requestId } = JSON.parse(raw) as { requestId: string };
  await Bun.sleep(600);
  await jobSave({ requestId, status: "completed", endToEndId: `E12345678${Date.now()}` });
  console.log(`  [WORKER] ${requestId} settled`);
}

// Polls with exponential backoff and a cap, never at a fixed short interval.
async function statusPoll(location: string): Promise<PixJob> {
  for (let attempt = 0; attempt < 10; attempt++) {
    const job = (await (await fetch(`${PIX_API_URL}${location}`)).json()) as PixJob;
    console.log(`  [POLL] ${location} → ${job.status}`);
    if (job.status !== "pending") return job;
    await Bun.sleep(Math.min(2_000, 100 * 2 ** attempt));
  }
  throw new Error("PIX did not settle in time");
}

const worker = workerSettleOne();
const response = await fetch(`${PIX_API_URL}/pix`, {
  method: "POST",
  headers: { "content-type": "application/json" },
  body: JSON.stringify({ accountFromId: "ACC-1001", accountToId: "ACC-2001", amountCents: 50_000 }),
});
const location = response.headers.get("location")!;
console.log(`  [API] HTTP ${response.status} Location: ${location}`);
const job = await statusPoll(location);
console.log(`  [CLIENT] ${job.status} endToEndId=${job.status === "completed" ? job.endToEndId : "-"}`);

await worker;
await app.stop();
redisWorker.close();
redis.close();

Nível

introdutório

3/13

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

Domínio financeiro

  • PIX
  • Antifraude
  • Liquidação

Padrões do catálogo que implementa

  • Async Request-Reply

Infraestrutura

  • Rediscache / estrutura de dados

    redis:7-alpine:6379

Variáveis de ambiente

ASYNC_REQUEST_REPLY_REDIS_URL
redis://localhost:6379
Redis holding the job store and the transfer queue.
ASYNC_REQUEST_REPLY_API_PORT
7010
Port of the PIX API (POST /pix, GET /status/:requestId).

Por que se relacionam

Teste rápido

Qual destes combina com Async Request-Reply?

Próximo projeto, Mensageria & EventosClaim Check
Esc

↑ ↓ navegarEnter abrir239 resultados