pattern/resilience/timeout
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
Limite de tempo em cada chamada de rede; ao estourar, a conexão é abortada e o erro é explícito. Use em toda chamada remota.
pattern/resilience/timeout
Cenário
Antifraude com SLA de 400 ms responde em 700 ms: cortado em 400 ms e para de processar.
Planta
Sequência4 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.
Vocabulário compartilhado
timeoutRun cria AbortController e passa o signal ao fetch
O abort cancela a conexão real
Corrida contra o abort cobre quem ignora o signal
Timer limpo no finally
Trade-offs
O que se ganha, o que se paga
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./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: ErrorTimeout: antifraud exceeded 400 ms após cerca de 400 ms; o antifraude registra {"completed":0,"cancelled":1}.
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
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 1 de 6
Resiliência de ponta a ponta
Por que se relacionam
Próximo passo
Teste rápido
Qual é o próximo passo depois de Timeout?
Falha transitória merece nova tentativa. Abrir Retry
Seu progresso
0/157 estudados
Fica salvo só neste navegador.