You have a Postgres 16 streaming-replication cluster — one primary, two standbys — and an application that opens a new connection for every HTTP request, slams ~600 connections per second through psycopg, and routes every SELECT to the primary because nobody wrote the read-replica logic into the data-access layer. The primary is fine on CPU but spends real time servicing connection setup, and the two replicas mostly idle. pgpool-II sits in front of the cluster as both a connection pooler (in front of Postgres, the way pgBouncer does) and a query-aware load balancer that parses every statement, decides whether it’s a read or a write, and routes accordingly. The application connects to one address, gets a pooled session, and reads naturally spread across the standbys.
What’s happening
pgpool-II is a middleware between application connections and the Postgres cluster. Three behaviors that matter operationally:
- Connection pool. Like pgBouncer in session mode (default) or stateful pooling (option). Applications opening short-lived connections see a low-latency local handshake instead of hitting Postgres every time. Connection-storm protection.
- Read/write split. pgpool parses SQL and classifies each statement. Anything that starts a transaction with
BEGIN/START TRANSACTIONor contains a write (INSERT,UPDATE,DELETE,CREATE, etc.) is pinned to the primary. PureSELECToutside a transaction can be routed to a standby, weighted by thebackend_weightyou set per node. The application’s connection string doesn’t change. - Watchdog (optional). Multiple pgpool nodes elect a leader and present a virtual IP so the pgpool layer itself isn’t a single point of failure. The variant in this article uses pgpool-II in front of an already HA Postgres cluster, with two pgpool nodes + watchdog for the pgpool layer itself.
The pieces of this that bite operators after deployment:
black_query_pattern_listand load-balance correctness. pgpool needs to know which functions in your SQL are read-only and which mutate state. Custom functions default to “send to primary” unless you tell pgpool otherwise. If your app calls a customget_user_dashboard()SQL function that does only reads, setwhite_function_listso it gets load-balanced.- In-transaction reads always go to the primary. That’s by design — a
BEGIN; SELECT ...; UPDATE ...; COMMITblock has to be coherent. Applications that use long-running explicit transactions for read-only work won’t benefit from load balancing. Refactor those into autocommit-style reads. - Authentication. pgpool can do
scram-sha-256end-to-end but it requiresallow_clear_text_frontend_auth = offplus the rightpool_hba.conf. Get this wrong and either the client auth fails or pgpool falls back to clear text — neither acceptable on a private network without TLS. failover_command. pgpool can detect a dead backend and stop routing to it, but the actual promotion of a standby in your Postgres layer is still handled by Patroni /repmgr/ a human runbook. pgpool’s job is “stop using the dead one”; the cluster’s job is to elect a new primary.
How to verify
From any pgpool node:
# Backend state from pgpool's point of view
psql -h 127.0.0.1 -p 9999 -U postgres -d postgres -c "SHOW pool_nodes;"
# node_id | hostname | port | status | pg_status | lb_weight | role | pg_role | select_cnt
# ---------+--------------+------+--------+-----------+-----------+---------+---------+------------
# 0 | 10.50.0.11 | 5432 | up | up | 0.500000 | primary | primary | 12345
# 1 | 10.50.0.12 | 5432 | up | up | 1.500000 | standby | standby | 50412
# 2 | 10.50.0.13 | 5432 | up | up | 1.500000 | standby | standby | 49887
select_cnt should be heavily skewed toward the standbys. If it’s not, load balancing is not happening — check load_balance_mode = on and backend_weight values, and verify the SQL is actually a load-balanceable statement.
Confirm a SELECT is going to a standby:
psql -h 127.0.0.1 -p 9999 -U app -d app -c \
"SELECT inet_server_addr(), pg_is_in_recovery();"
If pg_is_in_recovery() returns t, you’re on a standby. Repeat ten times — you should see a mix of standby IPs.
Pool size and current usage:
psql -h 127.0.0.1 -p 9999 -U postgres -d postgres -c "SHOW pool_processes;"
psql -h 127.0.0.1 -p 9999 -U postgres -d postgres -c "SHOW pool_pools;"
Watchdog status (only if you’ve enabled it across multiple pgpool nodes):
pcp_watchdog_info -h 127.0.0.1 -p 9898 -U pcpadmin
The fix
Run the installer on each of the two pgpool nodes (a single pgpool node works for testing; two-node + watchdog is the production setup). The Postgres cluster behind it is assumed to exist — primary at PG_PRIMARY_IP, standbys at PG_STANDBY1_IP and PG_STANDBY2_IP, with replicator user, scram-sha-256 auth, and pg_hba.conf already opened for the pgpool node IPs.
#!/usr/bin/env bash
set -euo pipefail
### Ubuntu 22.04 — pgpool-II 4.5 in front of Postgres 16 streaming cluster
### Run on each of the 2 pgpool nodes after editing the variables
if [[ "$(id -u)" -ne 0 ]]; then
echo "Run as root."
exit 1
fi
# === EDIT PER NODE ===
NODE_NAME="pgpool1"
NODE_IP="10.50.0.31"
PEER_PGPOOL_IPS=("10.50.0.31" "10.50.0.32")
PEER_PGPOOL_NAMES=("pgpool1" "pgpool2")
WATCHDOG_VIP="10.50.0.30" # virtual IP shared by pgpool nodes
WATCHDOG_INTERFACE="eth0"
PG_PRIMARY_IP="10.50.0.11"
PG_STANDBY1_IP="10.50.0.12"
PG_STANDBY2_IP="10.50.0.13"
PG_PORT=5432
APP_USER="app"
APP_USER_PASSWORD_SCRAM="SCRAM-SHA-256\$4096:..." # full SCRAM-SHA-256 verifier
HEALTH_USER="pgpool_health"
HEALTH_PASSWORD="CHANGE_ME_HEALTH"
SR_USER="replicator"
SR_PASSWORD="CHANGE_ME_REPL"
PCP_USER="pcpadmin"
PCP_PASSWORD="CHANGE_ME_PCP"
PRIVATE_SUBNET="10.50.0.0/16"
# =====================
echo
echo "========================================"
echo "pgpool-II ${NODE_NAME} (${NODE_IP})"
echo "========================================"
echo
echo "==> Base OS update"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get upgrade -y
apt-get install -y curl ca-certificates gnupg lsb-release \
ufw fail2ban unattended-upgrades chrony jq lsof net-tools
systemctl enable --now chrony
echo "==> Hardening SSH"
sed -i 's|^[#[:space:]]*PermitRootLogin.*|PermitRootLogin prohibit-password|' /etc/ssh/sshd_config
sed -i 's|^[#[:space:]]*PasswordAuthentication.*|PasswordAuthentication no|' /etc/ssh/sshd_config
sshd -t && systemctl restart ssh
echo "==> Sysctl + limits for a pooling layer"
cat > /etc/sysctl.d/99-pgpool.conf <<'SYSCTL'
net.core.somaxconn = 4096
net.ipv4.tcp_max_syn_backlog = 8192
net.ipv4.ip_local_port_range = 10240 65535
fs.file-max = 2097152
net.ipv4.tcp_syncookies = 1
SYSCTL
sysctl --system
cat > /etc/security/limits.d/99-pgpool.conf <<'LIMITS'
pgpool soft nofile 200000
pgpool hard nofile 200000
LIMITS
echo "==> PGDG repo + pgpool-II + postgresql-client"
install -d -m 0755 /etc/apt/keyrings
curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \
| gpg --dearmor -o /etc/apt/keyrings/postgresql.gpg
echo "deb [signed-by=/etc/apt/keyrings/postgresql.gpg] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \
> /etc/apt/sources.list.d/pgdg.list
apt-get update -y
apt-get install -y pgpool2 postgresql-client-16
systemctl stop pgpool2 || true
echo "==> /etc/pgpool2/pgpool.conf"
cat > /etc/pgpool2/pgpool.conf <<EOF
listen_addresses = '*'
port = 9999
socket_dir = '/var/run/postgresql'
pcp_listen_addresses = '*'
pcp_port = 9898
pcp_socket_dir = '/var/run/postgresql'
backend_clustering_mode = 'streaming_replication'
# --- Backends ---
backend_hostname0 = '${PG_PRIMARY_IP}'
backend_port0 = ${PG_PORT}
backend_weight0 = 0
backend_data_directory0 = '/var/lib/postgresql/16/main'
backend_flag0 = 'ALLOW_TO_FAILOVER'
backend_hostname1 = '${PG_STANDBY1_IP}'
backend_port1 = ${PG_PORT}
backend_weight1 = 1
backend_data_directory1 = '/var/lib/postgresql/16/main'
backend_flag1 = 'ALLOW_TO_FAILOVER'
backend_hostname2 = '${PG_STANDBY2_IP}'
backend_port2 = ${PG_PORT}
backend_weight2 = 1
backend_data_directory2 = '/var/lib/postgresql/16/main'
backend_flag2 = 'ALLOW_TO_FAILOVER'
# --- Pool ---
num_init_children = 96
max_pool = 4
child_life_time = 300
child_max_connections = 0
connection_life_time = 0
client_idle_limit = 0
# --- Load balancing ---
load_balance_mode = on
ignore_leading_white_space = on
statement_level_load_balance = on
disable_load_balance_on_write = 'transaction'
# --- Authentication ---
enable_pool_hba = on
pool_passwd = 'pool_passwd'
authentication_timeout = 30
allow_clear_text_frontend_auth = off
# --- Streaming replication check ---
sr_check_period = 5
sr_check_user = '${HEALTH_USER}'
sr_check_password = '${HEALTH_PASSWORD}'
sr_check_database = 'postgres'
delay_threshold = 10485760
# --- Health check ---
health_check_period = 10
health_check_timeout = 20
health_check_user = '${HEALTH_USER}'
health_check_password = '${HEALTH_PASSWORD}'
health_check_database = 'postgres'
health_check_max_retries = 3
health_check_retry_delay = 1
# --- Failover (pgpool stops routing to dead backend) ---
failover_command = '/etc/pgpool2/failover.sh %d %h %p %D %m %H %M %P %r %R'
failback_command = ''
follow_primary_command = ''
search_primary_node_timeout = 0
# --- Logging ---
log_destination = 'syslog'
log_line_prefix = '%t: pid %p: '
log_connections = off
log_hostname = off
log_per_node_statement = off
log_standby_delay = 'if_over_threshold'
# --- Misc ---
serialize_accept = on
connection_cache = on
EOF
echo "==> /etc/pgpool2/pool_hba.conf — only accept private subnet, scram-sha-256"
cat > /etc/pgpool2/pool_hba.conf <<EOF
local all all trust
host all all 127.0.0.1/32 scram-sha-256
host all all ${PRIVATE_SUBNET} scram-sha-256
EOF
echo "==> /etc/pgpool2/pool_passwd — application user(s)"
# In real life: pg_enc -m -k <keyfile> -u <user> <password> writes here.
# For the installer we drop in the SCRAM verifier you provided.
cat > /etc/pgpool2/pool_passwd <<EOF
${APP_USER}:${APP_USER_PASSWORD_SCRAM}
EOF
chown pgpool:pgpool /etc/pgpool2/pool_passwd
chmod 600 /etc/pgpool2/pool_passwd
echo "==> /etc/pgpool2/pcp.conf"
PCP_MD5=$(printf '%s' "${PCP_PASSWORD}" | md5sum | awk '{print $1}')
echo "${PCP_USER}:${PCP_MD5}" > /etc/pgpool2/pcp.conf
chown pgpool:pgpool /etc/pgpool2/pcp.conf
chmod 600 /etc/pgpool2/pcp.conf
echo "==> /etc/pgpool2/failover.sh"
cat > /etc/pgpool2/failover.sh <<'FAILOVER'
#!/usr/bin/env bash
# Called when pgpool detects a dead backend.
# This does NOT promote a replica — that is the cluster's job
# (Patroni / repmgr / pg_auto_failover / human runbook).
# We just log loudly and let the cluster orchestrator do the promotion.
FAILED_NODE_ID="$1"
FAILED_HOST="$2"
FAILED_PORT="$3"
FAILED_DB_DIR="$4"
NEW_PRIMARY_ID="$5"
NEW_PRIMARY_HOST="$6"
OLD_PRIMARY_ID="$7"
OLD_PRIMARY_PORT="$8"
NEW_PRIMARY_PG_DATA="$9"
OLD_PRIMARY_HOST="${10}"
logger -t pgpool-failover "node ${FAILED_NODE_ID} (${FAILED_HOST}:${FAILED_PORT}) reported DOWN. new_primary_id=${NEW_PRIMARY_ID} new_primary_host=${NEW_PRIMARY_HOST}"
exit 0
FAILOVER
chmod 755 /etc/pgpool2/failover.sh
chown pgpool:pgpool /etc/pgpool2/failover.sh
echo "==> Adding watchdog block (only if 2+ pgpool nodes)"
NODE_INDEX=-1
for i in "${!PEER_PGPOOL_IPS[@]}"; do
if [[ "${PEER_PGPOOL_IPS[$i]}" == "${NODE_IP}" ]]; then
NODE_INDEX=$i
fi
done
cat >> /etc/pgpool2/pgpool.conf <<EOF
# --- Watchdog ---
use_watchdog = on
wd_hostname = '${NODE_IP}'
wd_port = 9000
wd_priority = $((10 - NODE_INDEX))
delegate_IP = '${WATCHDOG_VIP}'
if_up_cmd = '/usr/bin/sudo /sbin/ip addr add \$_IP_\$/24 dev ${WATCHDOG_INTERFACE} label ${WATCHDOG_INTERFACE}:0'
if_down_cmd = '/usr/bin/sudo /sbin/ip addr del \$_IP_\$/24 dev ${WATCHDOG_INTERFACE}'
arping_cmd = '/usr/bin/sudo /usr/sbin/arping -U \$_IP_\$ -w 1 -I ${WATCHDOG_INTERFACE}'
wd_lifecheck_method = 'heartbeat'
wd_interval = 10
wd_priority = $((10 - NODE_INDEX))
EOF
# Add each peer as a separate other_pgpool block
for i in "${!PEER_PGPOOL_IPS[@]}"; do
if [[ "${PEER_PGPOOL_IPS[$i]}" == "${NODE_IP}" ]]; then
continue
fi
cat >> /etc/pgpool2/pgpool.conf <<EOF
other_pgpool_hostname${i} = '${PEER_PGPOOL_IPS[$i]}'
other_pgpool_port${i} = 9999
other_wd_port${i} = 9000
heartbeat_hostname${i} = '${PEER_PGPOOL_IPS[$i]}'
heartbeat_port${i} = 9694
heartbeat_device${i} = '${WATCHDOG_INTERFACE}'
EOF
done
echo "==> sudoers for VIP commands"
cat > /etc/sudoers.d/pgpool <<'SUDO'
pgpool ALL=(root) NOPASSWD: /sbin/ip
pgpool ALL=(root) NOPASSWD: /usr/sbin/arping
SUDO
chmod 440 /etc/sudoers.d/pgpool
echo "==> ufw"
ufw --force reset
ufw default deny incoming
ufw default allow outgoing
ufw allow 22/tcp
ufw allow from ${PRIVATE_SUBNET} to any port 9999 proto tcp
ufw allow from ${PRIVATE_SUBNET} to any port 9898 proto tcp
ufw allow from ${PRIVATE_SUBNET} to any port 9000 proto tcp
ufw allow from ${PRIVATE_SUBNET} to any port 9694 proto udp
ufw --force enable
echo "==> Bringing pgpool up"
chown -R pgpool:pgpool /etc/pgpool2
systemctl enable --now pgpool2
sleep 3
echo
echo "========================================"
echo "DONE — ${NODE_NAME}"
echo "========================================"
echo
echo "Listeners:"
ss -lntp | grep -E ':(9999|9898|9000)\b' || true
echo
echo "Backends (run from this node):"
PGPASSWORD="${HEALTH_PASSWORD}" \
psql -h 127.0.0.1 -p 9999 -U "${HEALTH_USER}" -d postgres -c "SHOW pool_nodes;" || true
echo
echo "Application connects to: ${WATCHDOG_VIP}:9999"
A couple of operational notes for the team picking this up. Pool sizing is the most common misconfiguration. num_init_children = 96 and max_pool = 4 means up to 384 concurrent backend connections — enough for most apps but easy to outrun if you 10x traffic. Verify against the primary’s max_connections (set in postgresql.conf), and remember that each pgpool node contributes its own pool, so two pgpool nodes mean up to 768 backend connections combined. Either size the Postgres primary’s max_connections accordingly or put pgBouncer in transaction-pooling mode behind pgpool for tighter compression — yes, two poolers in series is a legitimate topology for very high connection rates.
Watchdog is for the pgpool layer; it does not promote Postgres. The failover_command in this config just logs and returns 0. Your Postgres HA layer (Patroni or repmgr) is what promotes a standby. pgpool will notice the new primary on its next sr_check_period and start routing writes to the right host.
If your app is hitting connection-pool exhaustion or your replicas are idle while your primary works hard, our Cloud PaaS team rolls pgpool-II into the environment management plan with pool-utilization alerts and a sized-against-traffic baseline — start a scoping call to plan the rollout.