# 504 网关超时：上游连接池耗尽

- **ID:** `api/http-504-gateway-timeout-upstream-connection-pool-exhausted`
- **领域:** api
- **类别:** resource_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

API 网关到上游服务的连接池已完全占用，导致新请求排队并最终超时，通常是由于上游响应缓慢或连接池大小不足。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| Nginx 1.26+ | active | — | — |
| Envoy 1.30+ | active | — | — |
| AWS ALB (2024) | active | — | — |

## 解决方案

1. ```
   增加上游连接池大小。Nginx 示例：`upstream backend { server 10.0.1.5:8080; keepalive 100; }`（从默认的 32 增加）。
   ```
2. ```
   通过添加缓存、减少数据库查询或扩展上游实例来优化上游响应时间。使用 `nginx_upstream_check_module` 等工具监控上游延迟。
   ```
3. ```
   在网关处实现按客户端 IP 的连接池限制或速率限制以防止滥用。Nginx 示例：`limit_conn_zone $binary_remote_addr zone=addr:10m; limit_conn addr 10;`。
   ```

## 无效尝试

- **** — The pool will quickly exhaust again if the upstream is slow or the pool size is too small; it's a temporary fix. (90% 失败率)
- **** — Timeouts only delay the error; the pool remains exhausted and requests still queue. (80% 失败率)
- **** — The error is about connection pool capacity, not network connectivity. (70% 失败率)
