TExcelTAD
Home › Web Servers in Depth: Nginx, HAProxy, Caddy & Traefik › Upstreams & Load-Balancing Methods

Upstreams & Load-Balancing Methods

An upstream block names a group of backend servers; proxy_pass http://name; sends requests to it. Nginx as a Reverse Proxy showed round-robin and failover. This lesson covers every method open-source Nginx has, what each is good for, and the server parameters that shape traffic. The general theory is in Load Balancing.

The methods

Directive (in upstream) Picks Good for
(none) weighted round-robin similar, stateless backends: the default
least_conn; the server with the fewest active connections (weighted) requests of very different duration (reports, uploads, long polls)
ip_hash; by the first three octets of the client IPv4 address (or the whole IPv6 address) crude stickiness without cookies
hash $key [consistent]; by any key: $request_uri, $arg_user, $cookie_session cache servers (same URL → same server), sharding
random [two [least_conn]]; random, or the better of two random picks ("power of two choices") many load balancers in front of the same backends
sticky cookie …; a cookie set by Nginx session affinity; open-source since 1.29.6 (before that NGINX Plus only), not in 1.24

Server parameters: weight=3, max_fails=3 fail_timeout=10s (passive health: after 3 failures in 10 s the server is skipped for 10 s), backup (used only when all others are down), down (taken out, keeps hash mappings stable), max_conns=100 (limit active connections to that server). Active health checks (sending probes) are an NGINX Plus feature; open-source Nginx only notices failures on real requests. That is one reason to put HAProxy or Traefik in front of backends that fail often.

Weights and backup

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[2]}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 big & A=$!
python3 app.py 9002 small & B=$!
python3 app.py 9009 backup &
for p in 9001 9002 9009; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  upstream app {
    server 127.0.0.1:9001 weight=3;
    server 127.0.0.1:9002;
    server 127.0.0.1:9009 backup;
  }
  server { listen 127.0.0.1:8080; location / { proxy_pass http://app; } }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "8 requests: $(for i in $(seq 8); do curl -s 127.0.0.1:8080/; done | tr '\n' ' ')"
kill $A $B; sleep 0.3
echo "primaries down: $(for i in $(seq 3); do curl -s 127.0.0.1:8080/; done | tr '\n' ' ')"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %3
8 requests: big big small big big big small big
primaries down: backup backup backup

Nginx's weighted round-robin is smooth: with weights 3 and 1 it sends big big small big, not big big big small, so the small server never sits idle for a whole cycle. The backup server got traffic only once both primaries were gone.

Hashing: which requests move when a server leaves?

With hash $key, the server is hash(key) mod N. Change N (a server is removed or added) and most keys move to a different server: for a cache tier, that means most of the cache is suddenly cold. hash $key consistent uses a hash ring (ketama), so only the keys of the removed server move. The session maps 400 keys over four backends, removes one, and counts how many keys changed server:

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"{sys.argv[1]}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
for p in 9001 9002 9003 9004; do python3 app.py $p & done
for p in 9001 9002 9003 9004; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
conf() {  # $1 = hash options, $2 = state of the fourth server ("" or "down"-like removal)
cat > nginx.conf <<EOF
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  upstream cache { hash \$arg_key $1; server 127.0.0.1:9001; server 127.0.0.1:9002; server 127.0.0.1:9003; $2 }
  server { listen 127.0.0.1:8080; location / { proxy_pass http://cache; } }
}
EOF
}
mapping() { for k in $(seq 400); do echo "$k $(curl -s "127.0.0.1:8080/?key=k$k")"; done; }
for mode in "" consistent; do
  conf "$mode" "server 127.0.0.1:9004;"; nginx -p "$PWD" -c nginx.conf -e stderr; mapping > before.txt
  nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; sleep 0.3
  conf "$mode" "";                       nginx -p "$PWD" -c nginx.conf -e stderr; mapping > after.txt
  nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; sleep 0.3
  moved=$(paste -d' ' before.txt after.txt | awk '$2 != $4' | wc -l)
  lost=$(grep -c ' 9004
  

 before.txt)
  echo "hash ${mode:-(plain)}: 4 -> 3 servers, $moved of 400 keys moved ($lost were on the removed server)"
done
hash (plain): 4 -> 3 servers, 296 of 400 keys moved (99 were on the removed server)
hash consistent: 4 -> 3 servers, 86 of 400 keys moved (86 were on the removed server)

With plain hashing, far more keys moved than the ones that had to (those on the removed server). With consistent, only the removed server's keys moved; the rest of the cache stays warm. Use consistent for any hash-based upstream whose membership changes. To take a server out temporarily without remapping anything, mark it down instead of deleting the line.

least_conn: a model

The difference between round-robin and least-connections shows up when request durations vary. The model below sends a fixed sequence of requests (every third takes 5 time units, the others 1) to three servers and measures how long requests wait in a queue:

python · try it yourself
def simulate(policy, arrivals, servers=3):
    ends = [[] for _ in range(servers)]     # per server: end times of queued/running requests (one at a time)
    rr, waits = 0, []
    for t, duration in arrivals:
        active = [sum(1 for e in ends[i] if e > t) for i in range(servers)]
        if policy == "round_robin":
            s = rr % servers; rr += 1
        else:                                # least_conn: fewest active, ties -> lowest index
            s = min(range(servers), key=lambda i: (active[i], i))
        start = max([t] + ends[s])           # FIFO: wait until the server's queue is empty
        ends[s].append(start + duration)
        waits.append(start - t)
    return sum(waits) / len(waits), max(waits)

# a request every time unit; every 3rd one is a slow report (5 units)
arrivals = [(t, 5 if t % 3 == 0 else 1) for t in range(60)]
for policy in ("round_robin", "least_conn"):
    avg, worst = simulate(policy, arrivals)
    print(f"{policy:12} average wait {avg:6.2f}  worst wait {worst:3d}")
round_robin  average wait   6.33  worst wait  38
least_conn   average wait   0.00  worst wait   0

The three servers together have enough capacity (7 units of work arrive every 3 time units; they can do 9), yet round-robin builds a queue: every third request lands on server 0, and every third request is slow, so server 0 gets 5 units of work per 3 time units while the others idle. Least-connections steers new requests away from the busy server and nobody waits. Real traffic is rarely this regular, but the effect is the same whenever request costs differ a lot.

Test yourself

A tier of four cache servers uses hash $request_uri;. One server is removed. What happens?

  1. Only that server's URLs move
  2. Most URLs map to a different server, so most of the cache is cold; consistent would move only the removed server's share
  3. Nothing
  4. All requests fail

Which open-source Nginx feature notices a failed backend?

  1. Active health checks that probe /health
  2. Passive checks: max_fails/fail_timeout count failures of real requests
  3. Prometheus
  4. None

When is least_conn better than round-robin?

  1. Always
  2. When request durations vary a lot, so some servers accumulate long requests
  3. When there is only one server
  4. For UDP