HAProxy TCP Load Balancing for Databases
Read/write split and Sentinel routing.
TCP Load Balancing for Database Workloads
While HAProxy is best known for HTTP load balancing, its Layer 4 (TCP) capabilities make it an excellent database proxy. TCP mode enables read/write splitting for PostgreSQL, Redis Sentinel routing, and MySQL cluster load balancing — all without application changes.
PostgreSQL Read/Write Splitting
Route writes to the primary and reads to replicas using HAProxy's TCP health checks:
listen postgres_write
bind *:5432
mode tcp
option pgsql-check user haproxy
default-server inter 3s fall 3 rise 2
server pg-primary 10.0.1.10:5432 check
listen postgres_read
bind *:5433
mode tcp
balance leastconn
option pgsql-check user haproxy
default-server inter 3s fall 3 rise 2
server pg-replica1 10.0.1.11:5432 check
server pg-replica2 10.0.1.12:5432 check
server pg-primary 10.0.1.10:5432 check backupThe option pgsql-check directive performs actual PostgreSQL protocol health checks, detecting not just TCP connectivity but database readiness.
Redis Sentinel Routing
Route Redis traffic to the current master using an external check script:
listen redis_master
bind *:6379
mode tcp
balance first
option tcp-check
tcp-check connect
tcp-check send "PING\r\n"
tcp-check expect string +PONG
tcp-check send "INFO replication\r\n"
tcp-check expect string role:master
tcp-check send "QUIT\r\n"
tcp-check expect string +OK
server redis1 10.0.1.20:6379 check inter 2s
server redis2 10.0.1.21:6379 check inter 2s
server redis3 10.0.1.22:6379 check inter 2sThis configuration actively checks each Redis node's replication role and only routes to the current master.
MySQL Group Replication
listen mysql_cluster
bind *:3306
mode tcp
balance roundrobin
option mysql-check user haproxy
server mysql1 10.0.1.30:3306 check
server mysql2 10.0.1.31:3306 check
server mysql3 10.0.1.32:3306 checkConnection Limits and Timeouts
Database connections are long-lived compared to HTTP. Tune HAProxy accordingly:
defaults
mode tcp
timeout connect 5s
timeout client 30m
timeout server 30m
timeout check 5s
listen postgres_write
bind *:5432
maxconn 200
default-server maxconn 100The 30-minute client/server timeouts accommodate long-running queries, while maxconn prevents connection exhaustion on database backends.
Monitoring Database Backends
Key metrics to track via the HAProxy stats page:
- Current sessions — Monitor connection pool utilization
- Backend health — Detect replica lag or failures
- Connection queue — Identify when backends are saturated
- Response time — Track TCP connection establishment time
Eazy SaaS Tip: We combine HAProxy TCP load balancing with PgBouncer connection pooling for PostgreSQL deployments. This dual-layer approach provides both high availability and efficient connection management for applications with thousands of concurrent users.