# 502 Bad Gateway

> https://http-status.org/docs/502

**Family:** 5xx Server Error

## Rationale

The server, while acting as a gateway or proxy, received an invalid response from the upstream server.

## In Plain Terms

I'm a middleman server, and the server I was trying to talk to gave me a bad or broken response.

## Description

The HTTP 502 Bad Gateway status code indicates that the server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.

## Server Perspective

### Usage
- Return 502 when the upstream response is malformed, truncated, protocol-invalid, or otherwise unusable
- Use it only when this server is in a gateway, reverse-proxy, or similar intermediary role
- Upstream server returns invalid response
- Proxy can't parse upstream response
- Load balancer receives malformed response
- API gateway gets bad response from backend

### Implementation
- Record which upstream failed, what validation failed, and the correlation or trace ID for the downstream request
- Return a sanitized error payload rather than forwarding broken upstream bytes to the client

### Common Headers
- No status-specific header is required; include request or trace metadata when it helps incident debugging

### Body
- A body is optional but usually helpful; explain that an upstream dependency returned an invalid response without leaking internal topology or secrets

### Pitfalls
- Do not use 502 when the upstream simply took too long; that is 504 Gateway Timeout
- Do not use 502 for generic origin-server bugs when no intermediary role is involved
- Do not return 502 when the upstream sends a valid HTTP error response; pass that response through to the client to keep the failure reason transparent.
- Your own application failed before contacting an upstream service (use 500 Internal Server Error)
- You know the service itself is temporarily unavailable due to maintenance or overload (use 503 Service Unavailable)
- Request timeout (use 504 Gateway Timeout)
- Direct server errors (use 500 Internal Server Error)

## Client Perspective

### Pitfalls
- Do not assume the request itself is invalid
- Do not treat 502 as proof that the origin service is completely down

## Examples

### Invalid upstream response

Backend API returned malformed JSON that proxy couldn't parse

**Request:**
```
GET https://api.example.test/api/data
```

**Response:**
```
502 Bad Gateway
Content-Type: application/json

{
  "error": "bad_gateway"
}
```

## Related Codes

- [500 Internal Server Error](/docs/500.md)
- [503 Service Unavailable](/docs/503.md)
- [504 Gateway Timeout](/docs/504.md)

