Vous avez un cluster Postgres 16 en réplication par streaming — un primaire, deux standbys — et une application qui ouvre une nouvelle connexion par requête HTTP, pousse ~600 connexions par seconde via psycopg et envoie chaque SELECT au primaire parce que personne n’a câblé la logique read-replica dans la couche d’accès aux données. Le primaire est OK côté CPU mais passe du vrai temps à servir le handshake des connexions, et les deux réplicas restent essentiellement au repos. pgpool-II se place devant le cluster comme connection pooler (devant Postgres, à la manière de pgBouncer) et comme load balancer conscient des requêtes qui parse chaque statement, décide si c’est une lecture ou une écriture et route en conséquence. L’application se connecte à une seule adresse, obtient une session poolée et les lectures se répartissent naturellement entre les standbys.
Ce qui se passe
pgpool-II est un middleware entre les connexions applicatives et le cluster Postgres. Trois comportements qui comptent en opération :
- Pool de connexions. Comme pgBouncer en mode session (défaut) ou en pooling stateful (option). Les apps qui ouvrent des connexions courtes voient un handshake local à faible latence au lieu de taper Postgres à chaque fois. Protection anti-tempête de connexions.
- Read/write split. pgpool parse le SQL et classe chaque statement. Tout ce qui ouvre une transaction par
BEGIN/START TRANSACTIONou contient une écriture (INSERT,UPDATE,DELETE,CREATE, etc.) est épinglé sur le primaire. UnSELECTpur hors transaction peut être routé vers un standby, pondéré par lebackend_weightque vous fixez par nœud. La chaîne de connexion de l’application ne change pas. - Watchdog (optionnel). Plusieurs nœuds pgpool élisent un leader et présentent une IP virtuelle, pour que la couche pgpool elle-même ne soit pas un single point of failure. La variante de cet article place pgpool-II devant un cluster Postgres déjà HA, avec deux nœuds pgpool + watchdog pour la couche pgpool elle-même.
Les pièges qui mordent les opérateurs après déploiement :
black_query_pattern_listet correction du load-balance. pgpool doit savoir quelles fonctions dans votre SQL sont read-only et lesquelles mutent l’état. Les fonctions custom valent par défaut « envoyer au primaire » sauf indication contraire. Si l’app appelle une fonction SQL customget_user_dashboard()qui ne fait que des lectures, mettez-la danswhite_function_listpour qu’elle soit load-balancée.- Une lecture dans une transaction part toujours sur le primaire. C’est voulu — un bloc
BEGIN; SELECT ...; UPDATE ...; COMMITdoit être cohérent. Les applications qui utilisent des transactions explicites longues pour du read-only ne bénéficieront pas du load balancing. Refactorez-les en lectures autocommit. - Authentification. pgpool peut faire du
scram-sha-256de bout en bout mais cela exigeallow_clear_text_frontend_auth = offplus un bonpool_hba.conf. Ratez ça et soit l’auth client échoue, soit pgpool retombe en clear text — aucun des deux acceptable sur un réseau privé sans TLS. failover_command. pgpool peut détecter un backend mort et arrêter de l’utiliser, mais la promotion réelle d’un standby dans votre couche Postgres reste gérée par Patroni /repmgr/ un runbook humain. Le rôle de pgpool est « arrêter d’utiliser celui qui est mort » ; le rôle du cluster est d’élire un nouveau primaire.
Comment vérifier
Depuis n’importe quel nœud pgpool :
# 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 doit être nettement penché vers les standbys. Sinon, le load balancing n’a pas lieu — vérifiez load_balance_mode = on et les valeurs de backend_weight, et confirmez que les requêtes sont bien load-balanceables.
Confirmez qu’un SELECT part sur un standby :
psql -h 127.0.0.1 -p 9999 -U app -d app -c \
"SELECT inet_server_addr(), pg_is_in_recovery();"
Si pg_is_in_recovery() retourne t, vous êtes sur un standby. Répétez dix fois — vous devez voir un mélange d’IPs de standby.
Taille de pool et usage courant :
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;"
État du watchdog (seulement si activé entre plusieurs nœuds pgpool) :
pcp_watchdog_info -h 127.0.0.1 -p 9898 -U pcpadmin
Le correctif
Lancez l’installeur sur chacun des deux nœuds pgpool (un seul nœud suffit pour tester ; deux nœuds + watchdog est la configuration de production). Le cluster Postgres derrière est supposé déjà en place — primaire en PG_PRIMARY_IP, standbys en PG_STANDBY1_IP et PG_STANDBY2_IP, avec utilisateur replicator, auth scram-sha-256 et pg_hba.conf déjà ouvert pour les IPs des nœuds pgpool.
#!/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"
Quelques notes opérationnelles pour l’équipe qui reprend. Le dimensionnement du pool est la mauvaise configuration la plus fréquente. num_init_children = 96 et max_pool = 4 veut dire jusqu’à 384 connexions backend simultanées — suffisant pour la plupart des apps mais facile à dépasser en cas de x10 sur le trafic. À cadrer contre le max_connections du primaire (dans postgresql.conf), et rappelez-vous que chaque nœud pgpool apporte son propre pool, donc deux nœuds pgpool = jusqu’à 768 connexions backend cumulées. Soit on dimensionne max_connections du primaire en conséquence, soit on place pgBouncer en transaction-pooling derrière pgpool pour une compression plus serrée — oui, deux poolers en série est une topologie légitime pour des taux de connexion très élevés.
Le watchdog concerne la couche pgpool ; il ne promeut pas Postgres. Le failover_command de cette configuration se contente de loguer et retourne 0. Votre couche Postgres HA (Patroni ou repmgr) est ce qui promeut un standby. pgpool remarquera le nouveau primaire à son prochain sr_check_period et reroutera les écritures vers le bon hôte.
Si votre app tape l’épuisement de pool ou si vos réplicas tournent au ralenti pendant que le primaire transpire, notre équipe Cloud PaaS intègre pgpool-II au plan environnements infogérés avec alertes d’utilisation de pool et baseline dimensionnée selon le trafic — planifiez un appel de cadrage pour préparer la mise en place.