- A 502 bad gateway always comes from a gateway or proxy. RFC 9110 defines it that way, and as of November 23, 2026 the OpenAI, Anthropic, and Bedrock Converse error references list no 502 from the model servers themselves.
- On an LLM call, three hops can send a 502: your load balancer or reverse proxy, an AI gateway, and the provider's edge. The body format, the provider request ID, and the load balancer's ELB versus Target metrics tell them apart.
- The most common self-inflicted 502 is a keep-alive race: Node.js closes idle connections after 5 seconds by default, and an AWS Application Load Balancer keeps them for 60.
- Retry a 502 from exactly one layer, before any bytes reach the client. Stacked SDK and gateway retries can turn one user request into 36 upstream attempts.
- Fallbacks to a second provider handle what retries cannot. In Bifrost, an open-source AI gateway, each fallback gets its own retry budget, and every attempt is logged with its status code.
A 502 bad gateway on an LLM API call means a proxy somewhere between your code and the model received a response it could not use. The model did not send it. Fixing it starts with finding which hop did, then deciding whether the failure is in your infrastructure or the provider's, and only then choosing retries, timeouts, and fallbacks that keep a transient one from reaching users. This guide walks each hop of a request to OpenAI, Anthropic, or Amazon Bedrock, and uses Bifrost, an open-source AI gateway, as the worked example for gateway behavior. It ends with a triage checklist.
#What a 502 bad gateway means on an LLM request
A 502 is a status code that only a gateway or proxy sends. RFC 9110 defines it as a server that, "while acting as a gateway or proxy, received an invalid response" from the server behind it. In practice, invalid covers a reset connection, a connection closed mid-request, malformed headers, and a failed TLS handshake.
That definition narrows the search. The model servers report their own failures with other codes, as of November 23, 2026:
| Provider | Server-side codes in its error reference | 502 listed |
|---|---|---|
| OpenAI | 500 server error, 503 model overloaded | No |
| Anthropic | 500 api_error, 504 timeout_error, 529 overloaded_error | No |
| Amazon Bedrock (Converse) | 500 internal, 503 unavailable, 424 model error, 429 not ready or throttled, 408 model timeout | No |
Sources: OpenAI error codes, Claude API errors, and the Converse API reference.
So a 502 is a question about which proxy produced it. Its sibling, the 504, also comes from a proxy, but it means no response arrived in time rather than an invalid one. On LLM traffic the two have different causes, so read the exact code before reading anything else.
#Where a 502 comes from on an LLM call
A typical production request crosses three proxies before it reaches a model: your load balancer or reverse proxy, an AI gateway if you run one, and the provider's edge. Each one turns a different upstream failure into the same three digits, and each leaves a different mark on the response.
Your load balancer or reverse proxy is the hop you control most directly. An AWS Application Load Balancer generates a 502 when its target resets the connection, closes it while a request is outstanding, returns malformed headers or a response header over 32 KB, fails the TLS handshake, or is a Lambda function that errors, times out, or returns a body over 1 MB.
An AI gateway is a proxy too. It can pass a provider's 5xx through after its retries run out, or generate a 502 of its own. Bifrost, for example, returns 502 upstream_credentials_exhausted when every configured provider key fails for an account-level reason, covered below.
The provider's edge is the last hop. Providers run edge layers in front of their API servers. Anthropic's errors page says that on the first-party API, Cloudflare returns its 413 error "before the request reaches the API servers." A 502 from that layer means the edge could not get a valid answer from the servers behind it, which is a provider-side failure.
#How to find which hop sent the 502
Read the response body and headers before opening any dashboard. A provider's own errors are structured JSON with a request ID, and a proxy's errors usually are not. Then split your load balancer's metrics, which separate errors it generated from errors it passed through.
- Check the body format. Anthropic's API "always returns errors as JSON" with a top-level
errorobject holding atypeand amessage. An HTML page or an empty body came from a proxy. - Check for a provider request ID. Every Anthropic API response carries a
request-idheader. A 502 without one most likely never got a response from the provider's API servers. - Split the load balancer metrics. An ALB counts errors it generates in
HTTPCode_ELB_5XX_Countand errors passed through from targets inHTTPCode_Target_5XX_Count. A rise in the first means the ALB could not talk to your service. A rise in the second means your service, or something behind it, returned the 5xx. - Check your gateway's log. A gateway that logs each attempt shows whether the provider returned the 502, whether it was retried, and which provider finally served the request.
- Check the provider's status page. OpenAI's guide points to its status page for 500 and 503 errors. A 502 that lines up with an incident is provider-side.
- Correlate with request shape. If failures cluster on long prompts, large
max_tokens, or non-streaming calls, suspect a timeout or connection-lifetime mismatch on your side before blaming the provider.
| What you see | Hop that likely sent it | Whose side |
|---|---|---|
HTML body, HTTPCode_ELB_5XX_Count rising | Your load balancer | Yours |
Gateway error code such as upstream_credentials_exhausted | Your AI gateway | Yours (keys or quota) |
| Provider JSON error passed through the gateway after retries | Provider, relayed by the gateway | Provider's |
| Non-JSON body, no provider request ID, status page incident | Provider edge | Provider's |
#Your-side causes of 502 errors and how to fix them
The 502s you can fix on your side mostly trace back to connection lifetimes. LLM calls hold connections open far longer than a typical web request, and defaults tuned for short page loads produce resets that the load balancer reports as a 502.
#Keep-alive shorter than the load balancer idle timeout
This is the most common one. AWS lists the cause as a target that closed the connection "while the load balancer had an outstanding request," and tells you to check "whether the keep-alive duration of the target is shorter than the idle timeout value of the load balancer."
The defaults collide. An ALB keeps idle connections for 60 seconds by default. A Node.js HTTP server closes them after 5 seconds: server.keepAliveTimeout is 5000 ms on Node.js v26.12.1, measured for this article. Between second 5 and second 60, the ALB can send a request down a socket the app has just closed, and the client gets a 502.
Set the app server's keep-alive longer than the ALB idle timeout, for example 65 seconds against 60. In Node.js, also raise headersTimeout above keepAliveTimeout. Then the load balancer, not your server, closes idle connections.
#Lambda limits behind an ALB
If your LLM proxy runs on AWS Lambda behind an ALB, three Lambda conditions produce a 502: a response body over 1 MB, a function that hits its configured timeout, and a function that errors or is throttled. Long generations hit the timeout first. Move long LLM routes to a long-running service, or put them behind a path that supports streaming.
#Deployments and TLS
Two more ALB causes show up during routine changes. A target deregistered during a deploy gets a 502 for any request still in flight once the deregistration delay elapses, so set that delay longer than your longest generation. A TLS handshake error between the ALB and the target, often after a certificate or cipher change on the target, also returns a 502.
#Long silent calls are usually 504s
A non-streaming completion with a large max_tokens can stay silent for minutes. nginx's proxy_read_timeout defaults to 60 seconds between two reads, and an ALB closes a target connection that sends nothing for its 60-second idle timeout. Both report that as a 504 Gateway Timeout, not a 502. The SDKs wait far longer, so the proxy cuts the call first.
The fix is the same either way. Stream the response so tokens arrive well inside every idle timeout, or raise the proxy timeouts for the LLM route only. Anthropic recommends streaming or the Message Batches API for long requests, "especially those over 10 minutes," and warns that some networks drop idle connections after a variable period. Streaming also gives you time to first token as an early health signal.
#Provider-side 502s: what you can and cannot fix
A 502 from the provider's edge, or a provider 5xx relayed by your gateway, is outside your control. You cannot fix it, but you can stop it from reaching users. Confirm it on the provider's status page, let a bounded retry absorb a blip, and fail over to a second provider when the failure lasts longer than the retry budget.
Provider-side failures cluster in time. One 502 at 3 a.m. is noise. A minute of them across many requests is an incident, and retrying the same provider for that minute adds load to a struggling service while your users wait. That is the point where a fallback earns its configuration.
Provider-side 502s also differ by region and deployment. Bedrock, Azure OpenAI, and Vertex AI each serve models from regional endpoints, so a fallback to the same model in another region or on another cloud can succeed while the primary is failing. For how to run two providers at once rather than one in reserve, see the active-active vs active-passive comparison.
#Which 502 retries are safe
Retry a 502 with exponential backoff and a small cap, only before any response bytes have reached your client, and only from one layer. Three properties of LLM calls make blind retries risky: the requests are POSTs, streams cannot be replayed once they start, and every layer already retries by default.
#LLM calls are POST requests
RFC 9110 counts only "PUT, DELETE, and safe request methods" as idempotent, and says a client "SHOULD NOT automatically retry a request with a non-idempotent method" unless it knows the request is safe to repeat. nginx follows that rule: without non_idempotent in proxy_next_upstream, it does not pass a POST to the next upstream once the request has been sent.
For a stateless chat turn, a retry costs another generation and nothing else. When the call runs tool calls with side effects, such as sending an email or writing a record, retry the model call but make the tool execution idempotent, or check for completed side effects before repeating them.
#Streams cannot be retried once they start
nginx's docs state the limit plainly: passing a request to the next server "is only possible if nothing has been sent to a client yet." Once the first token reaches the client, no proxy can retry transparently. Anthropic adds that on a streaming response "an error can occur after the API returns a 200 response," and those errors arrive as events in the stream instead of an HTTP status.
Handle mid-stream failures in the client. Either restart the request and discard the partial output, or keep what arrived and offer the user a retry.
#Stacked retries multiply
Every layer retries by default. The OpenAI Python SDK retries connection errors, 408, 409, 429, and 5xx errors "2 times by default," and the Anthropic SDK retries transient failures twice with exponential backoff. A gateway with retries and fallbacks multiplies that.
Pick one layer to own retries, usually the one closest to the provider, because it sees each provider's errors and can fall back. Set the SDK's max_retries to 0 when a gateway handles retries, or leave the SDK at its default and configure the gateway for fallbacks only. Write the total attempt count down, and check it against your user-facing timeout.
#Timeouts and fallbacks that absorb a 502
Order timeouts so that each layer waits longer than the layer inside it, and add a fallback for failures retries cannot fix. The innermost layer has the most context about what went wrong, so it should run out of time first and still have time to retry or fall back before an outer layer cuts the connection.
A workable order, from the outside in:
- Client timeout, longest. An ALB returns a 460 when the client gives up before the load balancer.
- Load balancer idle timeout, shorter than the client's, and long enough for your slowest non-streaming call or streaming in use.
- App server keep-alive, longer than the load balancer idle timeout, as above.
- Gateway or SDK per-request timeout, shorter than the outer layers, so a retry or fallback can still finish inside them.
Retries on the same provider fix a blip. A fallback sends the request to a different provider or model, which keeps users served through a regional outage. Before relying on one, inject a 502 into the primary and confirm the fallback actually serves traffic; the failover testing guide covers how to run those drills.
#Handling 502s in an AI gateway: Bifrost
An AI gateway is a natural owner for retries and fallbacks, because it sees every provider and every attempt. Bifrost is an AI gateway with an Apache 2.0 open-source core that puts 10,000+ models across 25+ providers behind one API, and its retry and fallback behavior is documented down to the status code. As of November 23, 2026:
- Which errors retry. Bifrost treats
500,502,503,504, and529as transient and retries them on the same key with exponential backoff. It rotates to another key on401,402,403, and429, and does not retry validation errors such as400or422, timeouts, or cancelled requests. - Retries are off until you set them.
max_retriesdefaults to 0. Backoff defaults to 500 ms initial and 5,000 ms maximum, with jitter of 0.8 to 1.2. - Fallbacks run in order. A request carries an ordered
fallbackslist ofprovider/modelstrings, and the first success wins. Each provider in the chain gets its own fullmax_retriesbudget, so a primary and two fallbacks atmax_retries: 3can make 12 attempts. - Timeouts fall back, deadlines do not. A provider timeout is recorded as a
504withfail_reasonrequest_timed_outand goes straight to the next fallback without a same-provider retry. An expired request deadline ends the request with no fallback. - The error you get back. If every fallback fails, Bifrost returns the primary provider's error and headers, not the last fallback's.
Bifrost's own documented 502 is upstream_credentials_exhausted. It means every configured key failed for an account-level reason, such as a revoked credential or an exhausted quota, so the caller's gateway key is fine and the provider credentials are not. Retrying will not help. Rotate or top up the provider keys.
Per-provider retries and timeouts live in network_config in config.json. This excerpt follows the documented example and was not run for this article:
"network_config": {
"default_request_timeout_in_seconds": 120,
"max_retries": 3,
"retry_backoff_initial": 500,
"retry_backoff_max": 5000,
"stream_idle_timeout_in_seconds": 120
}The fallback chain goes on the request. Bifrost's own chat endpoint takes an OpenAI-style body plus a fallbacks list, and existing SDK clients can reach the gateway by changing only their base URL through the drop-in replacement routes:
{
"model": "openai/gpt-5.4-mini",
"fallbacks": ["anthropic/claude-sonnet-5", "anthropic/claude-haiku-5-5"],
"messages": [{ "role": "user", "content": "Summarize this ticket." }]
}Check the provider and model IDs against your own provider setup before you copy them. A response served by a fallback carries "is_fallback": true in extra_fields.routing_info, with the primary provider and model beside it.
That log is what makes 502s diagnosable. Bifrost's request logs record number_of_retries and an attempt_trail with each attempt's status_code and fail_reason, and link fallback attempts to the original request through parent_request_id. Filter by status and provider, and a provider that fails often shows up in the logs before it causes an outage.
The same gateway applies governance and security to that traffic: virtual keys, budgets, guardrails, and audit logs. Bifrost Edge extends those controls to AI apps and coding agents on employee machines, with enforcement on each device, so traffic from tools that never call your servers passes through the same gateway and its logs. For a step-by-step setup of a gateway in front of your app, see the LLM gateway tutorial, and for how gateways compare, the best LLM gateways roundup.
#A 502 triage checklist for LLM traffic
Work through these in order the next time a 502 shows up. The first two steps find the hop, the middle steps fix your side, and the last steps make sure provider-side 502s never reach users.
- Confirm the code. A 504 is a timeout and a 502 is an invalid response; they have different fixes.
- Find the hop. Check the body format, the provider request ID, the gateway's attempt log, and the ALB's ELB versus Target 5XX metrics.
- If the ALB generated it, compare your app's keep-alive with the ALB idle timeout, then check Lambda response size and timeout, deregistration delay, and target TLS.
- If failures cluster on long or non-streaming calls, stream the route or raise proxy timeouts for that route only.
- If your gateway generated it, read its error code. A credentials error needs new keys, not retries.
- If it came from the provider, check the status page, confirm exactly one layer retries with backoff, and confirm a fallback provider is configured and tested.
- Count the attempts. Multiply SDK attempts by gateway attempts, and keep the product inside your user-facing timeout.
- Watch the fallbacks. Alert on the share of responses with
is_fallback: true, so a degrading primary is visible while users still see successes.
#Questions
What causes a 502 Bad Gateway error on an API call?
A proxy between the client and the server received a response it could not use. On an LLM call that proxy is your load balancer or reverse proxy, an AI gateway, or the provider's edge. Common causes are a backend that reset or closed the connection mid-request, a keep-alive timeout shorter than the load balancer's idle timeout, malformed response headers, a failed TLS handshake, and a provider incident.
Is a 502 Bad Gateway my fault?
Sometimes. A 502 your own load balancer generated is usually a configuration problem on your side, such as an app server that closes idle connections before the load balancer does. A 502 from the provider's edge, especially one that lines up with an incident on the status page, is not something you can fix. The response body and your load balancer's metrics tell the two apart.
How long does a 502 Bad Gateway last?
A provider-side 502 is usually transient and clears within seconds to minutes, which is why retries with exponential backoff absorb most of them. During a real incident it can last as long as the incident, and only a fallback to another provider keeps requests succeeding. A 502 caused by your own configuration lasts until you change the configuration.
Should you retry a 502 error?
Yes, with exponential backoff, a small cap, and only from one layer. LLM calls are POST requests, so a retry runs the generation again, which is fine for a stateless chat turn but not for a call that triggers side effects. A stream that has already sent tokens to the client cannot be retried transparently, and a 502 caused by bad credentials will fail on every retry.
What is the difference between a 502 and a 504?
Both come from a gateway or proxy. A 502 means the proxy got an invalid response from the server behind it: a reset, a closed connection, or broken headers. A 504 means it got no response in time. On LLM traffic, a long non-streaming generation that stays silent past a 60-second proxy timeout usually produces a 504, while a keep-alive race usually produces a 502.
Does the OpenAI API return 502 Bad Gateway errors?
OpenAI's error code guide lists 500 for server errors and 503 for an overloaded model, and does not list 502 as of November 23, 2026. A 502 on an OpenAI call therefore comes from a proxy: your own load balancer or gateway, or an edge layer in front of the API. The OpenAI Python SDK retries 5xx errors twice by default, so a 502 your code sees has usually already been retried.