haproxy external sql check

How to configure HAProxy with external-check to query PostgreSQL database directly

A key feature of HAProxy is its ability to perform health checks, ensuring that only healthy servers receive traffic. This blog post will guide you through configuring HAProxy with an external check to query PostgreSQL, providing an extra layer of assurance that your database servers are functioning correctly.

Our motivation for not using the Patroni REST API and instead querying the database directly was due to the decision to use PgBouncer on the database hosts itself.

When it comes to choosing the right architecture for your high-availability PostgreSQL database environment, you have lots of the different options. One option is for the application to connect to a connection pooler (PgBouncer), which then connects to HAProxy, and HAProxy connects to the PostgreSQL database.

The other option is for the application to connect to the load balancing solution (HAProxy), which then connects to the connection pooler, with the pooler operating in front of the database. Both options have different pros and cons.

Application -> Pgbouncer -> HAProxy -> PostgreSQL Database(patroni)

Application -> HAproxy -> Pgbouncer -> PostgreSQL Database(patroni)

Since PgBouncer is a lightweight service that requires database administrators’ expertise to configure optimally and also reduces network latency, we chose to deploy PgBouncer directly on the PostgreSQL database servers. However, with this architecture, if we relied on health checks from the Patroni REST API, there was a risk of not detecting issues with the pooler application (PgBouncer). Therefore, we decided to use an external query for health checks in HAProxy by executing a simple query like the one below.

Patroni maintains a permanent connection to PostgreSQL and, with every heartbeat, it calls a few functions located in pg_catalog, such as pg_is_in_recovery() and pg_current_wal_lsn(). Similarly, we will perform these checks directly from PgBouncer to ensure that both PgBouncer and the PostgreSQL database are functioning correctly.

First, we will create a database user specifically for querying the database for health checks.

Here is the sample configuration of HAProxy for external checks. HaProxy server should have psql client for querying database directly. We will install postgresql16.

By deploying PgBouncer directly on PostgreSQL database servers, we minimized the network latency between PgBouncer and the database, which led to slightly faster query processing times compared to running PgBouncer on separate servers. This simplified the application architecture and reduced the need for coordination with application teams. Additionally, we have configured PgBouncer to connect to the database locally (using Unix sockets), which is more secure and performant than configuring remote connections.

Hope it helps.


Discover More from Osman DİNÇ


Comments

Leave your comment