# HTTP 502 `bad_gateway` — API Store Hub

> VI: HTTP 502 (`bad_gateway`) xảy ra khi kênh upstream của nhà cung cấp AI đóng kết nối đột ngột hoặc bảo trì ngắn hạn trong lúc xử lý yêu cầu.
> EN: HTTP 502 (`bad_gateway`) occurs when an upstream model provider drops a connection or experiences brief maintenance during request execution.

- Canonical VI: https://apistorehub.com/vi/loi-api/502-upstream-provider-failover
- Canonical EN: https://apistorehub.com/en/loi-api/502-upstream-provider-failover
- Retry Policy: Retry 1-2 times on the primary model, then fail over across model families on the same gateway.

## Root Causes
- An upstream model vendor experiencing a brief outage or mid-flight connection reset.
- Client code failing immediately on 502/503 without transient retries.
- Pinning 100% of production traffic to one single model family with no fallback.

## Step-by-Step Resolution
1. Treat HTTP 502 and 503 as transient: retry twice with 1s -> 2.5s jittered backoff.
2. Define a cross-family fallback chain (`claude-sonnet-5-5` -> `gpt-6.2-sol` -> `deepseek-v4-pro`) on one API key.
3. Use a lightweight client circuit breaker to bypass degraded models for 120 seconds.
4. Monitor live lane reliability on `/status` and `/ranking`.

## Diagnostic cURL
```bash
curl -i https://apistorehub.com/v1/chat/completions \
  -H "Authorization: Bearer sk-ash-your_key" \
  -H "Content-Type: application/json" \
  -d '{"model":"gpt-6.2-sol","messages":[{"role":"user","content":"failover check"}]}'
```

## Production Fix (TypeScript)
```
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://apistorehub.com/v1", apiKey: process.env.API_KEY });
const CHAIN = ["claude-sonnet-5-5", "gpt-6.2-sol", "deepseek-v4-pro"];

export async function completeWithFailover(prompt: string): Promise<string> {
  let lastErr: unknown;
  for (const model of CHAIN) {
    try {
      const res = await client.chat.completions.create({
        model,
        messages: [{ role: "user", content: prompt }],
      });
      return res.choices[0]?.message?.content || "";
    } catch (err: any) {
      lastErr = err;
      if (![502, 503, 504, 529, 429].includes(err?.status)) throw err;
    }
  }
  throw lastErr;
}
```

## FAQ
- **Why fail over across different model families?**: Vendor-wide outages affect all routes within that vendor; cross-family failover keeps app availability above 99.95%.
- **Does cross-family failover require separate keys or wallets on API Store Hub?**: No. One API key and one ST balance cover every model family.
- **Are HTTP 502 failures billed?**: No. Only completed valid responses incur ST charges.
