Pular para o conteúdo

Timeout

Limite de tempo em cada chamada de rede; ao estourar, a conexão é abortada e o erro é explícito. Use em toda chamada remota.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

Antifraude com SLA de 400 ms responde em 700 ms: cortado em 400 ms e para de processar.

Planta

Sequência
4/4
POST /antifraud/score (limite 400 ms)1400 ms sem resposta, abortconexão cancelada2percebe o abort e para o trabalho3ErrorTimeout antifraud excedeu 400 ms4API PIXAntifraude (700 ms)
4

4 passos — reproduza para seguir o fluxo

Como funciona

4passos

Limite de tempo em cada chamada de rede, com a conexão abortada e erro explícito ao estourar

Esconde cada passo: lembre antes de tocar para revelar.

  1. 1

    timeoutRun cria AbortController e passa o signal ao fetch

  2. 2

    O abort cancela a conexão real

  3. 3

    Corrida contra o abort cobre quem ignora o signal

  4. 4

    Timer limpo no finally

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

Vantagens

  • Libera workers e explicita o erro

  • Abort cancela o trabalho remoto

Custos

  • Rejeita chamada que terminaria logo depois

  • Limite abaixo do p99 corta tráfego normal

Código

pattern/resilience/timeout

5 arquivos

./

  • .env.exampleinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar só Bun

  1. bun install# dependências
  2. bun run demo# roda o cenário

Saída: ErrorTimeout: antifraud exceeded 400 ms após cerca de 400 ms; o antifraude registra {"completed":0,"cancelled":1}.

Requisitos
Bun

Código

src/demo.ts

// Demo: the antifraud check of a PIX takes 700 ms; the 400 ms timeout aborts the real connection and the service stops working.
import { Elysia } from "elysia";

const ANTIFRAUD_URL = Bun.env.TIMEOUT_ANTIFRAUD_URL ?? "http://localhost:4203";
const ANTIFRAUD_LATENCY_MS = 700;
const ANTIFRAUD_SLA_MS = 400;

class ErrorTimeout extends Error {
  override name = "ErrorTimeout";
}

// The antifraud service, slow in this run: it stops working as soon as the caller goes away.
const stats = { completed: 0, cancelled: 0 };
const antifraud = new Elysia().post("/antifraud/score", async ({ request }) => {
  const finished = await new Promise<boolean>((resolve) => {
    const timer = setTimeout(() => resolve(true), ANTIFRAUD_LATENCY_MS);
    request.signal.addEventListener("abort", () => (clearTimeout(timer), resolve(false)), { once: true });
  });
  if (finished) stats.completed++;
  else stats.cancelled++;
  return { decision: "approve" };
}).listen(new URL(ANTIFRAUD_URL).port);

// The signal goes down to fetch, so the abort cancels the real connection; the race stops waiting even for an
// operation that ignores the signal; the timer is cleared in finally so a fast call leaves nothing behind.
async function timeoutRun<T>(operation: (signal: AbortSignal) => Promise<T>, limitMs: number, description: string): Promise<T> {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(new ErrorTimeout(`${description} exceeded ${limitMs} ms`)), limitMs);
  const aborted = new Promise<never>((_, reject) => controller.signal.addEventListener("abort", () => reject(controller.signal.reason)));
  try {
    return await Promise.race([operation(controller.signal), aborted]);
  } finally {
    clearTimeout(timer);
  }
}

const started = performance.now();
const outcome = await timeoutRun((signal) => fetch(`${ANTIFRAUD_URL}/antifraud/score`, { method: "POST", signal }).then((response) => response.json()), ANTIFRAUD_SLA_MS, "antifraud").catch((error: Error) => `${error.name}: ${error.message}`);
console.log(`  [PIX] ${JSON.stringify(outcome)} after ${Math.round(performance.now() - started)} ms`);
// The service learns of the abort asynchronously: wait for its counters, not a fixed time.
while (stats.completed + stats.cancelled === 0) await Bun.sleep(10);
console.log(`  [ANTIFRAUD] ${JSON.stringify(stats)}`);
await antifraud.stop(true);

Nível

introdutório

1/13

Linhas de TypeScript
38
Tipo
A — código puro

Domínio financeiro

  • PIX
  • Antifraude
  • Limite

Padrões do catálogo que implementa

  • Timeout

Variáveis de ambiente

TIMEOUT_ANTIFRAUD_URL
http://localhost:4203

Trilhapasso 1 de 6

Resiliência de ponta a ponta

  1. 1Timeout
  2. 2Retry
  3. 3Circuit Breaker
  4. 4Fallback
  5. 5Bulkhead
  6. 6Resilience Kit

Por que se relacionam

Teste rápido

Qual é o próximo passo depois de Timeout?

Próximo projeto, Concorrência & CoordenaçãoActor Model
Esc

↑ ↓ navegarEnter abrir239 resultados