Configure application connection pooling for CockroachDB with PgBouncer and HAProxy

Intermediate 45 min Apr 05, 2026 127 views
Ubuntu 24.04 Debian 12 AlmaLinux 9 Rocky Linux 9

Set up efficient connection pooling for CockroachDB applications using PgBouncer as a connection pool manager and HAProxy for load balancing across multiple database nodes. This configuration reduces database connection overhead and improves application performance.

Prerequisites

  • Root or sudo access
  • Running CockroachDB cluster
  • Basic understanding of SQL databases
  • Network connectivity between nodes

What this solves

CockroachDB applications can overwhelm database nodes with too many concurrent connections, leading to performance degradation and connection errors. This tutorial configures PgBouncer to pool and reuse database connections efficiently, while HAProxy distributes traffic across multiple CockroachDB nodes for high availability and load distribution.

Step-by-step configuration

Update system packages

Start by updating your package manager to ensure you have the latest versions of all packages.

sudo apt update && sudo apt upgrade -y
sudo dnf update -y

Install PgBouncer and HAProxy

Install both PgBouncer for connection pooling and HAProxy for load balancing CockroachDB nodes.

sudo apt install -y pgbouncer haproxy
sudo dnf install -y pgbouncer haproxy

Create PgBouncer user database file

Create a user authentication file for PgBouncer to authenticate with CockroachDB. Replace the password with your actual CockroachDB user password.

sudo mkdir -p /etc/pgbouncer
sudo touch /etc/pgbouncer/userlist.txt
sudo chown pgbouncer:pgbouncer /etc/pgbouncer/userlist.txt
sudo chmod 600 /etc/pgbouncer/userlist.txt

Add your CockroachDB user credentials to the userlist file:

"myapp" "md5a1b2c3d4e5f6789abc123def456789ab"
Note: Generate the MD5 hash using: echo -n 'passwordusername' | md5sum and prefix with "md5".

Configure HAProxy for CockroachDB load balancing

Configure HAProxy to distribute connections across multiple CockroachDB nodes with health checks. This configuration provides load balancing and automatic failover.

global
    log stdout local0
    chroot /var/lib/haproxy
    stats socket /run/haproxy/admin.sock mode 660 level admin
    stats timeout 30s
    user haproxy
    group haproxy
    daemon

defaults
    mode tcp
    timeout connect 5000ms
    timeout client 50000ms
    timeout server 50000ms
    log global
    option tcplog
    option dontlognull

frontend cockroachdb_frontend
    bind *:26257
    default_backend cockroachdb_backend

backend cockroachdb_backend
    balance roundrobin
    option tcp-check
    tcp-check connect
    server crdb1 203.0.113.10:26257 check
    server crdb2 203.0.113.11:26257 check
    server crdb3 203.0.113.12:26257 check

frontend stats
    bind *:8404
    stats enable
    stats uri /stats
    stats refresh 30s

Configure PgBouncer for connection pooling

Configure PgBouncer to pool connections efficiently. This configuration uses transaction pooling for optimal performance with CockroachDB.

[databases]
myappdb = host=127.0.0.1 port=26257 dbname=myappdb user=myapp

[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt
logfile = /var/log/postgresql/pgbouncer.log
pidfile = /var/run/postgresql/pgbouncer.pid
admin_users = pgbouncer
stats_users = pgbouncer
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 25
max_db_connections = 100
reserve_pool_size = 10
reserve_pool_timeout = 3
max_prepared_statements = 0
server_reset_query = DISCARD ALL
server_check_query = SELECT 1
server_lifetime = 3600
server_idle_timeout = 600
log_connections = 1
log_disconnections = 1
log_pooler_errors = 1

Create PgBouncer systemd service

Create a proper systemd service file for PgBouncer to ensure it starts automatically and runs with correct permissions.

[Unit]
Description=PgBouncer connection pooler
After=network.target

[Service]
Type=notify
User=pgbouncer
Group=pgbouncer
ExecStart=/usr/sbin/pgbouncer /etc/pgbouncer/pgbouncer.ini
ExecReload=/bin/kill -HUP $MAINPID
KillMode=mixed
TimeoutSec=120
Restart=on-failure

[Install]
WantedBy=multi-user.target

Set proper file permissions

Configure correct ownership and permissions for PgBouncer files to ensure security and proper operation.

sudo chown -R pgbouncer:pgbouncer /etc/pgbouncer
sudo chmod 644 /etc/pgbouncer/pgbouncer.ini
sudo chmod 600 /etc/pgbouncer/userlist.txt
sudo mkdir -p /var/log/postgresql
sudo chown pgbouncer:pgbouncer /var/log/postgresql
Never use chmod 777. It gives every user on the system full access to your files. Instead, fix ownership with chown and use minimal permissions like 644 for config files and 600 for sensitive files.

Configure firewall rules

Open the necessary ports for HAProxy and PgBouncer while maintaining security. HAProxy uses port 26257 for CockroachDB connections and 8404 for stats.

sudo ufw allow 26257/tcp comment 'CockroachDB via HAProxy'
sudo ufw allow 6432/tcp comment 'PgBouncer'
sudo ufw allow 8404/tcp comment 'HAProxy Stats'
sudo ufw reload
sudo firewall-cmd --permanent --add-port=26257/tcp
sudo firewall-cmd --permanent --add-port=6432/tcp
sudo firewall-cmd --permanent --add-port=8404/tcp
sudo firewall-cmd --reload

Enable and start services

Start both HAProxy and PgBouncer services and enable them to start automatically on boot.

sudo systemctl daemon-reload
sudo systemctl enable --now haproxy
sudo systemctl enable --now pgbouncer
sudo systemctl status haproxy
sudo systemctl status pgbouncer

Configure application connection string

Update your application to connect through PgBouncer instead of directly to CockroachDB. This provides connection pooling benefits.

postgresql://myapp:password@localhost:6432/myappdb?sslmode=disable
Note: Applications connect to PgBouncer on port 6432, which then manages connections to CockroachDB via HAProxy on port 26257.

Optimize connection pool settings

Tune PgBouncer pool sizes

Adjust pool sizes based on your application's connection patterns and server resources. Start with conservative values and monitor performance.

# Connection pool tuning
default_pool_size = 25          # Connections per user/database
max_db_connections = 100        # Max connections to CockroachDB
reserve_pool_size = 10          # Emergency connections
max_client_conn = 1000          # Max client connections
server_lifetime = 3600          # Connection lifetime (1 hour)
server_idle_timeout = 600       # Idle timeout (10 minutes)

Configure HAProxy connection limits

Set appropriate connection limits and timeouts in HAProxy to prevent overwhelming CockroachDB nodes.

# Add to backend section
backend cockroachdb_backend
    balance roundrobin
    option tcp-check
    tcp-check connect
    maxconn 500
    server crdb1 203.0.113.10:26257 check maxconn 150
    server crdb2 203.0.113.11:26257 check maxconn 150
    server crdb3 203.0.113.12:26257 check maxconn 150

Monitor connection pool performance

Monitor PgBouncer statistics

Connect to PgBouncer's admin console to monitor pool usage and performance metrics in real-time.

psql -h 127.0.0.1 -p 6432 -U pgbouncer pgbouncer

Inside PgBouncer admin console:

SHOW STATS; SHOW POOLS; SHOW CLIENTS; SHOW SERVERS;

Monitor HAProxy statistics

Access HAProxy statistics dashboard to monitor backend server health and connection distribution.

# View HAProxy stats in browser
http://your-server:8404/stats

Or check via command line

echo "show stat" | socat stdio /run/haproxy/admin.sock

Verify your setup

# Check service status
sudo systemctl status haproxy pgbouncer

Test connection through PgBouncer

psql -h 127.0.0.1 -p 6432 -U myapp -d myappdb -c "SELECT version();"

Check PgBouncer pool statistics

psql -h 127.0.0.1 -p 6432 -U pgbouncer pgbouncer -c "SHOW STATS;"

Verify HAProxy backend health

curl -s http://localhost:8404/stats | grep cockroachdb_backend

Common issues

SymptomCauseFix
PgBouncer won't startIncorrect file permissionssudo chown pgbouncer:pgbouncer /etc/pgbouncer/*
Authentication failedWrong MD5 hash in userlistRegenerate hash: echo -n 'passwordusername' | md5sum
HAProxy backend downCockroachDB node unreachableCheck CockroachDB service and network connectivity
Connection pool exhaustedPool size too smallIncrease default_pool_size and max_db_connections
High connection latencyInefficient pool modeUse pool_mode = transaction for better throughput
SSL connection errorsSSL mismatch between layersConfigure SSL consistently across PgBouncer and HAProxy

Next steps

Automated install script

Run this to automate the entire setup

Need help?

Don't want to manage this yourself?

We handle high availability infrastructure for businesses that depend on uptime. From initial setup to ongoing operations.