<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/"><channel><title>TCP | A DevOps Blog</title><link>https://blog.bsdserver.nl/tag/tcp/</link><description>Hands-on DevOps and homelab content: Kubernetes clusters, self-hosted services, CI/CD pipelines and infrastructure as code, by Patrick de Ruiter of We Build Your Cloud.</description><language>en</language><image><url>https://blog.bsdserver.nl/images/app-icon.svg</url><title>A DevOps Blog</title><link>https://blog.bsdserver.nl/</link></image><lastBuildDate>Wed, 18 Nov 2026 09:00:00 +0100</lastBuildDate><atom:link href="https://blog.bsdserver.nl/tag/tcp/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title>HAProxy TCP Load Balancing: A Complete Guide to Layer 4 Load Balancing</title><link>https://blog.bsdserver.nl/haproxy-tcp-load-balancing-a-complete-guide-to-layer-4-load-balancing/</link><guid isPermaLink="false">693b721e79eb54000160a5dc</guid><dc:creator>Patrick de Ruiter</dc:creator><pubDate>Fri, 12 Dec 2025 01:38:38 +0000</pubDate><description>HAProxy is one of the most powerful and reliable load balancers available.</description><category>HAProxy</category><category>Load balancing</category><category>TCP</category><category>High availability</category><category>Networking</category><media:content url="https://blog.bsdserver.nl/content/images/2026/01/haproxy-tcp-loadbalancing.png" medium="image"/><content:encoded><![CDATA[<p>HAProxy is one of the most powerful and reliable load balancers available. It is best known for HTTP, but databases, Redis, message queues and TLS services speak their own protocols over TCP, and they need load balancing and failover too.</p>
<p>This guide covers HAProxy in TCP mode: algorithms, protocol-aware health checks, connection limits, failover patterns, TLS passthrough, client IP preservation and logging, ending with a complete PostgreSQL and Redis configuration.</p>
<h2 id="why-tcp-load-balancing">Why TCP Load Balancing? <a class="anchor" data-pagefind-ignore href="#why-tcp-load-balancing" aria-label="Link to this section">#</a></h2>
<p>Layer 4 load balancing works at the transport layer: it routes on IP addresses and ports and forwards the bytes without reading them.</p>
<ul>
<li><strong>Protocol agnostic</strong>: Works with any TCP-based protocol (databases, message queues, custom protocols)</li>
<li><strong>Lower latency</strong>: No content inspection means faster routing decisions</li>
<li><strong>TLS passthrough</strong>: End-to-end encryption without termination at the load balancer</li>
<li><strong>Simplicity</strong>: Fewer moving parts compared to Layer 7 configuration</li>
</ul>
<h3 id="when-to-use-it">When to use it <a class="anchor" data-pagefind-ignore href="#when-to-use-it" aria-label="Link to this section">#</a></h3>
<ul>
<li><strong>Use it</strong> for non-HTTP protocols, and for HTTPS when the backends must terminate TLS themselves.</li>
<li><strong>Skip it</strong> for plain HTTP(S) services where you want path routing, header changes or HTTP-level logs: use <code>mode http</code>.</li>
</ul>
<table>
	<thead>
			<tr>
					<th></th>
					<th><code>mode tcp</code> (Layer 4)</th>
					<th><code>mode http</code> (Layer 7)</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Routes on</td>
					<td>IP, port, TLS SNI</td>
					<td>Host, path, headers, cookies</td>
			</tr>
			<tr>
					<td>Sees content</td>
					<td>No</td>
					<td>Yes</td>
			</tr>
			<tr>
					<td>Protocols</td>
					<td>Any TCP</td>
					<td>HTTP/1.x, HTTP/2, HTTP/3</td>
			</tr>
			<tr>
					<td>TLS</td>
					<td>Passthrough or termination</td>
					<td>Termination</td>
			</tr>
	</tbody>
</table>
<h2 id="architecture-overview">Architecture Overview <a class="anchor" data-pagefind-ignore href="#architecture-overview" aria-label="Link to this section">#</a></h2>
<table>
	<thead>
			<tr>
					<th>Component</th>
					<th>Runs on</th>
					<th>Job</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Frontend</td>
					<td>HAProxy</td>
					<td>Listens on a port (<code>bind *:5432</code>) and picks a backend.</td>
			</tr>
			<tr>
					<td>Backend</td>
					<td>HAProxy</td>
					<td>Holds the server list, the algorithm and the health check.</td>
			</tr>
			<tr>
					<td>Servers</td>
					<td>Database, Redis or app hosts</td>
					<td>Receive the forwarded TCP connections.</td>
			</tr>
			<tr>
					<td>Stats socket</td>
					<td>HAProxy</td>
					<td>Runtime control: drain, disable, show state.</td>
			</tr>
	</tbody>
</table>
<p>The flow: client connects to HAProxy → frontend picks a backend → algorithm picks a healthy server → HAProxy opens a connection to it and copies bytes both ways until one side closes.</p>
<h2 id="installation">Installation <a class="anchor" data-pagefind-ignore href="#installation" aria-label="Link to this section">#</a></h2>
<p>On Debian/Ubuntu, use the official HAProxy packages from <a href="https://haproxy.debian.net" rel="noopener">haproxy.debian.net</a> instead of the distribution package, which lags several branches behind:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Ubuntu 24.04: official PPA. 3.3 is the newest branch built for 24.04; it is a</span>
</span></span><span class="line"><span class="cl"><span class="c1"># short-lived, non-LTS branch. HAProxy 3.4 LTS is available for Ubuntu 26.04</span>
</span></span><span class="line"><span class="cl"><span class="c1"># (ppa:vbernat/haproxy-3.4) and for Debian 13 (below).</span>
</span></span><span class="line"><span class="cl">apt update
</span></span><span class="line"><span class="cl">apt install --no-install-recommends software-properties-common
</span></span><span class="line"><span class="cl">add-apt-repository ppa:vbernat/haproxy-3.3
</span></span><span class="line"><span class="cl">apt install <span class="nv">haproxy</span><span class="o">=</span>3.3.<span class="se">\*</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Debian 13: official haproxy.debian.net repository (3.4 LTS)</span>
</span></span><span class="line"><span class="cl">curl https://haproxy.debian.net/haproxy-archive-keyring.gpg <span class="se">\
</span></span></span><span class="line"><span class="cl">  --create-dirs --output /etc/apt/keyrings/haproxy-archive-keyring.gpg
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> deb <span class="s2">&#34;[signed-by=/etc/apt/keyrings/haproxy-archive-keyring.gpg]&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  https://haproxy.debian.net trixie-backports-3.4 main <span class="se">\
</span></span></span><span class="line"><span class="cl">  &gt; /etc/apt/sources.list.d/haproxy.list
</span></span><span class="line"><span class="cl">apt update
</span></span><span class="line"><span class="cl">apt install <span class="nv">haproxy</span><span class="o">=</span>3.4.<span class="se">\*</span>
</span></span></code></pre></div><p>On RHEL/CentOS there is no official HAProxy package repository, so you get the distribution version:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">yum install haproxy
</span></span><span class="line"><span class="cl"><span class="c1"># RHEL/Rocky/Alma 9 AppStream ships the 2.8 LTS branch; check what you got</span>
</span></span><span class="line"><span class="cl">haproxy -v
</span></span></code></pre></div><p>The RHEL unit file does not create <code>/run/haproxy</code>, so the <code>stats socket /run/haproxy/admin.sock</code> line used throughout this post stops HAProxy from starting. Let systemd create the directory:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">mkdir -p /etc/systemd/system/haproxy.service.d
</span></span><span class="line"><span class="cl"><span class="nb">printf</span> <span class="s1">&#39;[Service]\nRuntimeDirectory=haproxy\n&#39;</span> &gt; /etc/systemd/system/haproxy.service.d/runtime-directory.conf
</span></span><span class="line"><span class="cl">systemctl daemon-reload
</span></span></code></pre></div><h2 id="basic-tcp-load-balancer-configuration">Basic TCP Load Balancer Configuration <a class="anchor" data-pagefind-ignore href="#basic-tcp-load-balancer-configuration" aria-label="Link to this section">#</a></h2>
<p>A minimal load balancer for three MySQL servers. What matters for TCP:</p>
<ul>
<li><code>mode tcp</code> and <code>option tcplog</code> in <code>defaults</code>: every proxy works at Layer 4 and logs connections, not requests.</li>
<li><code>timeout client</code> / <code>timeout server</code>: idle time before HAProxy closes the connection. Too low cuts off idle database sessions.</li>
<li><code>retries 3</code>: connection attempts to a server before giving up.</li>
<li><code>option mysql-check</code>: a health check that logs in to MySQL instead of only opening the port.</li>
</ul>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy"># /etc/haproxy/haproxy.cfg

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    
    # Performance tuning
    maxconn 50000
    tune.ssl.default-dh-param 2048

defaults
    log     global
    mode    tcp
    option  tcplog
    option  dontlognull
    timeout connect 10s
    timeout client  30s
    timeout server  30s
    retries 3

frontend mysql_frontend
    bind *:3306
    default_backend mysql_servers

backend mysql_servers
    balance roundrobin
    option mysql-check user haproxy
    server mysql1 192.168.1.10:3306 check
    server mysql2 192.168.1.11:3306 check
    server mysql3 192.168.1.12:3306 check
</code></pre><h2 id="load-balancing-algorithms">Load Balancing Algorithms <a class="anchor" data-pagefind-ignore href="#load-balancing-algorithms" aria-label="Link to this section">#</a></h2>
<p>The algorithm decides which server gets the next connection.</p>
<table>
	<thead>
			<tr>
					<th>Algorithm</th>
					<th>Use it for</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>roundrobin</code></td>
					<td>Short connections of similar cost; supports weights</td>
			</tr>
			<tr>
					<td><code>leastconn</code></td>
					<td>Long-lived connections such as database sessions</td>
			</tr>
			<tr>
					<td><code>source</code></td>
					<td>Clients that must stay on the same server</td>
			</tr>
			<tr>
					<td><code>first</code></td>
					<td>Filling servers one by one, for example so spare servers can sleep</td>
			</tr>
	</tbody>
</table>
<h3 id="round-robin">Round Robin <a class="anchor" data-pagefind-ignore href="#round-robin" aria-label="Link to this section">#</a></h3>
<p>Distributes connections in turn, in proportion to <code>weight</code>:</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    balance roundrobin
    server s1 192.168.1.10:5432 check weight 1
    server s2 192.168.1.11:5432 check weight 2  # Gets 2x traffic
    server s3 192.168.1.12:5432 check weight 1
</code></pre><h3 id="least-connections">Least Connections <a class="anchor" data-pagefind-ignore href="#least-connections" aria-label="Link to this section">#</a></h3>
<p>Sends traffic to the server with fewest active connections:</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    balance leastconn
    server s1 192.168.1.10:5432 check
    server s2 192.168.1.11:5432 check
    server s3 192.168.1.12:5432 check
</code></pre><h3 id="source-ip-hash">Source IP Hash <a class="anchor" data-pagefind-ignore href="#source-ip-hash" aria-label="Link to this section">#</a></h3>
<p>Ensures the same client always connects to the same server (session persistence). <code>hash-type consistent</code> moves only a few clients when a server is added or removed.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    balance source
    hash-type consistent
    server s1 192.168.1.10:5432 check
    server s2 192.168.1.11:5432 check
    server s3 192.168.1.12:5432 check
</code></pre><h3 id="first-available">First Available <a class="anchor" data-pagefind-ignore href="#first-available" aria-label="Link to this section">#</a></h3>
<p>Uses the first server with available connection slots. Requires <code>maxconn</code> on the servers: the next server only gets traffic when the first is full.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    balance first
    server s1 192.168.1.10:5432 check maxconn 100
    server s2 192.168.1.11:5432 check maxconn 100
</code></pre><h2 id="health-checks">Health Checks <a class="anchor" data-pagefind-ignore href="#health-checks" aria-label="Link to this section">#</a></h2>
<p>HAProxy only sends traffic to servers that pass their check. An open port is not a working service, so use a protocol check where one exists.</p>
<table>
	<thead>
			<tr>
					<th>Check</th>
					<th>Proves</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>option tcp-check</code> (no steps)</td>
					<td>The port accepts connections</td>
			</tr>
			<tr>
					<td><code>mysql-check</code>, <code>pgsql-check</code></td>
					<td>The database answers its handshake</td>
			</tr>
			<tr>
					<td><code>tcp-check send</code> / <code>expect</code></td>
					<td>The service gives the right answer to a request you define</td>
			</tr>
	</tbody>
</table>
<h3 id="basic-tcp-check">Basic TCP Check <a class="anchor" data-pagefind-ignore href="#basic-tcp-check" aria-label="Link to this section">#</a></h3>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    option tcp-check
    server s1 192.168.1.10:5432 check
</code></pre><h3 id="protocol-specific-health-checks">Protocol-Specific Health Checks <a class="anchor" data-pagefind-ignore href="#protocol-specific-health-checks" aria-label="Link to this section">#</a></h3>
<h4 id="mysqlmariadb">MySQL/MariaDB <a class="anchor" data-pagefind-ignore href="#mysqlmariadb" aria-label="Link to this section">#</a></h4>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend mysql_servers
    option mysql-check user haproxy
    server mysql1 192.168.1.10:3306 check
</code></pre><p>The check logs in as <code>haproxy</code> without a password. Create the HAProxy user in MySQL:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-sql" data-lang="sql"><span class="line"><span class="cl"><span class="k">CREATE</span><span class="w"> </span><span class="k">USER</span><span class="w"> </span><span class="s1">&#39;haproxy&#39;</span><span class="o">@</span><span class="s1">&#39;%&#39;</span><span class="p">;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="n">FLUSH</span><span class="w"> </span><span class="k">PRIVILEGES</span><span class="p">;</span><span class="w">
</span></span></span></code></pre></div><h4 id="postgresql">PostgreSQL <a class="anchor" data-pagefind-ignore href="#postgresql" aria-label="Link to this section">#</a></h4>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend postgres_servers
    option pgsql-check user haproxy
    server pg1 192.168.1.10:5432 check
</code></pre><h4 id="redis">Redis <a class="anchor" data-pagefind-ignore href="#redis" aria-label="Link to this section">#</a></h4>
<p>Sends <code>PING</code> and expects <code>+PONG</code>.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend redis_servers
    option tcp-check
    tcp-check connect
    tcp-check send PING\r\n
    tcp-check expect string +PONG
    server redis1 192.168.1.10:6379 check
</code></pre><h4 id="custom-tcp-check">Custom TCP Check <a class="anchor" data-pagefind-ignore href="#custom-tcp-check" aria-label="Link to this section">#</a></h4>
<p>Sends a raw HTTP request and expects a <code>200</code> status line. <code>tcp-check connect port</code> lets the check use another port than the traffic, for a health endpoint on a separate port.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend custom_servers
    option tcp-check
    tcp-check connect port 8080
    tcp-check send &#34;GET /health HTTP/1.1\r\nHost: localhost\r\n\r\n&#34;
    tcp-check expect rstring ^HTTP/1\.[01]\ 200
    server app1 192.168.1.10:8080 check
</code></pre><h3 id="health-check-parameters">Health Check Parameters <a class="anchor" data-pagefind-ignore href="#health-check-parameters" aria-label="Link to this section">#</a></h3>
<p><code>default-server</code> sets the values for all servers in the backend; a value on a <code>server</code> line overrides it.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    default-server inter 3s fall 3 rise 2
    server s1 192.168.1.10:5432 check
    server s2 192.168.1.11:5432 check inter 5s fall 2 rise 3
</code></pre><ul>
<li><code>inter</code>: Interval between checks (default: 2s)</li>
<li><code>fall</code>: Number of failed checks before marking server down</li>
<li><code>rise</code>: Number of successful checks before marking server up</li>
</ul>
<h2 id="connection-management">Connection Management <a class="anchor" data-pagefind-ignore href="#connection-management" aria-label="Link to this section">#</a></h2>
<p>Limits protect the backends: HAProxy queues or rejects connections instead of overloading a server.</p>
<h3 id="maximum-connections">Maximum Connections <a class="anchor" data-pagefind-ignore href="#maximum-connections" aria-label="Link to this section">#</a></h3>
<p><code>maxconn</code> works at three levels:</p>
<ul>
<li><code>global</code>: the whole process. Above it, HAProxy stops accepting.</li>
<li><code>frontend</code>: per listener.</li>
<li><code>server</code>: per backend server. Extra connections wait in the backend queue.</li>
</ul>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">global
    maxconn 50000

frontend db_frontend
    bind *:5432
    maxconn 10000
    default_backend db_servers

backend db_servers
    server db1 192.168.1.10:5432 check maxconn 500
    server db2 192.168.1.11:5432 check maxconn 500
</code></pre><h3 id="connection-queuing">Connection Queuing <a class="anchor" data-pagefind-ignore href="#connection-queuing" aria-label="Link to this section">#</a></h3>
<p><code>maxqueue 50</code> caps the queue for a server; beyond that, connections go to another server or fail instead of waiting.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    fullconn 1000
    server s1 192.168.1.10:5432 check maxconn 100 maxqueue 50
</code></pre><h3 id="connection-timeouts">Connection Timeouts <a class="anchor" data-pagefind-ignore href="#connection-timeouts" aria-label="Link to this section">#</a></h3>
<p>Each timeout covers one phase of a connection; the comments say which.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">defaults
    timeout connect 5s      # Time to establish connection to server
    timeout client  60s     # Inactivity timeout on client side
    timeout server  60s     # Inactivity timeout on server side
    timeout tunnel  1h      # Timeout for tunneled connections (WebSocket, etc.)
    timeout client-fin 30s  # Timeout for client FIN
    timeout server-fin 30s  # Timeout for server FIN
</code></pre><p>Database clients and pools keep connections open and idle. Raise the client and server timeouts, or HAProxy closes them:</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">defaults
    timeout client  3600s
    timeout server  3600s
</code></pre><h2 id="high-availability-patterns">High Availability Patterns <a class="anchor" data-pagefind-ignore href="#high-availability-patterns" aria-label="Link to this section">#</a></h2>
<h3 id="active-passive-with-backup-servers">Active-Passive with Backup Servers <a class="anchor" data-pagefind-ignore href="#active-passive-with-backup-servers" aria-label="Link to this section">#</a></h3>
<p>Servers marked <code>backup</code> only get traffic when all normal servers are down.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend db_servers
    balance roundrobin
    server primary1 192.168.1.10:5432 check
    server primary2 192.168.1.11:5432 check
    server backup1  192.168.1.20:5432 check backup
    server backup2  192.168.1.21:5432 check backup
</code></pre><h3 id="readwrite-splitting">Read/Write Splitting <a class="anchor" data-pagefind-ignore href="#readwrite-splitting" aria-label="Link to this section">#</a></h3>
<p>For database clusters with a primary and replicas. One frontend listens on two ports; <code>dst_port</code> sends writes to the primary and reads to the replicas. The application chooses the port.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend mysql_frontend
    bind *:3306
    bind *:3307
    
    # Port 3306 -&gt; Write (Primary)
    # Port 3307 -&gt; Read (Replicas)
    use_backend mysql_write if { dst_port 3306 }
    use_backend mysql_read if { dst_port 3307 }

backend mysql_write
    option mysql-check user haproxy
    server primary 192.168.1.10:3306 check

backend mysql_read
    balance leastconn
    option mysql-check user haproxy
    server replica1 192.168.1.11:3306 check
    server replica2 192.168.1.12:3306 check
    server primary  192.168.1.10:3306 check backup  # Fallback to primary
</code></pre><h3 id="graceful-server-maintenance">Graceful Server Maintenance <a class="anchor" data-pagefind-ignore href="#graceful-server-maintenance" aria-label="Link to this section">#</a></h3>
<p>Take a server out without cutting active connections. <code>weight 0</code> in the configuration stops new connections; the stats socket does the same at runtime without a reload.</p>
<table>
	<thead>
			<tr>
					<th>Command</th>
					<th>Effect</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>disable server</code></td>
					<td>Maintenance mode: no new connections, existing ones continue</td>
			</tr>
			<tr>
					<td><code>set server ... state drain</code></td>
					<td>No new load-balanced connections, health checks keep running</td>
			</tr>
			<tr>
					<td><code>enable server</code></td>
					<td>Back in rotation</td>
			</tr>
	</tbody>
</table>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">backend servers
    server s1 192.168.1.10:5432 check
    server s2 192.168.1.11:5432 check weight 0  # No new connections (drain)
</code></pre><p>Use the stats socket to manage servers dynamically:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Disable a server (existing connections preserved)</span>
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;disable server servers/s1&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Set server to drain mode</span>
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;set server servers/s1 state drain&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Re-enable a server</span>
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;enable server servers/s1&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Check server status</span>
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;show servers state&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span></code></pre></div><h2 id="tls-passthrough">TLS Passthrough <a class="anchor" data-pagefind-ignore href="#tls-passthrough" aria-label="Link to this section">#</a></h2>
<p>For end-to-end encryption without terminating TLS at the load balancer. HAProxy forwards the encrypted stream; certificates live on the backends.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend tls_frontend
    bind *:443
    mode tcp
    option tcplog
    default_backend tls_servers

backend tls_servers
    mode tcp
    balance roundrobin
    server s1 192.168.1.10:443 check
    server s2 192.168.1.11:443 check
</code></pre><h3 id="sni-based-routing">SNI-Based Routing <a class="anchor" data-pagefind-ignore href="#sni-based-routing" aria-label="Link to this section">#</a></h3>
<p>Route to different backends based on the TLS SNI header, the hostname the client sends unencrypted in its TLS hello.</p>
<ul>
<li><code>tcp-request inspect-delay 5s</code>: wait up to 5 seconds for the hello before deciding.</li>
<li><code>req_ssl_hello_type 1</code>: accept once a ClientHello arrived.</li>
<li><code>req_ssl_sni</code>: the requested hostname.</li>
</ul>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend tls_frontend
    bind *:443
    mode tcp
    tcp-request inspect-delay 5s
    tcp-request content accept if { req_ssl_hello_type 1 }
    
    use_backend app1_servers if { req_ssl_sni -i app1.example.com }
    use_backend app2_servers if { req_ssl_sni -i app2.example.com }
    default_backend default_servers

backend app1_servers
    mode tcp
    server app1 192.168.1.10:443 check

backend app2_servers
    mode tcp
    server app2 192.168.1.20:443 check

backend default_servers
    mode tcp
    server default1 192.168.1.30:443 check
</code></pre><h2 id="client-ip-preservation">Client IP Preservation <a class="anchor" data-pagefind-ignore href="#client-ip-preservation" aria-label="Link to this section">#</a></h2>
<h3 id="proxy-protocol">PROXY Protocol <a class="anchor" data-pagefind-ignore href="#proxy-protocol" aria-label="Link to this section">#</a></h3>
<p>In TCP mode the backend sees HAProxy&rsquo;s IP, not the client&rsquo;s, and there are no headers to add <code>X-Forwarded-For</code> to. The PROXY protocol passes client information through TCP load balancers by sending a short header before the data:</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend tcp_frontend
    bind *:5432
    default_backend tcp_servers

backend tcp_servers
    server s1 192.168.1.10:5432 check send-proxy-v2
</code></pre><p>The backend server must support PROXY protocol, or it reads the header as garbage and drops the connection. For HAProxy as the backend:</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend backend_frontend
    bind *:5432 accept-proxy
    # ...
</code></pre><h2 id="logging">Logging <a class="anchor" data-pagefind-ignore href="#logging" aria-label="Link to this section">#</a></h2>
<h3 id="tcp-specific-logging">TCP-Specific Logging <a class="anchor" data-pagefind-ignore href="#tcp-specific-logging" aria-label="Link to this section">#</a></h3>
<p><code>option tcplog</code> logs one line per connection. The custom <code>log-format</code> adds timings and connection counts.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">global
    log 127.0.0.1:514 local0 info

defaults
    mode tcp
    option tcplog
    log global

# Custom TCP log format
frontend tcp_frontend
    bind *:5432
    log-format &#34;%ci:%cp [%t] %ft %b/%s %Tw/%Tc/%Tt %B %ts %ac/%fc/%bc/%sc/%rc %sq/%bq&#34;
</code></pre><p>Log format variables for TCP:</p>
<ul>
<li><code>%ci</code>: Client IP</li>
<li><code>%cp</code>: Client port</li>
<li><code>%ft</code>: Frontend name</li>
<li><code>%b</code>: Backend name</li>
<li><code>%s</code>: Server name</li>
<li><code>%Tw</code>: Time waiting in queue (ms)</li>
<li><code>%Tc</code>: Time to connect to server (ms)</li>
<li><code>%Tt</code>: Total time (ms)</li>
<li><code>%B</code>: Bytes read from server</li>
<li><code>%ts</code>: Termination state</li>
</ul>
<p>HAProxy sends logs to syslog on UDP 514. Configure rsyslog to receive them and write <code>local0</code> to a file:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># /etc/rsyslog.d/haproxy.conf</span>
</span></span><span class="line"><span class="cl"><span class="nv">$ModLoad</span> imudp
</span></span><span class="line"><span class="cl"><span class="nv">$UDPServerRun</span> <span class="m">514</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">local0.* /var/log/haproxy.log
</span></span></code></pre></div><h2 id="statistics-and-monitoring">Statistics and Monitoring <a class="anchor" data-pagefind-ignore href="#statistics-and-monitoring" aria-label="Link to this section">#</a></h2>
<p>The stats page is HTTP even when all your proxies are TCP, so it sets <code>mode http</code> itself.</p>
<h3 id="stats-page">Stats Page <a class="anchor" data-pagefind-ignore href="#stats-page" aria-label="Link to this section">#</a></h3>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend stats
    bind *:8404
    mode http
    stats enable
    stats uri /stats
    stats refresh 10s
    stats admin if LOCALHOST
</code></pre><h3 id="prometheus-metrics">Prometheus Metrics <a class="anchor" data-pagefind-ignore href="#prometheus-metrics" aria-label="Link to this section">#</a></h3>
<p>See <a href="https://blog.bsdserver.nl/haproxy-monitoring-with-prometheus-complete-observability-guide/">HAProxy Monitoring with Prometheus</a> for scraping and alerting.</p>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy">frontend stats
    bind *:8404
    mode http
    http-request use-service prometheus-exporter if { path /metrics }
</code></pre><h2 id="complete-production-example">Complete Production Example <a class="anchor" data-pagefind-ignore href="#complete-production-example" aria-label="Link to this section">#</a></h2>
<p>A complete configuration for a PostgreSQL cluster and Redis:</p>
<table>
	<thead>
			<tr>
					<th>Frontend</th>
					<th>Port</th>
					<th>Backend</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>pg_write</code></td>
					<td>5432</td>
					<td>Primary, standby as backup; over 5000 connections are rejected</td>
			</tr>
			<tr>
					<td><code>pg_read</code></td>
					<td>5433</td>
					<td>Standbys with <code>leastconn</code>, primary as backup</td>
			</tr>
			<tr>
					<td><code>redis</code></td>
					<td>6379</td>
					<td>Only the server reporting <code>role:master</code> passes the check</td>
			</tr>
			<tr>
					<td><code>stats</code></td>
					<td>8404</td>
					<td>Stats page and <code>/metrics</code></td>
			</tr>
	</tbody>
</table>
<p>Settings worth knowing:</p>
<ul>
<li><code>option redispatch</code>: retry on another server if the chosen one fails.</li>
<li><code>option log-health-checks</code>: log health check state changes.</li>
<li><code>pgsql-check</code> checks that PostgreSQL answers, not whether it is the primary.</li>
</ul>
<pre tabindex="0"><code class="language-haproxy" data-lang="haproxy"># /etc/haproxy/haproxy.cfg

global
    log /dev/log local0
    log /dev/log local1 notice
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners
    stats timeout 30s
    user haproxy
    group haproxy
    daemon
    
    maxconn 100000
    nbthread 4
    cpu-map auto:1/1-4 0-3
    
    # Security
    ssl-default-bind-ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256
    ssl-default-bind-options ssl-min-ver TLSv1.2 no-tls-tickets

defaults
    log     global
    mode    tcp
    option  tcplog
    option  dontlognull
    option  log-health-checks
    
    timeout connect 5s
    timeout client  3600s
    timeout server  3600s
    timeout check   3s
    
    retries 3
    option  redispatch
    
    default-server inter 3s fall 3 rise 2

# Stats frontend
listen stats
    bind *:8404
    mode http
    stats enable
    stats uri /stats
    stats refresh 10s
    stats admin if LOCALHOST
    http-request use-service prometheus-exporter if { path /metrics }

# PostgreSQL Primary (Read/Write)
frontend pg_write
    bind *:5432
    default_backend pg_primary
    
    # ACL for connection limiting
    acl too_many_conns fe_conn gt 5000
    tcp-request connection reject if too_many_conns

backend pg_primary
    option pgsql-check user haproxy
    server pg-primary 192.168.1.10:5432 check
    server pg-standby1 192.168.1.11:5432 check backup

# PostgreSQL Replicas (Read-Only)
frontend pg_read
    bind *:5433
    default_backend pg_replicas

backend pg_replicas
    balance leastconn
    option pgsql-check user haproxy
    server pg-standby1 192.168.1.11:5432 check
    server pg-standby2 192.168.1.12:5432 check
    server pg-primary  192.168.1.10:5432 check backup  # Fallback

# Redis Cluster
frontend redis
    bind *:6379
    default_backend redis_servers

backend redis_servers
    balance first
    option tcp-check
    tcp-check connect
    tcp-check send &#34;PING\r\n&#34;
    tcp-check expect string +PONG
    tcp-check send &#34;INFO replication\r\n&#34;
    tcp-check expect string role:master
    tcp-check send &#34;QUIT\r\n&#34;
    tcp-check expect string +OK
    server redis1 192.168.1.20:6379 check
    server redis2 192.168.1.21:6379 check
    server redis3 192.168.1.22:6379 check
</code></pre><h2 id="validation-and-testing">Validation and Testing <a class="anchor" data-pagefind-ignore href="#validation-and-testing" aria-label="Link to this section">#</a></h2>
<h3 id="configuration-validation">Configuration Validation <a class="anchor" data-pagefind-ignore href="#configuration-validation" aria-label="Link to this section">#</a></h3>
<p>Check the syntax before every reload.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">haproxy -c -f /etc/haproxy/haproxy.cfg
</span></span></code></pre></div><h3 id="load-testing">Load Testing <a class="anchor" data-pagefind-ignore href="#load-testing" aria-label="Link to this section">#</a></h3>
<p>Open many connections at once, then run a real database benchmark through HAProxy.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Test TCP connection throughput</span>
</span></span><span class="line"><span class="cl"><span class="k">for</span> i in <span class="o">{</span>1..100<span class="o">}</span><span class="p">;</span> <span class="k">do</span>
</span></span><span class="line"><span class="cl">  nc -z -w1 haproxy.example.com <span class="m">5432</span> <span class="p">&amp;</span>
</span></span><span class="line"><span class="cl"><span class="k">done</span>
</span></span><span class="line"><span class="cl"><span class="nb">wait</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># PostgreSQL specific (initialise the pgbench tables once first)</span>
</span></span><span class="line"><span class="cl">pgbench -i -h haproxy.example.com -p <span class="m">5432</span> mydb
</span></span><span class="line"><span class="cl">pgbench -h haproxy.example.com -p <span class="m">5432</span> -c <span class="m">50</span> -j <span class="m">4</span> -T <span class="m">60</span> mydb
</span></span></code></pre></div><h2 id="troubleshooting">Troubleshooting <a class="anchor" data-pagefind-ignore href="#troubleshooting" aria-label="Link to this section">#</a></h2>
<h3 id="common-issues">Common Issues <a class="anchor" data-pagefind-ignore href="#common-issues" aria-label="Link to this section">#</a></h3>
<table>
	<thead>
			<tr>
					<th>Symptom</th>
					<th>Cause / fix</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Connections dropped after idle time</td>
					<td>Increase <code>timeout server</code> and <code>timeout client</code></td>
			</tr>
			<tr>
					<td>Server marked DOWN</td>
					<td>Check health check configuration and network connectivity</td>
			</tr>
			<tr>
					<td>Connection refused</td>
					<td>Verify backend servers are listening and firewall rules</td>
			</tr>
			<tr>
					<td>Slow connections</td>
					<td>Check <code>balance</code> algorithm and server capacity</td>
			</tr>
			<tr>
					<td>HAProxy does not start on RHEL</td>
					<td>Missing <code>/run/haproxy</code>; see the <code>RuntimeDirectory</code> fix above</td>
			</tr>
	</tbody>
</table>
<h3 id="debug-mode">Debug Mode <a class="anchor" data-pagefind-ignore href="#debug-mode" aria-label="Link to this section">#</a></h3>
<p><code>haproxy -d</code> runs in the foreground and prints every event. The socket commands show process info, per-server stats and the last protocol errors.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># Run HAProxy in debug mode</span>
</span></span><span class="line"><span class="cl">haproxy -d -f /etc/haproxy/haproxy.cfg
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># Check runtime status</span>
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;show info&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;show stat&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span><span class="line"><span class="cl"><span class="nb">echo</span> <span class="s2">&#34;show errors&#34;</span> <span class="p">|</span> socat stdio /run/haproxy/admin.sock
</span></span></code></pre></div><h2 id="automate-it">Automate it <a class="anchor" data-pagefind-ignore href="#automate-it" aria-label="Link to this section">#</a></h2>
<p>The Ansible roles and Terraform code that build this setup are on GitHub:
<a href="https://github.com/pderuiter/blog-haproxy-tcp-lb" rel="noopener">pderuiter/blog-haproxy-tcp-lb</a>. It creates an HAProxy VM on Proxmox and configures the complete production example from this post, PostgreSQL read/write and read-only frontends and the Redis master check included; set your database and Redis servers in <code>group_vars</code>, run <code>terraform apply</code>, then <code>ansible-playbook site.yml</code>.</p>
<h2 id="next-steps">Next Steps <a class="anchor" data-pagefind-ignore href="#next-steps" aria-label="Link to this section">#</a></h2>
<p>Next in the series: DNS load balancing with HAProxy, to spread DNS queries across multiple resolvers.</p>
<h2 id="summary">Summary <a class="anchor" data-pagefind-ignore href="#summary" aria-label="Link to this section">#</a></h2>
<p>Key takeaways:</p>
<ul>
<li>Use <code>mode tcp</code> for Layer 4 load balancing</li>
<li>Choose the right balancing algorithm for your use case</li>
<li>Implement proper health checks for each protocol</li>
<li>Configure appropriate timeouts for your workload</li>
<li>Use the stats socket for runtime management</li>
<li>Enable logging for troubleshooting and monitoring</li>
</ul>
<p>TCP load balancing is the building block for highly available infrastructure, whether you&rsquo;re running databases, message queues, or custom services.</p>
]]></content:encoded></item></channel></rss>