Pular para o conteúdo

Retry

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.

passos
4
arquivos
5
testes
0
tecnologias
4

Cenário

O SPI do BACEN responde 503 duas vezes e liquida na terceira, uma vez só.

Planta

Sequência
6/6
idempotencyKey gerada antes do loopPOST /settlements (key K)1503 SPI_UNAVAILABLE2espera aleatória entre 0 e 100 msPOST /settlements (key K)3503 SPI_UNAVAILABLE4espera aleatória entre 0 e 200 msPOST /settlements (key K)5200 liquidado6Cliente PIXLiquidação BACEN
6

6 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.

  1. 1

    idempotencyKey gerada antes do loop

  2. 2

    Só 429, 502, 503, 504 e timeout são retentados

  3. 3

    Espera entre 0 e delayBaseMs × 2^(n−1), até delayMaxMs (full jitter)

  4. 4

    Em maxAttempts o erro sobe; chave repetida devolve a liquidação original

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .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: duas linhas [RETRY] com 503 e espera aleatória (até 100 ms e até 200 ms); a terceira tentativa liquida e settlements recorded: 1.

Requisitos
Bun

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);
Esc

↑ ↓ navegarEnter abrir239 resultados