HAProxy
medium 28 minHAProxy is a load balancer and reverse proxy for TCP and HTTP.
See it run
Rules, two draws, checks, the queue, and changing things while running.
Operations
One request
From the TLS handshake to the log line.
Step 1 of 5
Accept
TLS ends here. The request must be complete within timeout http-request.
Step 1: Accept
def handle(conn): req = read(tls(conn), timeout=5) if rate(req.src) > 200: return 429 backend = first_match(rules, req) or default server = backend.pick() resp = server.send(req) log(TR, Tw, Tc, Tr, Ta) return resp- Work per request
- A few rules
- Where state lives
- Process memory
Set all timeouts.
In the real world
The same haproxy doing real jobs. Pick one and step through it.
Two HAProxy machines behind a layer 4 balancer.
Step 1 of 2
Both work
Each takes half. Peers copy the stick tables.
Step 1: Both work
Common mistakes
The bugs interviewers watch for, with the fix beside each.
No timeouts
criticalDead clients and servers hold connections for ever until the limit is reached.
Wrongdefaults mode httpRightdefaults mode http timeout connect 3s timeout client 30s timeout server 30s timeout http-request 5sNo limit per server
majorIn a peak every server gets slow for everyone, and retries add more.
Wrongserver api1 10.0.0.11:8080 checkRightserver api1 10.0.0.11:8080 check maxconn 100Checking only the port
majorA frozen app still accepts TCP connections.
Wrongserver api1 10.0.0.11:8080 checkRightoption httpchkhttp-check send meth GET uri /healthhttp-check expect status 200Trusting the client's header
majorA client can send any X-Forwarded-For. Set it, do not add to it.
Wrong# header passed on as receivedRighthttp-request set-header X-Forwarded-For %[src]Changes only at run time
minorThe next reload reads the files and brings the old values back.
Wrongset server api/api1 weight 10Right# change the file too:server api1 10.0.0.11:8080 check weight 10
Interview tips
How to explain it
- Rules choose the group.
- Two draws choose the server.
- The surplus waits in the proxy.
Numbers to know
- Check every 2 s, fall 3, rise 2.
- maxconn has no default limit.
- Random of two since 3.3.
Reach for it when
- Balancing is the main job.
- Servers need protection.
- You want to see where time goes.
Before production
- All timeouts, maxconn, real checks.
- Two machines.
- haproxy -c in the pipeline.