Enrutamiento de conexiones con PgBouncer y HAProxy
Enrute los clientes al primario actual y distribuya el tráfico de lectura entre réplicas para mantener las aplicaciones disponibles durante las conmutaciones por error.
Enrutamiento de conexiones con PgBouncer y HAProxy es una lección gratuita de Advanced PostgreSQL: Indexing, Partitioning, Replication en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Advanced PostgreSQL: Indexing, Partitioning, Replication, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
The Routing Problem
After a failover the primary moves to a new host. Applications need a stable endpoint so they do not have to be reconfigured each time. Connection routing solves this.
PgBouncer Basics
PgBouncer is a lightweight connection pooler. It multiplexes many client connections onto a small set of server connections, reducing backend load.
Pooling Modes
PgBouncer offers three pool modes:
- session — connection held for the whole client session
- transaction — returned after each transaction (most common)
- statement — returned after each statement
Basic Config
A minimal pgbouncer.ini points at the database and sets the pool mode.
[databases]
app = host=10.0.0.5 port=5432 dbname=app
[pgbouncer]
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20HAProxy for the Primary
HAProxy can health-check backends and forward traffic only to the node that is currently the primary, giving clients one fixed write endpoint.
Detecting the Primary
HAProxy uses an HTTP health check against a tool like Patroni's REST API. Only the primary returns 200 on the leader endpoint.
option httpchk GET /primary
http-check expect status 200Separate Read Endpoint
Define a second HAProxy frontend that balances across replicas (the /replica health check), so read-only queries scale across standbys.
listen postgres_read
bind *:5433
balance roundrobin
option httpchk GET /replicaRead/Write Splitting
Applications connect to port 5432 for writes (primary) and 5433 for reads (replicas). Many drivers and ORMs support separate read/write data sources.
Replica Lag Caution
Replicas can lag behind the primary. Route only queries that tolerate slightly stale data to replicas; read-your-own-write paths should hit the primary.
Putting It Together
A common stack: app -> PgBouncer -> HAProxy -> Patroni-managed PostgreSQL cluster. PgBouncer pools, HAProxy routes by role, Patroni manages failover.
Failover Behavior
On failover, Patroni promotes a new primary, HAProxy health checks flip the leader within seconds, and pooled connections reconnect to the new endpoint with minimal disruption.
Quick Check
How does HAProxy keep sending writes to the right node after failover?
Recap
You learned to route connections for high availability: PgBouncer pools connections, HAProxy health-checks to find the primary and balance reads across replicas, and the whole stack flips automatically on failover.
Preguntas frecuentes
¿La lección «Enrutamiento de conexiones con PgBouncer y HAProxy» es gratis?
Sí — el texto completo de «Enrutamiento de conexiones con PgBouncer y HAProxy» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Advanced PostgreSQL: Indexing, Partitioning, Replication, actualiza a CoddyKit PRO. El curso de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye 4 lecciones en total.
¿Qué aprenderé en «Enrutamiento de conexiones con PgBouncer y HAProxy»?
Enrute los clientes al primario actual y distribuya el tráfico de lectura entre réplicas para mantener las aplicaciones disponibles durante las conmutaciones por error. Practicas Advanced PostgreSQL: Indexing, Partitioning, Replication con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Advanced PostgreSQL: Indexing, Partitioning, Replication?
No se requiere experiencia previa. Advanced PostgreSQL: Indexing, Partitioning, Replication en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Enrutamiento de conexiones con PgBouncer y HAProxy»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Advanced PostgreSQL: Indexing, Partitioning, Replication?
Sí. Cada lección de Advanced PostgreSQL: Indexing, Partitioning, Replication incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Herramientas de conmutación por error automática (Patroni)
- Supervisión del estado de la replicación
- Estrategias de recuperación ante desastres
- Enrutamiento de conexiones con PgBouncer y HAProxy