Fix 502 Bad Gateway Errors in GPT and Claude API Calls

Zivv••43 min read
On this page
  1. Who Actually Returns the 502
  2. Step 1: Get the Raw Response and Identify the Hop
  3. 502 vs 500, 503, 504, and 529
  4. What Zivv Returns When an Upstream Fails
  5. How to Fix It
  6. How 502 Shows Up in Common Clients
  7. Preventing Repeat 502s
  8. FAQ

When a GPT or Claude call fails with 502 Bad Gateway, the reflex is to assume OpenAI or Anthropic is down. Sometimes it is. More often it is not, because 502 is the status code HTTP reserves for intermediaries: a server acting as a gateway forwarded your request to the next hop and got back nothing usable. An AI API call typically passes through three or four hops, and any of them can be the gateway that says 502. Same status code, very different fixes.

This guide is for developers calling OpenAI-compatible or Anthropic endpoints directly or through a gateway, and for anyone seeing 502 inside Claude Code, Codex, or Cursor. Throttling (429) and upstream overload (529) have their own guides: fixing 429 errors and 529s, timeouts, and dropped streams. This one is only about 502.

Who Actually Returns the 502

A typical request crosses these hops:

Your code / Claude Code / Cursor
        │
        ▼
① Your side: self-hosted Nginx, corporate gateway, local proxy, serverless platform
        │
        ▼
② API gateway or relay (for example, zivv.pro)
        │
        ▼
③ Upstream provider (OpenAI, Anthropic, Google, ...)

The rule of thumb: when a hop fails, the 502 comes from the hop in front of it. If your backend process crashes, your Nginx returns the 502. If the upstream provider misbehaves, the API gateway does. So the useful question is not "who sent the 502?" but "what is behind whoever sent it?"

Where the 502 originatesCommon causesWhat the response usually looks like
① Your own reverse proxyBackend crashed, restarting, wrong port, or slower than the proxy timeoutAn HTML page titled 502 Bad Gateway, with a server name such as nginx in the footer
① Corporate gateway or local proxyProxy cannot reach the target host, a proxy node is down, TLS handshake failsDepends on the proxy: often an empty body or the proxy's own error page
② API gatewayUpstream returned an unusable response, or every upstream is unavailableJSON in the protocol's error format, plus the gateway's own request ID
③ Upstream providerSomething inside the provider's stack failedUsually rewritten by the gateway; in the provider's format if you call it directly

One detail worth knowing: Anthropic's official error reference does not list 502 at all. Its documented 5xx errors are 500 api_error, 504 timeout_error, and 529 overloaded_error. A 502 on a direct Anthropic call is therefore more likely produced by a proxy layer somewhere in the path, including the provider's own edge, than by the API logic itself.

Step 1: Get the Raw Response and Identify the Hop

A "502" toast in a client tells you almost nothing. Reproduce the call with curl and -i to see headers and body:

curl -i https://zivv.pro/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-6.1-terra","messages":[{"role":"user","content":"ping"}]}'

Four things matter: the status line, Content-Type, any request-ID header, and the shape of the body. Then match what you see:

What you seeWhat it meansNext move
Content-Type: text/html with a 502 error pageA reverse proxy generated it; the request never reached the API applicationCheck your own Nginx or corporate gateway; also appears briefly while an entry proxy restarts, so retry after a moment
JSON with error.type and a request-ID headerThe API gateway application answeredNote the request ID and act on the message
No HTTP response at all, curl reports a connection errorNetwork path or local proxyCompare with the proxy bypassed
Always fails after the same duration, such as 60 secondsA timeout at one layerMatch that duration against every layer's timeout setting
Only large requests or long outputs failTimeout or oversized payloadStream, split the task, trim context
One model returns 502, others workThat model's upstream is unstableSwitch models or configure fallbacks

On Zivv there is a quick tell: every response from the Zivv application, errors included, carries x-request-id and request-id headers whose values start with req_. A 502 that is neither JSON nor carries those headers did not come from Zivv's application; it came from a layer in front of it.

If you suspect a local proxy, compare the request with and without it:

# Did the request go through a proxy from your environment, and what came back?
curl -sv https://zivv.pro/v1/models \
  -H "Authorization: Bearer sk-your-key" -o /dev/null 2>&1 | grep -i -E "proxy|< HTTP"

# Same request with every proxy bypassed, plus timing
curl -sS --noproxy '*' -o /dev/null -w "HTTP %{http_code} in %{time_total}s\n" \
  https://zivv.pro/v1/models -H "Authorization: Bearer sk-your-key"

Different results point at the proxy. If /v1/models succeeds but chat requests return 502, your key, base URL, and network are fine; the problem is the target model's upstream or the request itself.

502 vs 500, 503, 504, and 529

These codes get used loosely, but they mean different things and call for different reactions:

StatusMeaningUsual location of the problemWhat to do
500 Internal Server ErrorThe server failed while handling the request; Anthropic calls it api_errorServer side, occasionally triggered by specific request contentRetry once or twice; if the same request keeps failing, inspect the payload
502 Bad GatewayA gateway got no valid response from the next hopOne hop in the chainRetry with backoff; if it persists, locate the hop
503 Service UnavailableThe service cannot handle the request right nowCapacity, maintenance, or unavailable upstreamsRetry with longer gaps
504 Gateway TimeoutA gateway waited too long for the next hop; Anthropic calls it timeout_errorA timeout somewhere, or a task that is simply too longSwitch to streaming and fix timeouts before retrying
529 OverloadedAnthropic-specific overloaded_errorUpstream capacity is saturatedBack off and shift load; see the 529 guide

The short version for 502 vs 504: a 502 means the next hop answered with garbage or could not be reached at all; a 504 means it never answered before the deadline. When you see 504, look at timeouts first. When you see 502, check whether the service behind the gateway is alive.

What Zivv Returns When an Upstream Fails

Zivv sits at hop ②, so how it handles upstream failures decides what you end up seeing:

  • Upstream 502, 503, or 504, a connection failure, or a single channel timing out: Zivv does not hand the error straight to you. It retries on the next upstream channel for the same model and briefly deprioritizes the failing channel. If any channel succeeds, you just get a normal response.
  • Every candidate channel for the model fails: Zivv picks the status from the dominant failure type. Mostly channel faults returns 503 with service temporarily unavailable, please try again later; mostly rate limits returns 429; mostly overload returns 529. In other words, when a model's upstreams are broadly down, Zivv usually reports 503, not 502.
  • When Zivv itself returns 502: the upstream sent a success status with a body that could not be processed (upstream returned a response that could not be processed, error.code set to upstream_error); an image generation request came back without an image (upstream returned no generated image); or every channel failed on the embeddings endpoint (embeddings upstream unavailable, please retry later).
  • Streaming requests: once the response headers are sent (HTTP 200), a later failure can only be reported as an in-stream error event. An unrecognized upstream error mid-stream shows up as api_error with upstream service error; upstream overload shows up as overloaded_error.

A 502 on the OpenAI-compatible endpoint looks like this (the Anthropic endpoint uses the {"type":"error","error":{"type":"api_error","message":"..."}} shape):

{
  "error": {
    "message": "upstream returned a response that could not be processed",
    "type": "api_error",
    "param": null,
    "code": "upstream_error"
  }
}

Two rules hold across all of these: the error text is always Zivv's own wording, never the upstream's raw message, and a request that fails without returning content is not billed.

To see how many attempts a request took behind the scenes and how each one ended, pass the request ID from the response headers to /v1/generation:

curl "https://zivv.pro/v1/generation?id=req_xxxxxxxx" \
  -H "Authorization: Bearer sk-your-key"

The attempts array lists every attempt in order with its model, status code, and duration, and total_cost is what the request cost in total; no channel details are exposed. Usage is written when the request finishes, so allow a few seconds. The same request ID is searchable in the console's usage logs, and the detail view lets you open a support ticket with that request attached.

How to Fix It

Fix 1: Retry with Backoff to Absorb Occasional 502s

Every multi-hop system produces the occasional 502. The standard answer is to retry only the statuses worth retrying, back off exponentially with jitter, and cap the attempts. This version also logs which hop answered:

import random
import time

import httpx

RETRYABLE = {502, 503, 504, 529}
TIMEOUT = httpx.Timeout(connect=10.0, write=30.0, read=300.0, pool=10.0)


def chat(payload, max_attempts=4):
    for attempt in range(max_attempts):
        resp = None
        try:
            resp = httpx.post(
                "https://zivv.pro/v1/chat/completions",
                headers={"Authorization": "Bearer sk-your-key"},
                json=payload,
                timeout=TIMEOUT,
            )
        except (httpx.ConnectError, httpx.ReadError, httpx.RemoteProtocolError) as exc:
            print("connection-level failure:", type(exc).__name__)
        if resp is not None:
            if resp.status_code < 400:
                return resp.json()
            # HTML usually means a proxy layer; JSON plus a request ID means the API gateway
            print(resp.status_code, resp.headers.get("content-type"),
                  resp.headers.get("x-request-id"))
            if resp.status_code not in RETRYABLE:
                resp.raise_for_status()  # retrying a 4xx never helps
        if attempt == max_attempts - 1:
            raise RuntimeError("gave up after repeated 5xx responses")
        retry_after = resp.headers.get("retry-after", "") if resp is not None else ""
        delay = float(retry_after) if retry_after.isdigit() else min(2 ** attempt, 20)
        time.sleep(delay + random.uniform(0, 1))


chat({"model": "gpt-6.1-terra", "messages": [{"role": "user", "content": "ping"}]})

Three things to keep in mind:

  • Whether to retry 500: you can add it to RETRYABLE, but a request that fails with 500 every time is usually triggering the error with its content, and no number of retries will change that
  • Do not stack retry layers: the official OpenAI and Anthropic SDKs already retry connection errors, 429, and 5xx twice by default. If you wrap your own loop around them, set the SDK's max_retries to 0, or rely on the SDK alone. Anthropic responses can also carry x-should-retry: false, which the official SDK honors
  • You are retrying the whole request: that is safe for plain completions; workflows with side effects, such as writing results to a database, must tolerate running twice

Fix 2: Check Status Pages and Model Uptime

If a few retries still end in 502, find out whether the upstream is having an incident. Calling providers directly, check their status pages (status.openai.com, status.anthropic.com). On Zivv, open the model's page in the Model Hub, for example gpt-6.1-terra: its 24-hour status panel shows availability measured from real traffic on the site, refreshed every five minutes and broken down by hour. A model that clearly degrades in a given window is an upstream problem, and waiting or switching models beats editing code.

Fix 3: Switch Models or Declare Fallbacks per Request

When one model keeps failing while others work, switching is the fastest fix. To make that automatic, Zivv supports request-level model fallback: add a top-level models array (the same field name OpenRouter uses), and if every channel for the primary model fails with 429, 5xx, or 529, the gateway moves to the next model in order, up to three alternates:

curl -i https://zivv.pro/v1/chat/completions \
  -H "Authorization: Bearer sk-your-key" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-6.1-terra",
    "models": ["claude-sonnet-5-5", "gemini-4-hydrogen"],
    "messages": [{"role": "user", "content": "ping"}]
  }'

The X-Zivv-Model response header names the model that actually served the request. Fallback works on /v1/chat/completions, /v1/messages, and /v1/responses; it never switches models after output has started streaming to you, and malformed requests do not trigger it. The full rules and advice on choosing alternates are in request-level model fallback.

Fix 4: Shrink the Payload and Split Long Jobs

The bigger and longer a request, the more likely it runs into some hop's timeout or resource ceiling:

  • Send images by URL where supported instead of tens of megabytes of base64
  • Compact long conversations and send only the context the task needs
  • Stream long outputs, or split them into several shorter requests

An oversized body normally produces 413, not 502; if you see 413, treat it as "request too large" and trim. For splitting long jobs and resuming after a failure, see the 529 and timeout guide.

Fix 5: Line Up Your Timeouts, Outer Longer Than Inner

Plenty of 502s and 504s are generated on your side of the chain. The classic setup is a Next.js or FastAPI backend that calls the model, with Nginx in front. Nginx's proxy_read_timeout defaults to 60 seconds, so a non-streaming request that generates for two minutes gets cut off by Nginx first. The client receives Nginx's error page, and the real error from your backend is lost.

The principle: each outer layer should wait a little longer than the layer inside it, so the inner layer times out first and hands back a structured JSON error. Zivv's own entry point follows this rule: its entry Nginx allows 30 seconds more than the limit Zivv applies while waiting for upstream response headers, so a timeout reaches the client as Zivv's JSON error rather than an Nginx 504 page. For your own reverse proxy:

location /api/chat {
    proxy_pass http://127.0.0.1:3000;
    proxy_http_version 1.1;
    proxy_set_header Connection "";
    proxy_buffering off;        # never buffer streamed output
    proxy_connect_timeout 5s;
    proxy_read_timeout 330s;    # longer than the backend's own model-call timeout
    proxy_send_timeout 300s;
}

proxy_read_timeout measures the gap between two reads, not the total duration. A streaming response that keeps sending data never trips it, which is one more reason to stream long outputs. For streams that stall or drop behind a proxy, see the SSE streaming guide. On serverless platforms, also check the function execution limit; past it, the platform returns its own 5xx.

How 502 Shows Up in Common Clients

  • Claude Code: speaks the Anthropic protocol; set ANTHROPIC_BASE_URL to https://zivv.pro with no /v1. It generally retries 5xx on its own and prints retry notices in the terminal. If failures persist, test the endpoint with curl and check for a stale local proxy configured for Claude Code. Breaking big jobs into smaller tasks makes each failure much cheaper.
  • Codex: uses the OpenAI-compatible Responses API with base URL https://zivv.pro/v1. For persistent 502s, confirm which model provider configuration is active, then curl the same model.
  • Cursor, Cherry Studio, and other desktop clients: many show only "502" or "request failed." Check whether the app has its own proxy setting, then reproduce with curl; if curl works and the app does not, the problem is the app's network settings.
  • Your own application: the most common 502 comes from your own Nginx or gateway. Work through Fix 5 for timeouts, buffering, and backend health; your backend logs usually hold the real error.

Preventing Repeat 502s

  1. One retry policy: retry only 5xx, 529, and connection errors, with exponential backoff, jitter, and a cap; keep either the SDK's retries or your own, not both
  2. Log enough to locate the hop: status code, Content-Type, request ID, and duration on every failure
  3. Fallback models on critical paths: the models field or your own degradation logic, so one bad model does not take the feature down
  4. Timeouts that tighten inward: client, then your proxy, then the backend's model call, so the innermost layer reports a structured error first
  5. Watch the 5xx rate: it should sit near zero; a rising trend is your cue to act before users notice

If you are still juggling keys and retry logic for several providers, create a Zivv account and try a different setup: one key for models from multiple vendors, automatic channel failover when a single upstream breaks, no charge for requests that fail without returning content, and per-request model, status, and cost visible in the console and through /v1/generation.

FAQ

Does a GPT 502 error mean OpenAI is down?

Not necessarily. A 502 only says that some gateway in the path got no valid response from the hop behind it, and that could be your own proxy, a corporate gateway, a relay service, or the provider. Run curl -i: an HTML error page points at a proxy layer, while JSON with an error object comes from the API gateway. Check status.openai.com for incidents at the same time, then decide whether to wait, switch models, or fix your own configuration.

Am I charged for requests that fail with 502?

Failed requests that return no content generally do not incur token charges; on direct provider accounts, the provider's billing is authoritative. On Zivv, a request that fails without returning content is not billed, and failed attempts the gateway routed away from are recorded at zero cost. You can confirm with /v1/generation, using the request ID from the response headers, and check the request's total_cost.

What is the difference between 502 and 504?

A 502 means the gateway received an invalid response from the next hop or could not reach it at all; a 504 means the gateway waited for the next hop until it timed out. For 504, look at timeouts at every layer and at the task's duration, and stream long outputs. For 502, start by confirming that the service behind the gateway is up and healthy.

Why does /v1/models work while chat requests return 502?

Listing models involves no inference, while a chat request has to be forwarded to an upstream and wait for generation. A working model list proves your key, base URL, and network path are fine, so the problem is the target model's upstream, or a request large or long enough to hit some layer's timeout. Send the same request to a different model to tell the two apart.

I keep getting 502 after several retries. What now?

Stop increasing the retry rate and work through three checks in order: use curl -i to confirm which layer returned the 502; check the provider's status page or the model's 24-hour availability in the Model Hub; switch to another model or add fallback models. If the 502 is confirmed to come from Zivv, find the request in the console's usage logs and open a ticket with its request ID.