# 502 坏网关：上游超时

- **ID:** `api/http-502-bad-gateway-upstream-timeout`
- **领域:** api
- **类别:** network_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

代理或网关服务器（例如 Nginx、AWS ALB）未及时收到上游服务器的响应，导致超时。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Nginx 1.24 | active | — | — |
| AWS ALB | active | — | — |
| HAProxy 2.6 | active | — | — |
| Kong 3.4 | active | — | — |
| Istio 1.18 | active | — | — |

## 解决方案

1. ```
   Increase the proxy timeout value. For Nginx, add 'proxy_read_timeout 120s;' in the location block. For AWS ALB, increase the idle timeout setting in the target group to 120 seconds.
   ```
2. ```
   Optimize the upstream server's response time by adding database indexes, caching, or scaling horizontally. Use a CDN or caching layer for static responses.
   ```
3. ```
   Implement a retry mechanism with exponential backoff. Example in Python: for i in range(3): try: response = requests.get(url, timeout=30); break except requests.exceptions.Timeout: time.sleep(2**i)
   ```

## 无效尝试

- **** — The timeout is on the proxy side, not the client. The proxy's timeout configuration must be adjusted. (70% 失败率)
- **** — The upstream server may be slow due to load or inefficient queries, not a crash. (60% 失败率)
- **** — The upstream server is still under load; immediate retries will likely timeout again. (90% 失败率)
