502

Bad Gateway

5xx Server Error

ELI5

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

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
  • Upstream server returns invalid response
  • Proxy can't parse upstream response
  • Load balancer receives malformed response
  • API gateway gets bad response from backend

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
  • 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)

Examples

Invalid upstream response

Request:GET https://api.example.test/api/data
Response:502 Bad Gateway # Headers Content-Type: application/json # Body { "error": "bad_gateway" }

Backend API returned malformed JSON that proxy couldn't parse

References

Related Status Codes