Skip to main content
502Retryable

OpenAI 502 Bad Gateway

An edge proxy in front of the API got an invalid response from upstream — infrastructure, not your request.

Most likely causes

  1. 1.Edge/CDN blip between Cloudflare and origin
  2. 2.Deploy in progress upstream

Fix checklist

  • Retry with backoff — almost always transient
  • For streams, reconnect with a fresh request

Retry guidance

Retry after 1s, then 2s, 4s with jitter; alert after 3 failures.

// Retry 502 with exponential backoff + full jitter.
async function callWithBackoff(payload: unknown, maxAttempts = 5) {
  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const res = await fetch("https://api.openai.com/v1/chat/completions", {
      method: "POST",
      headers: {
        "content-type": "application/json",
        Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
      },
      body: JSON.stringify(payload),
    });
    if (res.status !== 502) return res;
    // Honor Retry-After when present; otherwise exponential backoff, capped at 32s.
    const retryAfter = Number(res.headers.get("retry-after"));
    const base = Number.isFinite(retryAfter) && retryAfter > 0
      ? retryAfter * 1000
      : Math.min(1000 * 2 ** attempt, 32_000);
    await new Promise((r) => setTimeout(r, base * (0.5 + Math.random() * 0.5)));
  }
  throw new Error("OpenAI 502: still failing after backoff — check https://status.openai.com");
}

Provider status page: status.openai.com