# 502 Bad Gateway: Upstream timeout

- **ID:** `api/http-502-bad-gateway-upstream-timeout`
- **Domain:** api
- **Category:** network_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

The proxy or gateway server (e.g., Nginx, AWS ALB) did not receive a timely response from the upstream server, causing a timeout.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| Nginx 1.24 | active | — | — |
| AWS ALB | active | — | — |
| HAProxy 2.6 | active | — | — |
| Kong 3.4 | active | — | — |
| Istio 1.18 | active | — | — |

## Workarounds

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.** (85% success)
   ```
   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.** (80% success)
   ```
   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)** (75% success)
   ```
   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)
   ```

## Dead Ends

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