Tratamento de Erros 429 e Cabeçalho Retry-After

Para assegurar estabilidade operacional coletiva e proteção contra sobrecarga, o Yzex Connect impõe limites de requisições baseados em janelas deslizantes (sliding windows).

Cabeçalhos de Rate Limiting

Todas as respostas HTTP da API retornam métricas de consumo nos headers:

Cabeçalho Descrição

RateLimit-Limit

Cota máxima permitida no intervalo configurado.

RateLimit-Remaining

Quantidade de chamadas remanescentes na janela atual.

RateLimit-Reset

Segundos restantes até a redefinição integral da cota.

Retry-After

(Presente apenas em HTTP 429) Segundos obrigatórios de espera antes de tentar novamente.

Implementação de Backoff Exponencial com Jitter

Ao receber o código de status 429 Too Many Requests, sua aplicação cliente DEVE honrar o valor estipulado no cabeçalho Retry-After. Se o cabeçalho não estiver presente, utilize a estratégia de backoff exponencial com ruído estocástico (Full Jitter):

export async function fetchWithRetry(
  url: string,
  options: RequestInit,
  maxRetries = 3
): Promise<Response> {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    const res = await fetch(url, options);

    if (res.status !== 429) {
      return res;
    }

    const retryAfterHeader = res.headers.get('Retry-After');
    let waitMs = 0;

    if (retryAfterHeader) {
      waitMs = parseInt(retryAfterHeader, 10) * 1000;
    } else {
      // Full Jitter: random_between(0, min(cap, base * 2 ** attempt))
      const base = 500;
      const cap = 10000;
      const exponential = Math.min(cap, base * Math.pow(2, attempt));
      waitMs = Math.random() * exponential;
    }

    await new Promise((resolve) => setTimeout(resolve, waitMs));
  }

  throw new Error(`Excedido limite de retries (${maxRetries}) para chamada à API.`);
}