Маршрутизация соединений с PgBouncer и HAProxy
Направляйте клиентов к текущему ведущему серверу и распределяйте трафик чтения между репликами, чтобы приложения оставались доступными при переключении после сбоя.
«Маршрутизация соединений с PgBouncer и HAProxy» — бесплатный урок Advanced PostgreSQL: Indexing, Partitioning, Replication на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Advanced PostgreSQL: Indexing, Partitioning, Replication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Advanced PostgreSQL: Indexing, Partitioning, Replication содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
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.
Часто задаваемые вопросы
Урок «Маршрутизация соединений с PgBouncer и HAProxy» бесплатный?
Да — полный текст урока «Маршрутизация соединений с PgBouncer и HAProxy» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Advanced PostgreSQL: Indexing, Partitioning, Replication, подпишись на CoddyKit PRO. Курс Advanced PostgreSQL: Indexing, Partitioning, Replication содержит 4 уроков всего.
Чему я научусь в уроке «Маршрутизация соединений с PgBouncer и HAProxy»?
Направляйте клиентов к текущему ведущему серверу и распределяйте трафик чтения между репликами, чтобы приложения оставались доступными при переключении после сбоя. Ты практикуешь Advanced PostgreSQL: Indexing, Partitioning, Replication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Advanced PostgreSQL: Indexing, Partitioning, Replication?
Предыдущий опыт не требуется. Advanced PostgreSQL: Indexing, Partitioning, Replication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Маршрутизация соединений с PgBouncer и HAProxy»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Advanced PostgreSQL: Indexing, Partitioning, Replication?
Да. Каждый урок Advanced PostgreSQL: Indexing, Partitioning, Replication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Инструменты автоматического переключения (Patroni)
- Мониторинг состояния репликации
- Стратегии аварийного восстановления
- Маршрутизация соединений с PgBouncer и HAProxy