pattern/resilience/retry
- AbortSignal
- Bun
- ElysiaJS
- TypeScript
Repete operação com falha transitória (503, timeout, rate limit) com teto e espera crescente com jitter; em escrita, a mesma chave idempotente em toda tentativa.
pattern/resilience/retry
Cenário
O SPI do BACEN responde 503 duas vezes e liquida na terceira, uma vez só.
Planta
Sequência6 passos — reproduza para seguir o fluxo
Como funciona
4passos
Repete operação com falha transitória (503, timeout, rate limit) com teto e espera crescente com jitter
Esconde cada passo: lembre antes de tocar para revelar.
idempotencyKey gerada antes do loop
Só 429, 502, 503, 504 e timeout são retentados
Espera entre 0 e delayBaseMs × 2^(n−1), até delayMaxMs (full jitter)
Em maxAttempts o erro sobe; chave repetida devolve a liquidação original
Trade-offs
O que se ganha, o que se paga
Vantagens
Falha transitória não chega ao cliente
Jitter espalha as tentativas
Custos
Latência soma as esperas
Escrita exige idempotência no destino
Código
pattern/resilience/retry
5 arquivos./
src/
Executar só Bun
bun install# dependênciasbun run demo# roda o cenárioSaída: duas linhas [RETRY] com 503 e espera aleatória (até 100 ms e até 200 ms); a terceira tentativa liquida e settlements recorded: 1.
Código
src/demo.ts// Demo: a PIX settlement where the BACEN SPI answers 503 twice; the client retries with full-jitter backoff and one idempotency key.
import { Elysia, t } from "elysia";
const BACEN_URL = Bun.env.RETRY_BACEN_URL ?? "http://localhost:4202";
const RETRY = { maxAttempts: 4, delayBaseMs: 100, delayMaxMs: 2_000 };
const SETTLEMENT_TIMEOUT_MS = 300;
class ErrorUpstream extends Error {
override name = "ErrorUpstream";
constructor(readonly status: number) {
super(`BACEN answered ${status}`);
}
}
// The BACEN settlement, idempotent by key (the condition for any retry that writes); the next 2 calls answer 503.
let unavailable = 2;
const settled = new Map<string, { endToEndId: string }>();
const bacen = new Elysia().post("/settlements", ({ headers, status }) => {
if (unavailable-- > 0) return status(503, { code: "SPI_UNAVAILABLE" });
const key = headers["idempotency-key"] ?? "";
// A replay answers the original result: the debit happens once, whatever the number of attempts.
if (!settled.has(key)) settled.set(key, { endToEndId: `E${Date.now()}` });
return settled.get(key);
}, { body: t.Object({ pixKey: t.String(), amountCents: t.Integer({ minimum: 1 }) }) }).listen(new URL(BACEN_URL).port);
// Only transient infrastructure failures are retried; a business 4xx or an unknown error goes up at once.
const errorIsRetryable = (error: unknown) => (error instanceof ErrorUpstream && [429, 502, 503, 504].includes(error.status)) || (error instanceof Error && error.name === "TimeoutError");
// Full jitter: anywhere between 0 and the capped exponential, so clients that failed together do not retry together.
const backoffDelay = (attempt: number) => Math.floor(Math.random() * Math.min(RETRY.delayBaseMs * 2 ** (attempt - 1), RETRY.delayMaxMs));
async function retryWith<T>(operation: () => Promise<T>): Promise<T> {
for (let attempt = 1; ; attempt++) {
try {
return await operation();
} catch (error) {
if (!errorIsRetryable(error) || attempt >= RETRY.maxAttempts) throw error;
const delayMs = backoffDelay(attempt);
console.log(` [RETRY] attempt ${attempt} failed (${(error as Error).message}), waiting ${delayMs} ms`);
await Bun.sleep(delayMs);
}
}
}
// The idempotency key is generated once, before the loop, and every attempt sends it.
const idempotencyKey = crypto.randomUUID();
const result = await retryWith(async () => {
const response = await fetch(`${BACEN_URL}/settlements`, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": idempotencyKey }, body: JSON.stringify({ pixKey: "maria@banco.com", amountCents: 15_000 }), signal: AbortSignal.timeout(SETTLEMENT_TIMEOUT_MS) });
if (!response.ok) throw new ErrorUpstream(response.status);
return response.json();
});
console.log(` [PIX] settled ${JSON.stringify(result)}, settlements recorded: ${settled.size}`);
await bacen.stop(true);
Nível
introdutório
1/13
Domínio financeiro
Padrões do catálogo que implementa
Variáveis de ambiente
Trilhapasso 2 de 6
Resiliência de ponta a ponta
Parecidos
Relações
Onde ele se encaixa
Por que se relacionam
Próximo passo
Combina com
Teste rápido
Qual é o próximo passo depois de Retry?
Para de insistir no que caiu. Abrir Circuit Breaker
Seu progresso
0/157 estudados
Fica salvo só neste navegador.