{"id":1135,"date":"2026-11-03T12:31:44","date_gmt":"2026-11-03T12:31:44","guid":{"rendered":"https:\/\/www.vps.tc\/blog\/?p=1135"},"modified":"2026-11-03T09:33:41","modified_gmt":"2026-11-03T09:33:41","slug":"what-is-a-load-balancer-traffic-distribution","status":"publish","type":"post","link":"https:\/\/www.vps.tc\/blog\/en\/what-is-a-load-balancer-traffic-distribution\/","title":{"rendered":"Understanding Load Balancers: How Traffic Distribution Works"},"content":{"rendered":"<div class=\"aiw-summary\" id=\"aiw-ozet\">\n<p class=\"aiw-summary-title\">Quick Summary &#8211; Load Balancing<\/p>\n<p>A load balancer distributes client traffic across backend servers according to configured rules and health checks. It does not create capacity; it lets existing application nodes work together.<\/p>\n<ul>\n<li><strong>Single entry address<\/strong> \u2014 In the hypothetical isolated lab, the client connects to HAProxy at 192.0.2.10, which distributes requests to backends at 192.0.2.11 and 192.0.2.12.<\/li>\n<li><strong>L4 and L7<\/strong> \u2014 L4 operates at the TCP connection level, while L7 can use application information such as HTTP paths and headers.<\/li>\n<li><strong>Distribution algorithm<\/strong> \u2014 Round robin is selected for the two stateless, equally sized example backends; equal request counts do not guarantee equal processing loads.<\/li>\n<li><strong>TLS trust boundary<\/strong> \u2014 TLS terminates at HAProxy on 443\/TCP; unencrypted backend connections on 8080\/TCP are an assumption limited to the isolated lab.<\/li>\n<li><strong>Health checks<\/strong> \u2014 HAProxy expects HTTP 200 from \/health and excludes a node from new request distribution once it reaches the failure threshold.<\/li>\n<li><strong>Single failure point<\/strong> \u2014 Even with two application servers, losing the single HAProxy node can interrupt access to the service.<\/li>\n<\/ul>\n<\/div>\n<p class=\"aiw-lead\">Two application servers do not automatically share traffic. A load balancer accepts client traffic at a common endpoint and distributes it to suitable backends. Its algorithm determines which node to select; health checks determine which nodes are available. It uses existing capacity rather than creating more, and neither replicates databases nor prevents every outage.<\/p>\n<div class=\"aiw-toc\" style=\"border:1px solid #dbe3ea;border-radius:8px;padding:16px 20px;margin:0 0 28px\">\n<p class=\"aiw-toc-head\"><strong>Table of Contents<\/strong><span class=\"aiw-toc-meta\"> \u00b7 18 min read<\/span><\/p>\n<ol style=\"margin:10px 0 0;padding-left:22px\">\n<li><a href=\"#why-does-traffic-enter-through-one-endpoint-when-there-are-two-application-servers\">Why Does Traffic Enter Through One Endpoint When There Are Two Application Servers?<\/a><\/li>\n<li><a href=\"#l4-and-l7-what-information-drives-the-routing-decision\">L4 and L7: What Information Drives the Routing Decision?<\/a><\/li>\n<li><a href=\"#is-round-robin-suitable-for-every-workload\">Is Round Robin Suitable for Every Workload?<\/a><\/li>\n<li><a href=\"#serving-two-backends-through-one-address-with-haproxy\">Serving Two Backends Through One Address with HAProxy<\/a><\/li>\n<li><a href=\"#tls-termination-and-the-trust-boundary-around-client-ip-addresses\">TLS Termination and the Trust Boundary Around Client IP Addresses<\/a><\/li>\n<li><a href=\"#when-a-node-is-not-ready-testing-health-checks\">When a Node Is Not Ready: Testing Health Checks<\/a><\/li>\n<li><a href=\"#what-happens-if-the-load-balancer-stops\">What Happens If the Load Balancer Stops?<\/a><\/li>\n<li><a href=\"#check-these-before-validating-the-lab\">Check These Before Validating the Lab<\/a><\/li>\n<li><a href=\"#frequently-asked-questions\">Frequently Asked Questions<\/a><\/li>\n<li><a href=\"#sources\">Sources<\/a><\/li>\n<\/ol>\n<\/div>\n<h2 id=\"why-does-traffic-enter-through-one-endpoint-when-there-are-two-application-servers\">Why Does Traffic Enter Through One Endpoint When There Are Two Application Servers?<\/h2>\n<p>One application node struggles; another sits idle. Capacity exists. Starting another server changes nothing if clients still connect to the first. In this hypothetical lab, I put a shared endpoint before <code>app1<\/code> and <code>app2<\/code>, centralizing server selection so traffic can reach either node.<\/p>\n<p>So, <strong>what is a load balancer<\/strong>? A component distributing incoming traffic across backend servers according to configured rules-the core function described in Google Cloud&#8217;s overview. Clients connect to one address; the balancer selects a node. The application&#8217;s address becomes independent of server selection.<\/p>\n<p>The test client at <code>192.0.2.20<\/code> reaches HAProxy at <code>192.0.2.10<\/code>, which forwards requests to <code>app1<\/code> at <code>192.0.2.11:8080<\/code> or <code>app2<\/code> at <code>192.0.2.12:8080<\/code>. HAProxy&#8217;s 2.8 configuration documentation describes <code>frontend<\/code> as accepting connections and <code>backend<\/code> as defining distribution settings and servers. An <a href=\"https:\/\/www.vps.tc\/blog\/en\/nginx-reverse-proxy-setup\/\">Nginx reverse proxy<\/a> offers a useful comparison: here, the intermediary distributes traffic between two application nodes.<\/p>\n<p>This lab runs Ubuntu Server 24.04 LTS with distribution-packaged HAProxy 2.8.x. It is not internet-routed. RFC 5737 reserves <code>192.0.2.0\/24<\/code> for documentation; here it stays inside an isolated virtual network. No real DNS record is assumed: <code>curl --resolve<\/code> maps <code>app.example.com<\/code> to HAProxy. HAProxy redirects HTTP on 80\/TCP to HTTPS, terminates TLS on 443\/TCP, and connects to backends over HTTP. Clients verify the certificate using <code>--cacert \/opt\/lb-demo\/ca.crt<\/code>. Only the balancer can access backend 8080\/TCP; management access stays separate.<\/p>\n<p>Load balancing distributes traffic across existing capacity; it creates none. It cannot accelerate a slow node, and not every distribution rule considers current load. Two nodes do not mean halved response times: a single request&#8217;s work is not automatically split between machines. Disk bottlenecks and serial application processing remain.<\/p>\n<p>The Python 3.12 standard-library applications are stateless, without a shared database. Balancing neither replicates databases nor automatically shares sessions. Before moving your application onto a second node, identify where session data and uploaded files live. A shared entry address does not make the servers&#8217; memory or disks shared.<\/p>\n<div class=\"aiw-callout aiw-callout-example\">\n<p class=\"aiw-callout-label\">Example<\/p>\n<p>In the hypothetical lab, HAProxy at 192.0.2.10 distributes requests to 192.0.2.11:8080 and 192.0.2.12:8080. These documentation addresses are used only within an isolated virtual network; no real DNS record or internet-facing service is assumed.<\/p>\n<\/div>\n<h2 id=\"l4-and-l7-what-information-drives-the-routing-decision\">L4 and L7: What Information Drives the Routing Decision?<\/h2>\n<p>Two requests reaching one IP but different servers do not prove the balancer reads URLs. Connection information can suffice. Google Cloud&#8217;s documentation distinguishes network balancing from HTTP-aware application balancing. I&#8217;d choose based on the information your routing decision needs.<\/p>\n<p><strong>L4 balances TCP connections.<\/strong> Source and destination IPs, ports, and the balancing algorithm can inform selection. HAProxy&#8217;s 2.8 configuration manual describes <code>mode tcp<\/code> as bidirectional forwarding without interpreting HTTP messages. Requests sharing a connection stay with the selected backend; they do not rotate between servers. Long-lived connections affect distribution. Equal connection counts do not mean equal application load.<\/p>\n<p><strong>L7 can route using HTTP request information:<\/strong> the <code>Host<\/code> header, URL path, or another header. HAProxy&#8217;s documented <code>mode http<\/code> and ACL mechanism support request-level decisions. Separate path-based pools are optional; L7 can simply distribute requests between two copies of one application.<\/p>\n<p>TLS sets the boundary. With passthrough, backends decrypt traffic; the balancer cannot read HTTP headers or paths. Inspecting SNI in an unencrypted ClientHello does not expose HTTP content. This hypothetical, non-internet-routed lab uses TLS-terminating L7: HAProxy 2.8.x on Ubuntu Server 24.04 LTS terminates TLS at <code>192.0.2.10:443<\/code>, forwarding <code>app.example.com<\/code> requests over HTTP across the isolated backend network to app1 at <code>192.0.2.11:8080<\/code> or app2 at <code>192.0.2.12:8080<\/code>.<\/p>\n<p>A reverse proxy accepts client connections for backends, potentially just one. A load balancer distributes traffic among multiple targets. Overlapping roles, not synonyms. An <a href=\"https:\/\/www.vps.tc\/blog\/en\/nginx-reverse-proxy-setup\/\">Nginx reverse proxy setup<\/a> can perform both; this lab&#8217;s HAProxy does too.<\/p>\n<p>DNS-based distribution returns different IP addresses; it neither carries HTTP traffic nor routes by URL path. Caching and TTL affect when clients see changed addresses. This lab uses no real DNS: on test client <code>192.0.2.20<\/code>, <code>curl --resolve<\/code> maps the name to the balancer for the specified port. Changing a DNS answer does not move an existing TCP connection to another backend.<\/p>\n<h2 id=\"is-round-robin-suitable-for-every-workload\">Is Round Robin Suitable for Every Workload?<\/h2>\n<p>Equal request counts do not mean equal work. Imagine one request returning text while another builds a large report: matching counters can hide different CPU usage and response times. Counts mislead. I would consider request duration, connection behavior, and backend capacity too.<\/p>\n<p>According to the HAProxy 2.8 configuration manual, <code>roundrobin<\/code> selects servers in turn according to their weights-a reasonable starting point for short, similarly priced HTTP requests. It neither measures application CPU queues nor predicts request cost. The next server might not finish first; expensive requests accumulating on one node can produce uneven response times.<\/p>\n<h3>Long connections change the calculation<\/h3>\n<p>The same manual recommends <code>leastconn<\/code> for long sessions, not very short HTTP sessions. It favors fewer connections while accounting for server weights. Long-lived WebSocket connections are a possible use case. Connection count still is not processing load: idle connections and those continuously processing data have different costs.<\/p>\n<p>HAProxy documents <code>balance source<\/code> as hashing the source IP. With the server set and distribution settings unchanged, the same source IP reaches the same server. Users behind NAT may share one address, concentrating traffic on one node. IP persistence does not mean evenly distributed users.<\/p>\n<p>Weights assign different traffic shares to unequal-capacity servers. Hypothetical <code>weight 2<\/code> and <code>weight 1<\/code> settings target approximately 2:1 request distribution under round robin, not twice the performance. Session stickiness can return users to one node, but cannot recover local session data after node loss. It replaces neither data consistency nor a shared session store when needed.<\/p>\n<p>For this hypothetical, isolated lab, I would choose <code>balance roundrobin<\/code>: HAProxy 2.8.x on Ubuntu Server 24.04 LTS, with equal-capacity, stateless app1 (<code>192.0.2.11:8080<\/code>) and app2 (<code>192.0.2.12:8080<\/code>). No stickiness or shared database is needed here. If the workload changes, follow <a href=\"https:\/\/www.vps.tc\/blog\/en\/prometheus-grafana-setup-vps-monitoring\/\">How to Monitor a VPS with Prometheus and Grafana<\/a> to compare per-node latency, active connections, and CPU usage. Do not change algorithms on request counts alone.<\/p>\n<h2 id=\"serving-two-backends-through-one-address-with-haproxy\">Serving Two Backends Through One Address with HAProxy<\/h2>\n<p>Two running applications do not yet make one endpoint. I would make their identities visible first. This hypothetical lab uses Ubuntu Server 24.04 LTS. RFC 5737 reserves <code>192.0.2.0\/24<\/code> for documentation; keep it isolated, never internet-routed. HTTP comes first here only to check routing before adding TLS.<\/p>\n<p>Use sudo-capable accounts. Apply security updates; install repository packages HAProxy 2.8.x, OpenSSL 3.0.x and Python 3.12. Record version-query output and exact package revisions. The Turkish labels identify machines, not executable commands: all machines, load balancer, both application nodes, then test client.<\/p>\n<pre><code># Her makinede\nsudo apt update\nsudo apt upgrade -y\n\nY\u00fck dengeleyici: 192.0.2.10\nsudo apt install -y haproxy openssl\ndpkg-query -W haproxy openssl\n\nHer iki uygulama d\u00fc\u011f\u00fcm\u00fcnde\nsudo apt install -y python3\npython3 --version\ndpkg-query -W python3 python3.12\n\nTest istemcisi: 192.0.2.20\nsudo apt install -y curl<\/code><\/pre>\n<p>Create <code>\/opt\/lb-demo\/app.py<\/code> on both backends. The stateless application uses no shared database: <code>\/<\/code> returns node identity; <code>\/health<\/code> returns 503 when the not-ready marker exists, otherwise 200. This Python standard-library server is lab-only, not a production application server.<\/p>\n<pre><code>sudo install -d -m 0755 \/opt\/lb-demo\nsudo tee \/opt\/lb-demo\/app.py &gt;\/dev\/null &lt;&lt;'PY'\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\nfrom pathlib import Path\nimport sys\n\naddress, node = sys.argv[1:3]\n\nclass Handler(BaseHTTPRequestHandler):\n    def do_GET(self):\n        if self.path == \"\/health\":\n            ready = not Path(\"\/opt\/lb-demo\/not-ready\").exists()\n            status, text = (200, \"ready\\n\") if ready else (503, \"not ready\\n\")\n        elif self.path == \"\/\":\n            status, text = 200, node + \"\\n\"\n        else:\n            status, text = 404, \"not found\\n\"\n        body = text.encode(\"utf-8\")\n        self.send_response(status)\n        self.send_header(\"Content-Type\", \"text\/plain; charset=utf-8\")\n        self.send_header(\"Content-Length\", str(len(body)))\n        self.end_headers()\n        self.wfile.write(body)\n\nThreadingHTTPServer((address, 8080), Handler).serve_forever()\nPY<\/code><\/pre>\n<p>Start each application as an ordinary user on its named node; leave terminals open. Allow backend 8080\/TCP only from <code>192.0.2.10<\/code>, blocking other sources. Keep management access separate.<\/p>\n<pre><code># Yaln\u0131zca app1 \u00fczerinde\npython3 \/opt\/lb-demo\/app.py 192.0.2.11 app1\n\nYaln\u0131zca app2 \u00fczerinde\npython3 \/opt\/lb-demo\/app.py 192.0.2.12 app2<\/code><\/pre>\n<p>HAProxy&#8217;s 2.8 configuration manual describes <code>frontend<\/code> as accepting connections; <code>backend<\/code> defines destinations and distribution. <code>roundrobin<\/code> cycles through healthy, equally weighted nodes. These starting timeouts allow five seconds for connection establishment and 30 seconds of client\/server inactivity-not a total request deadline.<\/p>\n<pre><code># Y\u00fck dengeleyicide\nsudo cp -a \/etc\/haproxy\/haproxy.cfg \/etc\/haproxy\/haproxy.cfg.before-demo\nsudo tee \/etc\/haproxy\/haproxy.cfg &gt;\/dev\/null &lt;&lt;'CFG'\nglobal\n    log \/dev\/log local0\n    user haproxy\n    group haproxy\n    daemon\n\ndefaults\n    log global\n    mode http\n    option httplog\n    timeout connect 5s\n    timeout client 30s\n    timeout server 30s\n\nfrontend http_lab\n    bind 192.0.2.10:80\n    default_backend applications\n\nbackend applications\n    balance roundrobin\n    option httpchk GET \/health\n    http-check expect status 200\n    server app1 192.0.2.11:8080 check\n    server app2 192.0.2.12:8080 check\nCFG\nsudo haproxy -c -f \/etc\/haproxy\/haproxy.cfg &amp;&amp; sudo systemctl reload haproxy<\/code><\/pre>\n<p>Validate before reloading. Always. <code>-c<\/code> checks configuration; <code>&amp;&amp;<\/code> prevents reload after failure. Expect <code>Configuration file is valid<\/code>; that does not prove backend reachability. Run these requests on the client:<\/p>\n<pre><code>for i in 1 2 3 4; do\n    curl --noproxy '*' --fail --silent --show-error \\\n      --resolve app.example.com:80:192.0.2.10 \\\n      http:\/\/app.example.com\/\ndone<\/code><\/pre>\n<p>With both nodes healthy and no competing traffic, expect alternating <code>app1<\/code>\/<code>app2<\/code>, either first. No real DNS is used. HTTP is temporary: the target redirects 80\/TCP to 443\/TCP, terminates TLS at HAProxy and keeps HTTP backends. The certificate\/key bundle belongs at <code>\/etc\/haproxy\/certs\/app.example.com.pem<\/code>, with SAN <code>app.example.com<\/code>. For HTTPS verification, specify the test-only lab CA using <code>--cacert \/opt\/lb-demo\/ca.crt<\/code>.<\/p>\n<div class=\"aiw-callout aiw-callout-tip\">\n<p class=\"aiw-callout-label\">Tip<\/p>\n<p>Before reloading the service, validate the configuration with sudo haproxy -c -f \/etc\/haproxy\/haproxy.cfg. Successful validation does not prove that the backends are reachable or that the client trusts the certificate; test connectivity separately.<\/p>\n<\/div>\n<h2 id=\"tls-termination-and-the-trust-boundary-around-client-ip-addresses\">TLS Termination and the Trust Boundary Around Client IP Addresses<\/h2>\n<p>HTTPS in your browser does not mean encryption reaches the application. The boundary moves. In this hypothetical Ubuntu Server 24.04 LTS lab, HAProxy 2.8.x terminates TLS at <code>192.0.2.10:443<\/code>, forwarding HTTP to <code>192.0.2.11:8080<\/code> and <code>192.0.2.12:8080<\/code>. Restrict backend 8080\/TCP access to HAProxy; keep management separate.<\/p>\n<h3>A certificate the client can verify<\/h3>\n<p>Run these OpenSSL 3.0.x commands on the load balancer; existing CA files stop generation. The SAN contains <code>app.example.com<\/code>. The combined certificate\/private-key PEM gets <code>600<\/code> permissions; its directory gets <code>700<\/code>.<\/p>\n<pre><code>sudo install -d \/opt\/lb-demo\nsudo install -d -o root -g root -m 700 \/etc\/haproxy\/certs\nsudo sh -c '\nset -e\numask 077\ncd \/opt\/lb-demo\ntest ! -e ca.key\ntest ! -e ca.crt\nopenssl req -x509 -newkey rsa:2048 -nodes -sha256 -days 365 \\\n  -keyout ca.key -out ca.crt -subj \"\/CN=LB Demo Lab CA\" \\\n  -addext \"basicConstraints=critical,CA:TRUE\" \\\n  -addext \"keyUsage=critical,keyCertSign,cRLSign\"\nopenssl req -new -newkey rsa:2048 -nodes \\\n  -keyout app.example.com.key -out app.example.com.csr \\\n  -subj \"\/CN=app.example.com\"\nprintf \"%s\\n\" \\\n  \"subjectAltName=DNS:app.example.com\" \\\n  \"basicConstraints=critical,CA:FALSE\" \\\n  \"keyUsage=critical,digitalSignature,keyEncipherment\" \\\n  \"extendedKeyUsage=serverAuth\" &gt; server.ext\nopenssl x509 -req -in app.example.com.csr \\\n  -CA ca.crt -CAkey ca.key -CAcreateserial \\\n  -out app.example.com.crt -days 30 -sha256 -extfile server.ext\ncat app.example.com.crt app.example.com.key \\\n  &gt; \/etc\/haproxy\/certs\/app.example.com.pem\nchown root:root \/etc\/haproxy\/certs\/app.example.com.pem\nchmod 600 \/etc\/haproxy\/certs\/app.example.com.pem\nopenssl verify -CAfile ca.crt -verify_hostname app.example.com app.example.com.crt\n'<\/code><\/pre>\n<p>Expect <code>app.example.com.crt: OK<\/code>. Securely transfer only the CA certificate to the client&#8217;s <code>\/opt\/lb-demo\/ca.crt<\/code>, readable by your account. Do not transfer the CA private key. System-wide trust installation is unnecessary.<\/p>\n<h3>I would not trust the incoming header<\/h3>\n<p>The HAProxy 2.8 configuration manual specifies that <code>http-request set-header<\/code> replaces existing same-name headers. With one trusted proxy, derive <code>X-Forwarded-For<\/code> from the TCP source. Sender identity also matters when you <a href=\"https:\/\/www.vps.tc\/blog\/en\/nginx-reverse-proxy-setup\/\">configure Nginx as a reverse proxy<\/a>.<\/p>\n<p>Replace the frontend\/backend pair in <code>\/etc\/haproxy\/haproxy.cfg<\/code>; retain <code>global<\/code> and timeout-configured <code>defaults<\/code>. Remove all <code>option forwardfor<\/code> settings, including inherited ones. HTTP requests stop at the redirect, so downstream <code>X-Forwarded-Proto<\/code> is <code>https<\/code>. Delete <code>Forwarded<\/code> too.<\/p>\n<pre><code>frontend fe_web\n    mode http\n    bind 192.0.2.10:80\n    bind 192.0.2.10:443 ssl crt \/etc\/haproxy\/certs\/app.example.com.pem\n    http-request redirect scheme https code 301 unless { ssl_fc }\n    http-request del-header Forwarded\n    http-request set-header X-Forwarded-For %[src]\n    http-request set-header X-Forwarded-Proto https\n    default_backend be_apps\n\nbackend be_apps\n    mode http\n    balance roundrobin\n    option httpchk\n    http-check send meth GET uri \/health ver HTTP\/1.1 hdr Host app.example.com\n    http-check expect status 200\n    server app1 192.0.2.11:8080 check\n    server app2 192.0.2.12:8080 check<\/code><\/pre>\n<p>The Turkish labels below identify the load balancer and test client. Do not execute the uncommented client label.<\/p>\n<pre><code># Y\u00fck dengeleyicide:\nsudo haproxy -c -f \/etc\/haproxy\/haproxy.cfg &amp;&amp; sudo systemctl reload haproxy\n\n192.0.2.20 test istemcisinde:\ncurl --noproxy '*' --resolve app.example.com:80:192.0.2.10 \\\n  -sS -D - -o \/dev\/null http:\/\/app.example.com\/\ncurl --noproxy '*' --resolve app.example.com:443:192.0.2.10 \\\n  --cacert \/opt\/lb-demo\/ca.crt \\\n  -H 'X-Forwarded-For: 192.0.2.99' \\\n  -sS -D - https:\/\/app.example.com\/<\/code><\/pre>\n<p>Expect <code>301<\/code> with an HTTPS <code>Location<\/code>, then node identity after certificate verification. <code>--resolve<\/code> replaces DNS lookup; <code>--cacert<\/code> specifies the test CA. The root response does not expose request headers, so cannot prove forwarding: the expected application-side address is <code>192.0.2.20<\/code>, not <code>192.0.2.99<\/code>.<\/p>\n<p>In the Python 3.12 application, <code>\/opt\/lb-demo\/app.py<\/code>, trust these headers only when <code>BaseHTTPRequestHandler<\/code>&#8216;s <code>self.client_address[0]<\/code> equals <code>192.0.2.10<\/code>. Never use other peers&#8217; headers for identity or access decisions. Backend HTTP is an isolated-lab assumption; across untrusted networks, re-encrypt with certificate-verified TLS.<\/p>\n<div class=\"aiw-callout aiw-callout-warn\">\n<p class=\"aiw-callout-label\">Caution<\/p>\n<p>A client-supplied X-Forwarded-For header is not a trustworthy record of the client IP on its own. In this lab&#039;s single-proxy setup, HAProxy should replace it with the connection&#039;s source address, and the application should trust forwarded headers only from HAProxy. Restrict access to 8080\/TCP to the load balancer as well.<\/p>\n<\/div>\n<h2 id=\"when-a-node-is-not-ready-testing-health-checks\">When a Node Is Not Ready: Testing Health Checks<\/h2>\n<p>An open port proves little. In this hypothetical Ubuntu Server 24.04 LTS lab, I would test readiness by keeping app1&#8217;s <code>\/<\/code> working while <code>\/health<\/code> returns 503.<\/p>\n<p>HAProxy 2.8&#8217;s configuration documentation says default HTTP checks accept 2xx and 3xx responses. Require exactly 200 in the <code>apps<\/code> block of <code>\/etc\/haproxy\/haproxy.cfg<\/code>; preserve the HTTPS frontend&#8217;s <code>default_backend apps<\/code> and existing TLS settings:<\/p>\n<pre><code>backend apps\n    mode http\n    balance roundrobin\n    option httpchk\n    http-check send meth GET uri \/health ver HTTP\/1.1 hdr Host app.example.com\n    http-check expect status 200\n    server app1 192.0.2.11:8080 check inter 2s fall 3 rise 2\n    server app2 192.0.2.12:8080 check inter 2s fall 3 rise 2<\/code><\/pre>\n<p>The same documentation defines <code>inter 2s<\/code> as the check interval, <code>fall 3<\/code> as three consecutive failures before removal, and <code>rise 2<\/code> as two consecutive successes before return. Neither six-second detection nor four-second recovery is guaranteed: failure timing, response times, timeouts and scheduling delays matter.<\/p>\n<p>On the load balancer, validate and reload; <code>&amp;&amp;<\/code> prevents reloading if validation fails:<\/p>\n<pre><code>sudo haproxy -c -f \/etc\/haproxy\/haproxy.cfg &amp;&amp; sudo systemctl reload haproxy<\/code><\/pre>\n<p>Through app1&#8217;s management session, stop the application and temporarily disable automatic restarting. Run this Python 3.12 helper in the foreground. Replacement can briefly cause connection errors; assess the 503 test only after it starts listening. Keep 8080\/TCP accessible only from the load balancer.<\/p>\n<pre><code>python3.12 - &lt;&lt;'PY'\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\n\nclass Handler(BaseHTTPRequestHandler):\n    def do_GET(self):\n        if self.path == \"\/health\":\n            status, body = 503, b\"not ready\\n\"\n        elif self.path == \"\/\":\n            status, body = 200, b\"app1\\n\"\n        else:\n            status, body = 404, b\"not found\\n\"\n        self.send_response(status)\n        self.send_header(\"Content-Type\", \"text\/plain\")\n        self.send_header(\"Content-Length\", str(len(body)))\n        self.end_headers()\n        self.wfile.write(body)\n\ntry:\n    ThreadingHTTPServer((\"192.0.2.11\", 8080), Handler).serve_forever()\nexcept KeyboardInterrupt:\n    pass\nPY<\/code><\/pre>\n<p>From the load balancer, expect <code>503<\/code>:<\/p>\n<pre><code>curl -sS --max-time 5 -o \/dev\/null -w '%{http_code}\\n' \\\n  http:\/\/192.0.2.11:8080\/health<\/code><\/pre>\n<p>On test client 192.0.2.20, run this before the change, during the 503 condition and after recovery. Each invocation opens a new connection; <code>--resolve<\/code> avoids real DNS, while <code>--cacert<\/code> verifies the certificate using the lab CA.<\/p>\n<pre><code>for i in $(seq 1 12); do\n    curl --silent --show-error --fail --max-time 5 \\\n      --resolve app.example.com:443:192.0.2.10 \\\n      --cacert \/opt\/lb-demo\/ca.crt https:\/\/app.example.com\/\n    sleep 1\ndone<\/code><\/pre>\n<p>Expect both nodes initially, then only app2 after the failure threshold. Stop the helper with Ctrl+C, restart <code>\/opt\/lb-demo\/app.py<\/code> using its previous launch method, and restore automatic restarting. Repeat the direct check: expect 200. After two successful health checks, app1 should rejoin. These are expectations, not measured results.<\/p>\n<p>Existing connections do not migrate; requests in progress may fail. Retrying writes can duplicate operations-verify application idempotency keys or equivalent protection before enabling automatic retries.<\/p>\n<div class=\"aiw-callout aiw-callout-warn\">\n<p class=\"aiw-callout-label\">Caution<\/p>\n<p>The settings inter 2s, fall 3, and rise 2 define the check interval and consecutive failure\/success thresholds, respectively; they do not guarantee an exact failure-detection time. Existing connections to a node removed from the pool do not move to another server. Automatically retrying write requests can repeat the same operation unless the application prevents duplicate processing.<\/p>\n<\/div>\n<h2 id=\"what-happens-if-the-load-balancer-stops\">What Happens If the Load Balancer Stops?<\/h2>\n<p>Two healthy application servers can still leave your site unreachable. In this hypothetical lab, the single HAProxy 2.8.x node on Ubuntu Server 24.04 LTS at <code>192.0.2.10<\/code> is a <strong>single point of failure<\/strong>. If it disappears, <code>192.0.2.11<\/code> and <code>192.0.2.12<\/code> may keep serving, but backend <code>8080\/TCP<\/code> access allows only the balancer. The test client has no direct route in.<\/p>\n<p>Symptoms vary. A stopped HAProxy process may cause connection refusals; unanswered traffic may cause timeouts. Do not expect HTTP 503 if nothing can generate that response. HAProxy&#8217;s 2.8 configuration documentation describes checks that remove unhealthy backends from rotation, not protection against losing the balancer itself.<\/p>\n<p>A second balancer is an architectural option, not configured here. Traffic needs a way to reach the healthy node: consider provider-supported virtual or reassignable IPs, without assuming VRRP works on every VPS network. Keep certificates, configuration and security rules consistent. I would also ask whether one physical failure could disable both nodes.<\/p>\n<p>Managed balancing shifts some operational work to a provider. Google Cloud&#8217;s overview describes regional and global scope options for application and network load balancers. Compare protocols, regional-failure resilience requirements, health-check behavior and documented service limits. Application dependencies do not automatically become redundant.<\/p>\n<p>For capacity decisions, I would compare HTTP error rates, connection failures, queue length, backend health and p95\/p99 latency: completion-time thresholds covering 95% and 99% of requests, respectively. HAProxy&#8217;s documented connection limits and queue timeouts help locate potential waiting points. Growing queues alongside rising latency suggest capacity pressure; CPU alone cannot tell you enough. <a href=\"https:\/\/www.vps.tc\/blog\/en\/prometheus-grafana-setup-vps-monitoring\/\">How to Monitor a VPS with Prometheus and Grafana<\/a> explains an approach for comparing these signals on one timeline.<\/p>\n<p>The lab&#8217;s Python 3.12 applications are stateless, without a shared database. Production needs separate designs for session storage, database redundancy and data consistency. Session stickiness cannot recover sessions from a lost node&#8217;s memory.<\/p>\n<p>Before production, include balancer loss in a controlled failure test. Check connection failures, alarm delivery and restored TLS-verified access after recovery separately.<\/p>\n<h2 id=\"check-these-before-validating-the-lab\">Check These Before Validating the Lab<\/h2>\n<ul class=\"aiw-checklist\">\n<li>Apply Ubuntu Server 24.04 LTS security updates and record the exact package revisions for HAProxy 2.8.x, OpenSSL 3.0.x, and Python 3.12.<\/li>\n<li>Use 192.0.2.0\/24 addresses only within the isolated virtual network and restrict backend access on 8080\/TCP to HAProxy.<\/li>\n<li>Verify that the lab certificate includes app.example.com in its SAN field and restrict permissions on the PEM file containing the private key.<\/li>\n<li>Do not reload HAProxy until you have validated its configuration with sudo haproxy -c -f \/etc\/haproxy\/haproxy.cfg.<\/li>\n<li>Test HTTPS access with curl &#8211;resolve app.example.com:443:192.0.2.10 &#8211;cacert \/opt\/lb-demo\/ca.crt https:\/\/app.example.com\/.<\/li>\n<li>Make one backend return 503 from \/health in a controlled test; observe its exclusion from new request distribution and its return to service after it resumes returning 200.<\/li>\n<li>Test HAProxy failure before moving to a production design, and monitor error rates, queue length, and latency percentiles.<\/li>\n<\/ul>\n<div class=\"aiw-cta\">\n<p>Do not stop at watching requests spread across two backends. Before going to production, stop the load balancer in a controlled test and verify that your planned backup access path actually works.<\/p>\n<p class=\"aiw-cta-action\"><a href=\"https:\/\/www.vps.tc\/en\/vps\">Explore VPS plans<\/a><\/p>\n<\/div>\n<h2 id=\"frequently-asked-questions\">Frequently Asked Questions<\/h2>\n<div class=\"aiw-faq\">\n<details class=\"aiw-faq-item\" open>\n<summary>What is a load balancer, and what does it do?<\/summary>\n<p>A load balancer distributes incoming client connections or requests across multiple backend servers. Its distribution algorithm, weights, and health checks can determine which node receives traffic. This makes use of existing capacity and reduces new traffic sent to unhealthy nodes. However, a load balancer does not create additional processing capacity, replicate application data, or provide high availability on its own.<\/p>\n<\/details>\n<details class=\"aiw-faq-item\">\n<summary>What is the difference between L4 and L7 load balancing?<\/summary>\n<p>L4 load balancing distributes traffic using transport-layer information, such as TCP connections. L7 can make routing decisions based on HTTP paths, hostnames, or headers. When TLS traffic passes through without being decrypted, its HTTP headers are not visible. The hypothetical lab uses an L7 setup because HAProxy terminates TLS on 443\/TCP and can therefore process HTTP information.<\/p>\n<\/details>\n<details class=\"aiw-faq-item\">\n<summary>Are a reverse proxy and a load balancer the same thing?<\/summary>\n<p>A reverse proxy communicates with backend services on behalf of clients and can sit in front of just one server. A load balancer&#039;s defining job is distributing traffic across multiple targets. Software such as HAProxy can perform both roles. DNS-based distribution works at the name-resolution layer; caching means it does not offer the same control as a proxy in front of the application.<\/p>\n<\/details>\n<details class=\"aiw-faq-item\">\n<summary>Should I use round robin or leastconn?<\/summary>\n<p>Round robin is a straightforward starting point for nodes with similar capacity handling short requests. Leastconn considers active connection counts, making it worth evaluating for workloads with long-lived connections. Neither algorithm measures CPU load on its own. Validate your choice using request duration, queue length, and latency percentiles; do not assume equal request counts mean equal processing costs.<\/p>\n<\/details>\n<details class=\"aiw-faq-item\">\n<summary>Do open connections move when a health check fails?<\/summary>\n<p>No. Health checks do not move open connections to another backend. HAProxy can exclude a node from new distribution decisions once it reaches the failure threshold, but requests already in progress may fail or time out. Checking a \/health response that reflects application readiness is more meaningful than checking only whether a port is open. Handle duplicate write prevention separately when implementing retries.<\/p>\n<\/details>\n<details class=\"aiw-faq-item\">\n<summary>Does a single load balancer provide high availability?<\/summary>\n<p>A single load balancer can reduce the impact of backend failures, but it remains a single point of failure. If the HAProxy node stops, access to healthy application servers can also fail. Consider a second load balancer with a provider-supported virtual IP arrangement or a managed load balancing service. Design the data layer and session state separately, and test load balancer failure under controlled conditions.<\/p>\n<\/details>\n<\/div>\n<h2 id=\"sources\">Sources<\/h2>\n<ul class=\"aiw-sources\">\n<li><a href=\"https:\/\/github.com\/haproxy\/haproxy\/blob\/v2.8.0\/doc\/configuration.txt\" target=\"_blank\" rel=\"noopener\">HAProxy 2.8 &#8211; Configuration, Distribution Algorithms, and Health Checks<\/a> \u2014 github.com<\/li>\n<li><a href=\"https:\/\/cloud.google.com\/load-balancing\/docs\/load-balancing-overview\" target=\"_blank\" rel=\"noopener\">Google Cloud &#8211; Application and Network Load Balancing Overview<\/a> \u2014 cloud.google.com<\/li>\n<li><a href=\"https:\/\/www.rfc-editor.org\/rfc\/rfc5737\" target=\"_blank\" rel=\"noopener\">IETF RFC 5737 &#8211; IPv4 Address Blocks Reserved for Documentation<\/a> \u2014 rfc-editor.org<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>Distributing traffic across two application servers does not, by itself, provide high availability. A hypothetical HAProxy lab explains L4\/L7 differences, distribution algorithms, health checks, and the load balancer&#8217;s own failure risk.<\/p>\n","protected":false},"author":2,"featured_media":1133,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[11],"tags":[],"class_list":["post-1135","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cloud-computing"],"lang":"en","translations":{"en":1135,"tr":1134},"pll_sync_post":[],"_links":{"self":[{"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/posts\/1135","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/comments?post=1135"}],"version-history":[{"count":1,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/posts\/1135\/revisions"}],"predecessor-version":[{"id":1137,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/posts\/1135\/revisions\/1137"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/media\/1133"}],"wp:attachment":[{"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/media?parent=1135"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/categories?post=1135"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.vps.tc\/blog\/wp-json\/wp\/v2\/tags?post=1135"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}