Qaynaq LABS · TOOLS

HTTP · 5xx Server Error

502 Bad Gateway

Gateway or proxy received an invalid response from upstream server.

When you see this status

  • Proxy forwards request to unhealthy backend
  • Upstream service crashes mid-response
  • Network partition between proxy and backend
  • Backend returns malformed HTTP response
  • Timeout occurs waiting for backend response

Common causes

  • Backend server crashes or overload
  • Network connectivity issues
  • Misconfigured proxy/gateway
  • Backend sends invalid HTTP headers
  • Upstream service returns non-HTTP response

How to debug it

  1. Check backend server health/availability
  2. Inspect proxy/gateway logs for errors
  3. Verify network connectivity to backend
  4. Test backend endpoint directly
  5. Monitor backend response times

Return this code in your framework

Express (Node.js)
app.get('/proxy', (req, res) => { res.status(502).send('Bad Gateway'); });
FastAPI (Python)
from fastapi import FastAPI; app = FastAPI(); @app.get('/') async def root(): return Response(status_code=502);
NestJS
import { Controller, Get, HttpCode } from '@nestjs/common'; @Controller() export class AppController { @Get() @HttpCode(502) getBadGateway() { return 'Bad Gateway'; } }
Go (net/http)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway); });

About HTTP 502

HTTP status code 502 Bad Gateway is part of the 5xx Server Error family. Gateway or proxy received an invalid response from upstream server. Understanding it is essential for backend engineers, API designers, and anyone debugging integrations between services.

The Qaynaq Labs HTTP Status Code Explainer covers all standard codes with practical guidance: what triggers them, how to debug them in production, and exactly how to return them from common frameworks. Each code page is hand-curated and verified.

Frequently asked

Is 502 the same as 503?

No. 503 indicates the server is temporarily unavailable, while 502 means the server returned an invalid response.

Can clients retry on 502?

Yes, but only if the request is idempotent. Retries may succeed if the backend recovers.

Does 502 always mean the backend is down?

Not always. It can also indicate network issues or malformed responses from the backend.

How to differentiate 502 from 504?

504 is a timeout waiting for the backend, while 502 is an invalid response from the backend.