Pcornel
Browse topics
Options
Recent
Favorites
Web Infrastructure · Technical reference

HTTP Load Balancing

Direct answer

HTTP (layer 7) load balancing distributes requests across backend servers based on HTTP information, with health checks, persistence and header handling. nginx (upstream) and HAProxy are the common software implementations.

When to use this

Use it to scale web applications horizontally, remove failed or draining servers from service, and route by host, path or header to different backend pools.

First 30 seconds

1. Which backends are UP/DOWN/DRAIN?

2. Do health checks test the real application path?

3. Are errors from all backends or one?

4. Do sessions break when traffic moves (persistence/shared state)?

Operational verification

client → frontend/listener (TLS) → routing rules (host/path) → backend pool → algorithm + persistence → healthy server → response; health checks update membership

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
nginx open source (ngx_http_upstream_module) and HAProxy 3.x.
Applicability is projected only from persisted Topic profile and Command metadata.
At a glance

Operational reference

Fast context before you go deeper.

Platformnginx open source (ngx_http_upstream_module) and HAProxy 3.x.
Scope / prerequisiteUse it to scale web applications horizontally, remove failed or draining servers from service, and route by host, path …
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

3 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

Capture the concrete output, symptom, packet, log or counter before changing anything.

Step 1 Read-only Verification Verify boundary
# HAProxy: configuration check and live server state (runtime API on the stats socket)
haproxy -c -f /etc/haproxy/haproxy.cfg
echo "show stat" | socat stdio /run/haproxy/admin.sock | cut -d, -f1,2,18,19,37 | column -s, -t
#   pxname,svname,status,weight,check_status  -> e.g. web_back  web1  UP  1  L7OK
echo "show servers state" | socat stdio /run/haproxy/admin.sock

# nginx: configuration and upstream errors
nginx -t
grep -E 'upstream|no live upstreams' /var/log/nginx/error.log | tail

# Health endpoint on each backend directly
for b in 10.0.0.21 10.0.0.22; do curl -sS -o /dev/null -w "$b %{http_code}\n" http://$b:8080/healthz; done

In HAProxy's show stat, check_status such as L7OK, L7STS (wrong status code), L4TOUT (connect timeout) or L4CON (refused) tells you why a server is down. In nginx open source, no live upstreams means every server in the group is currently marked failed.

Step 2 Common mistakes Narrow the fault
  • Health checks that only test that a port is open.
  • Assuming open-source nginx actively health-checks upstreams.
  • Retrying POST requests automatically.
  • Trusting X-Forwarded-For from anyone.
  • Taking servers out of service abruptly instead of draining them.
Step 3 Troubleshooting Narrow the fault

503 from the balancer. No healthy backend: check health-check results, not just whether the service runs — a changed health path or Host header makes every check fail.

Uneven load. Round-robin with long-lived connections (WebSockets, HTTP/2) or very uneven request cost; use least connections. Persistence by source IP behind a NAT or CDN sends many users to one server.

Users logged out randomly. Sessions stored per server without persistence, or persistence lost when a server goes down. Centralise sessions.

Backends log only the balancer's IP. X-Forwarded-For/PROXY protocol not configured, or the backend does not use it (nginx real_ip, Apache mod_remoteip).

Duplicate orders after a backend failure. Retries of non-idempotent requests; restrict retries to idempotent methods.

Key points

Open-source nginx has only passive health checks (max_fails/fail_timeout); HAProxy has active checks. Retrying is safe only for idempotent requests. Drain a server before maintenance. Backends see the balancer's IP unless X-Forwarded-For or PROXY protocol is configured and trusted.

Key checks
  • HAProxy: echo "show stat" | socat stdio /run/haproxy/admin.sock | cut -d, -f1,2,18,19 — backend/server status.
  • HAProxy: haproxy -c -f /etc/haproxy/haproxy.cfg — config check.
  • nginx: nginx -t; error log 'upstream ... failed' / 'no live upstreams'.
  • curl -sS -o /dev/null -w "%{http_code}\n" http://<backend>:<port>/healthz — health endpoint directly.
ReferenceWhat it is2 sections · depth on demand

Direct Answer

An HTTP load balancer terminates the client connection, picks a healthy backend for each request (or connection) using an algorithm and optional persistence, and forwards the request. It removes servers that fail health checks and lets you drain servers before maintenance. Because it works at layer 7 it can route by hostname or path, add X-Forwarded-For, and retry failed idempotent requests on another server. nginx and HAProxy are the usual software choices; open-source nginx only has passive health checks, HAProxy has active ones.

Scope and canonical references

  • Single-backend proxying: Reverse Proxy.
  • Web servers commonly used as balancers: Nginx, Caddy.
  • Persistent connections to backends: HTTP/1.1.
  • WebSocket traffic through balancers: WebSockets.
  • Network-layer load sharing (ECMP, routing): Networking routing Topics.
ReferenceImportant terms & boundaries1 section · depth on demand

In depth

Layer 4 vs layer 7

L4 (TCP/UDP)L7 (HTTP)
Decision based onIP and portHost, path, headers, cookies
TLSPassed through (or terminated)Usually terminated
Sees requestsNo — balances connectionsYes — can balance each request
Adds headersNo (PROXY protocol instead)X-Forwarded-For, Forwarded
RetriesConnection levelRequest level (idempotent only)

Algorithms

nginxHAProxyBehaviour
(default) weighted round-robinbalance roundrobinRotate by weight
least_connbalance leastconnFewest active connections; good for long or uneven requests
ip_hash / hash $remote_addrbalance sourceSame client → same server
hash $request_uri consistentbalance uriSame URL → same server (cache locality)
—balance hdr(<name>)By header value

Health checks

  • Passive (nginx open source): a server is marked unavailable after max_fails failures within fail_timeout (defaults 1 and 10 s); what counts as a failure is defined by proxy_next_upstream. Active health_check is only in the commercial nginx.
  • Active (HAProxy): option httpchk with http-check send/expect and check inter 2s fall 3 rise 2 on server lines probes each server independently of client traffic.

Point health checks at an endpoint that exercises the application's critical dependencies lightly, not only a static file — but not so deeply that a shared database hiccup marks every server down at once.

Persistence

Applications that keep session state in local memory need stickiness: HAProxy cookie SERVERID insert indirect nocache or stick tables; nginx open source offers ip_hash/hash. Better: store sessions centrally (Redis, database) so any server can serve any request.

Draining and maintenance

HAProxy: set server <backend>/<server> state drain stops new sessions while existing ones finish; state maint takes it out. nginx: mark the server down and reload (with ip_hash this keeps the hash mapping stable).

Timeouts and retries

HAProxy requires timeout connect, timeout client and timeout server; WebSockets use timeout tunnel after the upgrade. nginx uses proxy_connect_timeout, proxy_read_timeout (default 60 s) and proxy_send_timeout. Retries (proxy_next_upstream, HAProxy retries and option redispatch) must not resend POST requests that may already have been processed.

Client IP

At L7 add X-Forwarded-For (option forwardfor in HAProxy; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for in nginx) or the standard Forwarded header (RFC 7239), plus X-Forwarded-Proto. At L4 use the PROXY protocol, which prepends the original addresses to the TCP stream — both sides must have it enabled. Backends must trust these headers only from the balancer's addresses.

Upstream connection reuse

nginx keepalive in the upstream block caches idle backend connections per worker (enabled by default with 32 connections since 1.29.7; older versions need it set together with proxy_http_version 1.1 and an empty Connection header).

Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terminology layer

Terms & aliases

Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.

Aliases that resolve here
http load balancinglayer 7 load balancingl7 load balancerhaproxynginx upstreamhealth checksticky sessionsx-forwarded-for
Confirmation

Confirm action

Continue?