Skip to content

Load Balancer 502 Bad Gateway Fix

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Load Balancer 502 Bad Gateway Fix. We cover key concepts, practical examples, and best practices.

A 502 Bad Gateway error from a load balancer means the load balancer received an invalid response from an upstream server. This happens when backend servers are down, overloaded, or return malformed responses that the load balancer cannot forward.

The Wrong Way

import requests

# Retry without checking backend health
for i in range(3):
    try:
        r = requests.get("https://app.example.com", timeout=5)
        print(f"Status: {r.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"Attempt {i+1} failed: {e}")

Output:

Attempt 1 failed: 502 Server Error: Bad Gateway
Attempt 2 failed: 502 Server Error: Bad Gateway
Attempt 3 failed: 502 Server Error: Bad Gateway

The Right Way

Check backend health and implement proper error handling:

import requests

def check_backend_health(backend_url):
    try:
        r = requests.get(f"{backend_url}/health", timeout=5)
        if r.status_code == 200:
            print(f"Backend healthy: {r.json()}")
            return True
        print(f"Backend unhealthy: {r.status_code}")
        return False
    except requests.exceptions.RequestException as e:
        print(f"Backend unreachable: {e}")
        return False

def fetch_with_fallback(url, backends):
    for backend in backends:
        if check_backend_health(backend):
            try:
                response = requests.get(
                    url.replace("app.example.com", backend),
                    timeout=10
                )
                return response
            except requests.exceptions.RequestException:
                continue
    raise Exception("All backends failed")

backends = ["http://backend1:8080", "http://backend2:8080"]
result = fetch_with_fallback("https://app.example.com/api", backends)

Step-by-Step Fix

1. Check backend server health

# Test each backend directly
curl -I http://backend1:8080/health
curl -I http://backend2:8080/health

# Check response time
curl -w "%{http_code} %{time_total}s\n" -o /dev/null -s http://backend1:8080

2. Check load balancer configuration

# HAProxy
haproxy -f /etc/haproxy/haproxy.cfg -c

# Nginx
nginx -t

# Check status page
curl http://load-balancer:8080/stats

3. Increase backend timeout

# Nginx reverse proxy
location / {
    proxy_pass http://backend;
    proxy_connect_timeout 30s;
    proxy_read_timeout 30s;
    proxy_send_timeout 30s;
}

4. Check backend logs

# Application logs
tail -f /var/log/app/error.log

# Web server logs
tail -f /var/log/nginx/error.log

5. Implement health checks

from flask import Flask, jsonify

app = Flask(__name__)

@app.route("/health")
def health():
    # Check database connectivity
    # Check disk space
    # Check memory
    return jsonify({"status": "healthy"}), 200

Prevention Tips

  • Configure health checks with appropriate intervals and thresholds.
  • Set reasonable timeout values for backend connections.
  • Monitor backend response times and error rates.
  • Use circuit breakers to stop sending requests to failing backends.
  • Implement graceful degradation when backends are unhealthy.

Common Mistakes with balancer 502

  1. Using return to exit a function early instead of wrapping a pure value in the monad
  2. Mixing let bindings with <- bindings in do notation, producing type errors
  3. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors

These mistakes appear frequently in real-world LOAD code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What is the difference between 502 and 503?

502 Bad Gateway means the upstream server returned an invalid response. 503 Service Unavailable means the server is temporarily unable to handle the request (overloaded or down).

How do I find which backend caused the 502?

Check the load balancer logs. HAProxy logs the backend server IP. Nginx logs the upstream address. Each load balancer has a status page showing backend health.

Can a slow backend cause 502 errors?

Yes. If a backend responds too slowly, the load balancer's proxy_read_timeout fires and returns a 502. Increase the timeout or optimize the backend's response time.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro