502

Bad Gateway

5xx Server Error

Back to list

Server perspective

Use 502 when acting as a gateway or proxy and the upstream server sends an invalid or unusable response.

When to use

  • 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

How to respond

  • 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

Headers to consider

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

Response body

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

Server-side 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

Examples

Gateway rejects malformed upstream headers

Request:GET /api/report through an API gateway
Response:502 Bad Gateway with error: upstream_invalid_response

The gateway received bytes it could not treat as a valid upstream HTTP response and shields the client from that broken payload.

References

Related 5xx Server Error Codes