# 504 网关超时：上游响应超时

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

## 根因

API 网关或反向代理（如 Nginx、AWS API Gateway）在等待上游服务响应时超时，通常由于处理缓慢或网络问题。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Nginx 1.25.0 | active | — | — |
| AWS API Gateway (2024) | active | — | — |
| Kong 3.6.0 | active | — | — |
| HAProxy 2.9.0 | active | — | — |

## 解决方案

1. ```
   Increase the upstream timeout in the gateway configuration. For Nginx, add to the location block: `proxy_read_timeout 60s; proxy_connect_timeout 30s;`. Then reload: `nginx -s reload`.
   ```
2. ```
   Optimize the upstream service's response time by adding caching, database query optimization, or asynchronous processing. For example, use Redis caching for frequent queries.
   ```
3. ```
   Implement a retry mechanism with exponential backoff in the client, but ensure idempotency. Example in Python: `requests.get(url, timeout=10); time.sleep(2**attempt)`.
   ```

## 无效尝试

- **** — The timeout occurs at the gateway, not the client; client-side changes are irrelevant. (90% 失败率)
- **** — Restarting resets the service but does not address underlying performance bottlenecks like slow queries or resource leaks. (70% 失败率)
- **** — Removing timeouts allows slow requests to accumulate, potentially crashing the service. (80% 失败率)
