Day 3: Scaling horizontally with HAProxy
Goal: Start a second instance on s2, put HAProxy in front, secure it with health checks, and measure when two instances really handle more than one, and which balancing algorithm matters · Duration: approx. 75 min · Prerequisite: Day 2
Briefing
- Scaling vertically means: a bigger machine. Horizontally means: more machines, with a load balancer in front that distributes the requests. Horizontal goes further, but requires the app to be stateless: every instance must be able to answer every request.
kurzis stateless. Everything that matters is in PostgreSQL. A second instance is therefore just a copy of the file with a different name.- HAProxy distributes according to an algorithm (round robin, least connections, hash) and checks regularly whether the instances are healthy.
k6 ──▶ HAProxy :80 (s1) ──┬──▶ kurz s1:8080 ──┐
└──▶ kurz s2:8080 ──┴──▶ PostgreSQL (s3)
Stats :8404 Health check: GET /readyz every 2 s
Drill 1: The second instance
From today on, you also work on s2 and s3 from s1. For this, s1 needs an SSH key that s2 and s3 know:
# on s1
[ -f ~/.ssh/id_ed25519 ] || ssh-keygen -t ed25519 -N '' -f ~/.ssh/id_ed25519
cat ~/.ssh/id_ed25519.pubAppend the public key to ~/.ssh/authorized_keys on s2
and s3, the same way you deposited your own key. Then:
# on s1
ssh -o StrictHostKeyChecking=accept-new s2 hostname
ssh -o StrictHostKeyChecking=accept-new s3 hostnameExpected:
Warning: Permanently added 's2' (ED25519) to the list of known hosts.
s2
s3
Binary and unit to s2; only the name of the instance changes:
# on s1
scp -q /usr/local/bin/kurz s2:/tmp/kurz
sed 's/KURZ_INSTANZ=s1/KURZ_INSTANZ=s2/' /etc/systemd/system/kurz.service > /tmp/kurz.service
scp -q /tmp/kurz.service s2:/tmp/
ssh s2 'sudo install /tmp/kurz /usr/local/bin/kurz && sudo cp /tmp/kurz.service /etc/systemd/system/ \
&& sudo systemctl daemon-reload && sudo systemctl enable --now kurz'
curl -si http://s2:8080/healthz | grep -E '^HTTP|X-Kurz'Expected:
Created symlink /etc/systemd/system/multi-user.target.wants/kurz.service → /etc/systemd/system/kurz.service.
HTTP/1.1 200 OK
X-Kurz-Instanz: s2
Save your progress? Sign up for free
Drill 2: HAProxy in front
# on s1
sudo cp /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.orig
sudo tee /etc/haproxy/haproxy.cfg >/dev/null <<'EOF'
global
log /dev/log local0
maxconn 20000
stats socket /run/haproxy/admin.sock mode 660 level admin
defaults
mode http
log global
option httplog
timeout connect 2s
timeout client 30s
timeout server 30s
frontend web
bind :80
default_backend kurz
backend kurz
balance roundrobin
option httpchk GET /readyz
http-check expect status 200
default-server inter 2s fall 3 rise 2
server s1 s1:8080 check
server s2 s2:8080 check
frontend stats
bind :8404
stats enable
stats uri /
stats refresh 5s
EOF
sudo haproxy -c -f /etc/haproxy/haproxy.cfg; echo "Exit: $?"
sudo systemctl reload haproxy
for i in 1 2 3 4 5 6; do curl -s -o /dev/null -D - http://localhost/healthz | grep -i x-kurz; doneExpected:
Exit: 0
x-kurz-instanz: s1
x-kurz-instanz: s2
x-kurz-instanz: s1
x-kurz-instanz: s2
x-kurz-instanz: s1
x-kurz-instanz: s2
Alternating, as ordered. That the header now arrives in lowercase is not an error: HAProxy writes header names in lowercase, and HTTP treats them case-insensitively.
| Line | Meaning |
|---|---|
option httpchk GET /readyz |
The health check queries the readiness endpoint, which also checks the database |
inter 2s fall 3 rise 2 |
check every 2 s, out after 3 failures, back in after 2 successes |
timeout connect 2s |
anything that does not accept a connection within 2 s counts as unreachable |
The admin socket provides the state, machine-readable as CSV:
# on s1
echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f1,2,18,37 | head -5Expected:
# pxname,svname,status,check_status
web,FRONTEND,OPEN,
kurz,s1,UP,L7OK
kurz,s2,UP,L7OK
kurz,BACKEND,UP,
L7OK means: the check at layer 7, that is HTTP,
succeeded. The statistics page in the browser at
http://172.16.0.126:8404/ shows the same numbers.
Save your progress? Sign up for free
Drill 3: Does it help?
Directly against s1 versus via HAProxy to both instances:
# on s1
mkdir -p ~/sd/tag03 && cd ~/sd/tag03 && cp ~/sd/tag01/codes.txt ~/sd/tag01/mix.js .
for r in 2000 3000; do
echo "== direkt s1 $r/s"
RATE=$r DAUER=20s k6 run --quiet mix.js | grep -E 'http_req_duration\.|http_reqs\.' | sed 's/ */ /g'
echo "== HAProxy $r/s"
ZIEL=http://localhost RATE=$r DAUER=20s k6 run --quiet mix.js \
| grep -E 'http_req_duration\.|http_reqs\.' | sed 's/ */ /g'
doneExpected:
== direkt s1 2000/s
http_req_duration..............: avg=5.55ms min=675.78µs med=2.82ms max=86.05ms p(90)=14.05ms p(95)=19.79ms
http_reqs......................: 39837 1991.550113/s
== HAProxy 2000/s
http_req_duration..............: avg=20.01ms min=1.06ms med=7.92ms max=810.27ms p(90)=33.15ms p(95)=52.37ms
http_reqs......................: 38703 1932.791836/s
== direkt s1 3000/s
http_req_duration..............: avg=128.21ms min=1.16ms med=104.37ms max=592.99ms p(90)=232.84ms p(95)=323.47ms
http_reqs......................: 49598 2438.064705/s
== HAProxy 3000/s
http_req_duration..............: avg=52.06ms min=971.2µs med=35.12ms max=330.02ms p(90)=121.17ms p(95)=155.37ms
http_reqs......................: 54908 2738.776992/s
Sobering. At 2000/s, the path via HAProxy is even slower (p95 52 instead of 20 ms); at 3000/s somewhat better. The reason is in Day 2: s1 carries k6, HAProxy and one instance at the same time, and every additional hop costs CPU there. One instance is so fast that the load balancer itself becomes significant. Scaling horizontally only pays off once an instance hits its own limit.
Save your progress? Sign up for free
Drill 4: Small instances
In practice, instances are small: a container with half a core, a small cloud VM. That is exactly what you reproduce with a systemd limit. Each instance gets at most half a core:
# on s1
sudo mkdir -p /etc/systemd/system/kurz.service.d
printf '[Service]\nCPUQuota=50%%\n' | sudo tee /etc/systemd/system/kurz.service.d/cpu.conf >/dev/null
sudo systemctl daemon-reload && sudo systemctl restart kurz
ssh s2 "sudo mkdir -p /etc/systemd/system/kurz.service.d && printf '[Service]\nCPUQuota=50%%\n' \
| sudo tee /etc/systemd/system/kurz.service.d/cpu.conf >/dev/null \
&& sudo systemctl daemon-reload && sudo systemctl restart kurz"
systemctl show kurz -p CPUQuotaPerSecUSec; ssh s2 systemctl show kurz -p CPUQuotaPerSecUSecExpected:
CPUQuotaPerSecUSec=500ms
CPUQuotaPerSecUSec=500ms
500 ms of CPU time per second. And measure again:
# on s1
for r in 1000 2000; do
echo "== direkt s1 $r/s"
RATE=$r DAUER=20s k6 run --quiet mix.js | grep -E 'http_req_duration\.|http_reqs\.' | sed 's/ */ /g'
echo "== HAProxy $r/s"
ZIEL=http://localhost RATE=$r DAUER=20s k6 run --quiet mix.js \
| grep -E 'http_req_duration\.|http_reqs\.' | sed 's/ */ /g'
doneExpected:
== direkt s1 1000/s
http_req_duration..............: avg=64.11ms min=726.06µs med=55.08ms max=265.73ms p(90)=139.96ms p(95)=164.32ms
http_reqs......................: 19650 980.760248/s
== HAProxy 1000/s
http_req_duration..............: avg=5.37ms min=1.08ms med=2.73ms max=228.66ms p(90)=5.97ms p(95)=8.44ms
http_reqs......................: 19844 991.250913/s
== direkt s1 2000/s
http_req_duration..............: avg=443.71ms min=5.9ms med=473.11ms max=648.22ms p(90)=515.05ms p(95)=562.75ms
http_reqs......................: 21152 1041.450868/s
== HAProxy 2000/s
http_req_duration..............: avg=62.83ms min=1.05ms med=33.08ms max=1.09s p(90)=126.51ms p(95)=169.66ms
http_reqs......................: 36960 1842.530821/s
| Rate | One instance | Two behind HAProxy |
|---|---|---|
| 1000/s | 981/s, p95 164 ms | 991/s, p95 8 ms |
| 2000/s | 1041/s, p95 563 ms | 1843/s, p95 170 ms |
Now it shows what scaling is for: one small instance is saturated at around 1000/s, two handle almost double. At 1000/s, p95 drops from 164 to 8 ms, because neither of them runs at its limit anymore. The limit of half a core per instance stays for the rest of the book. This keeps s1 as the load generator below its own limit, and the effect of every measure stays visible.
Save your progress? Sign up for free
Drill 5: Round robin versus least connections
Round robin distributes stubbornly in turn. That works well as long as all instances are equally strong. What if s2 gets only a quarter of a core, for example because the machine is doing something else on the side?
# on s1
ssh s2 "printf '[Service]\nCPUQuota=25%%\n' | sudo tee /etc/systemd/system/kurz.service.d/cpu.conf \
>/dev/null && sudo systemctl daemon-reload && sudo systemctl restart kurz"
for algo in roundrobin leastconn; do
sudo sed -i "s/^ balance .*/ balance $algo/" /etc/haproxy/haproxy.cfg
sudo systemctl reload haproxy && sleep 4
echo "clear counters all" | sudo nc -U /run/haproxy/admin.sock >/dev/null
echo "== $algo"
ZIEL=http://localhost RATE=1200 DAUER=20s k6 run --quiet mix.js \
| grep -E 'http_req_duration\.|http_reqs\.' | sed 's/ */ /g'
echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,8 | sed -n 3,4p
doneExpected:
== roundrobin
http_req_duration..............: avg=477.27ms min=859.4µs med=34.42ms max=1.39s p(90)=1.07s p(95)=1.14s
http_reqs......................: 19200 921.983023/s
s1,9600
s2,9600
== leastconn
http_req_duration..............: avg=20.89ms min=1ms med=5.15ms max=390.55ms p(90)=67.01ms p(95)=86.07ms
http_reqs......................: 23407 1166.516763/s
s1,15928
s2,7479
Round robin gives each exactly 9600 requests. s2 drowns, and because every second request lands there, it drags the whole system to a p95 of 1.1 seconds. Least connections sends each new request to the instance with the fewest open connections: s1 gets twice as much, p95 drops to 86 ms, and throughput rises by a quarter. Without HAProxy knowing anything about CPU limits. It only sees who finishes more slowly.
Back to equal instances; leastconn stays:
# on s1
ssh s2 "printf '[Service]\nCPUQuota=50%%\n' | sudo tee /etc/systemd/system/kurz.service.d/cpu.conf \
>/dev/null && sudo systemctl daemon-reload && sudo systemctl restart kurz"
sudo sed -i "s/^ balance .*/ balance leastconn/" /etc/haproxy/haproxy.cfg
sudo haproxy -c -f /etc/haproxy/haproxy.cfg; echo "Exit: $?"
sudo systemctl reload haproxyExpected:
Exit: 0
Save your progress? Sign up for free
Exercise: Speed drills
- Show which algorithm the backend
kurzcurrently uses. Target time: 30 s - Show how many requests each instance has received so far. Target time: 1 min
- Call
/healthzten times via HAProxy and count the responses per instance. Target time: 1 min
Solution
# on s1
grep balance /etc/haproxy/haproxy.cfg
echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,8 | sed -n 3,4p
for i in $(seq 10); do curl -s -o /dev/null -D - http://localhost/healthz | grep -i x-kurz; done \
| sort | uniq -cSave your progress? Sign up for free
Checkpoint
# on s1
echo "show stat" | sudo nc -U /run/haproxy/admin.sock | cut -d, -f2,18 | sed -n 3,4pExpected: s1,UP and
s2,UP
# on s1
grep -h CPUQuota /etc/systemd/system/kurz.service.d/cpu.conf; ssh s2 grep -h CPUQuota \
/etc/systemd/system/kurz.service.d/cpu.confExpected: CPUQuota=50% twice
Challenge
A colleague wants to set balance source so that the same
user always lands on the same instance. What would that do to your load
test, and when do you need something like that at all?
Hint: From which address do all of k6’s requests come?
Solution
balance source picks the instance via a hash of the
client address. k6 sends everything from s1, so every
request lands on the same instance, and the other gets nothing. With
real users it is more even, but never as good as leastconn,
and many users behind a corporate proxy share one address. Binding to an
instance is only needed when the app keeps state in memory, such as
sessions. kurz is stateless, so it needs no binding. For
stateful apps, a cookie (cookie SERVERID insert) is a
cleaner binding than the address. Best of all, though, move the state
into a shared store like Valkey (Day 5).
Save your progress? Sign up for free
Clean-up
Nothing. HAProxy, both instances and the CPU limits stay.
Interview note
- What does an app need in order to scale horizontally? It must be stateless: no state in the memory of an instance that is needed for the next request. Sessions, uploads, caches belong in shared stores.
- Round robin or least connections? Least connections, as soon as instances or requests differ in weight. Round robin only for identical instances and identical requests.
- Isn’t the load balancer itself a single point of failure? Yes. In production, two run with a shared virtual address (keepalived/VRRP), or a managed cloud load balancer is used.
Enterprise note
- In front of HAProxy there is often another layer: DNS with multiple addresses, anycast or a CDN. Each layer distributes coarsely, the next one finely.
- Health checks should verify whether an instance can
answer requests, not just whether the process is alive.
/readyzwith a database check is good as long as the check stays cheap. A health check that takes all instances out at the same time on every database hiccup turns a partial outage into a total outage. That is exactly what Day 4 examines.