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
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 %38 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:
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