Skip to content

Nginx HTTP load balancing — upstream blocks, methods, and what to watch

How to spread HTTP traffic across multiple backends with Nginx upstream blocks — round_robin, least_conn, IP hash, and the keepalive setting most configs forget.

When the application stops fitting on one VM, you put two or three behind a load balancer and stop worrying about single-host CPU. Nginx is a perfectly serviceable HTTP load balancer for tens of thousands of requests per second per VM — the configuration is short, but the few non-obvious settings (keepalive, fail_timeout, the difference between methods) decide whether failover is smooth or visible to users.

How to verify

Look at the upstream block and what is currently in rotation:

sudo nginx -T | sed -n '/upstream /,/}/p'
sudo nginx -T | grep -E 'proxy_pass|server '
for i in 1 2 3 4; do curl -s http://your-domain/health; echo; done
ss -ant state established '( sport = :443 )' | wc -l

If your /health endpoint includes the hostname or instance ID, you can see distribution in real time. If three of four requests land on the same backend, the method may not be what you think.

What’s happening

An Nginx upstream block names a pool of backends and a balancing method. The default method is round-robin — request one to backend A, request two to backend B, request three to backend C. least_conn picks the backend with the fewest active connections, which is closer to what you want when request times vary widely. ip_hash makes a given client IP always land on the same backend, which fixes session affinity if your app does not centralise sessions — at the cost of unbalanced distribution when one IP sends most of the traffic.

The catch is that Nginx-to-upstream connections are short-lived by default — Nginx opens a new TCP connection for every upstream request. The keepalive setting inside the upstream block keeps a pool of warm connections open, which on a hot path turns a 30 ms request into a 5 ms request.

The procedure

  1. Define the upstream pool:
    upstream app_backends {
        least_conn;
    
        server 10.0.1.11:3000 max_fails=3 fail_timeout=30s;
        server 10.0.1.12:3000 max_fails=3 fail_timeout=30s;
        server 10.0.1.13:3000 max_fails=3 fail_timeout=30s backup;
    
        keepalive 32;
        keepalive_timeout 60s;
        keepalive_requests 1000;
    }
    backup means this server only takes traffic when all primaries are down.
  2. Point a server block at it:
    server {
        listen 443 ssl http2;
        server_name app.example.com;
        # ssl_certificate ...
    
        location / {
            proxy_pass         http://app_backends;
            proxy_http_version 1.1;
            proxy_set_header   Connection "";          # required for keepalive to upstream
            proxy_set_header   Host $host;
            proxy_set_header   X-Real-IP $remote_addr;
            proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header   X-Forwarded-Proto $scheme;
        }
    }
    The empty Connection header is what enables HTTP/1.1 keepalive to the upstream. Without it, the keepalive directive has no effect.
  3. Choose the method explicitly. We default to least_conn for app servers and only use ip_hash when forced by a non-sticky app. hash $arg_user_id consistent is the option to reach for if you need a stable mapping by a custom key.
  4. Weight unequal backends:
    server 10.0.1.11:3000 weight=2;
    server 10.0.1.12:3000 weight=1;
    Backend 11 gets twice the share of traffic 12 does. Use this only when the boxes are genuinely different sizes — uneven weights make capacity planning harder.
  5. Add a health check route on every backend (/healthz) and use it for an active probe. The open-source Nginx only does passive failure detection (count failures, mark down for fail_timeout); for active probes see Nginx upstream health checks.
  6. Validate with sudo nginx -t && sudo systemctl reload nginx. Confirm distribution with the curl loop above.
  7. Drain a backend before a deploy: edit the upstream block, mark the server down, reload. Nginx routes around it without waiting for failures.

Common pitfalls

  • Forgetting proxy_set_header Connection ""; — keepalive 32 is then silently a no-op and every request opens a new socket to the upstream.
  • Using ip_hash behind a CDN: every request appears to come from a small set of CDN IPs, so all traffic lands on a couple of backends.
  • max_fails=0 means “do not eject this backend on errors”. Useful when you want failures to surface to clients (a single-backend dev box) — dangerous in a real pool.
  • Sticky sessions via ip_hash plus a NAT’d corporate network — every employee at the customer office hits one backend.
  • Resolving upstream DNS at config load only. Nginx caches the IP forever unless you use resolver and set $upstream … indirection or the commercial resolve flag on server.

In the engagements we run, load balancing is rarely the hard part — the hard part is making the pool’s membership a function of an authoritative inventory (Terraform, an autoscaling group, an etcd lease) so a drained box is actually drained everywhere. Stack Harbor wraps this into clustered environments where the LB config follows the cluster state automatically.