AlgoViz

HAProxy

medium 28 min

HAProxy 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

Our systemHTTPSClientsHAProxyGET /api/cartServer api1Server api2Server api3

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

Our systemUsersL4 balancerHAProxy 140% busyHAProxy 240% busyServers

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

    critical

    Dead clients and servers hold connections for ever until the limit is reached.

    Wrong
    defaults    mode http
    Right
    defaults    mode http    timeout connect 3s    timeout client 30s    timeout server 30s    timeout http-request 5s
  • No limit per server

    major

    In a peak every server gets slow for everyone, and retries add more.

    Wrong
    server api1 10.0.0.11:8080 check
    Right
    server api1 10.0.0.11:8080 check maxconn 100
  • Checking only the port

    major

    A frozen app still accepts TCP connections.

    Wrong
    server api1 10.0.0.11:8080 check
    Right
    option httpchkhttp-check send meth GET uri /healthhttp-check expect status 200
  • Trusting the client's header

    major

    A client can send any X-Forwarded-For. Set it, do not add to it.

    Wrong
    # header passed on as received
    Right
    http-request set-header X-Forwarded-For %[src]
  • Changes only at run time

    minor

    The next reload reads the files and brings the old values back.

    Wrong
    set server api/api1 weight 10
    Right
    # 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.