Databases & Storage

Connection Pooling Explained: PgBouncer and ProxySQL on a VPS

By NileVPS Team · Published · 5 min read

اقرأ المقال بالعربي

Opening a database connection is more expensive than it looks. Every new connection involves a network handshake, often TLS, authentication, and memory on the database server. When an application opens and closes connections for every request, or when dozens of worker processes each hold their own connections, the database spends resources managing connections instead of running queries. Eventually you see errors like "too many connections" or "sorry, too many clients already". Connection pooling solves this by keeping a set of open connections and sharing them. This guide explains how pooling works and how to use PgBouncer for PostgreSQL and ProxySQL for MySQL.

Why connections are costly

  • PostgreSQL starts a separate operating system process for each connection. Each process uses memory, and very high connection counts add overhead even when most connections are idle.
  • MySQL and MariaDB use a thread per connection by default. Threads are lighter than processes, but thousands of them still compete for CPU and memory.
  • Applications multiply quickly: PHP-FPM with 50 workers, a queue worker pool and a cron job can open well over 100 connections, even if only a few queries run at any moment.

Raising max_connections is tempting, but more simultaneous connections do not mean more throughput. Beyond a certain point, the database slows down as connections compete for CPU, locks and memory.

How a pooler works

A connection pooler sits between the application and the database. Applications connect to the pooler as if it were the database. The pooler keeps a small number of real connections to the database open and assigns them to clients only when needed.

Two layers of pooling

  1. In-application pools: many runtimes and frameworks (Java with HikariCP, Node.js drivers, Go's database/sql, Python's SQLAlchemy) keep a pool inside each process. This works well for long-running processes.
  2. External poolers: PgBouncer and ProxySQL run as separate services. They are essential when many short-lived processes connect, as with PHP-FPM, or when several applications share one database.

PgBouncer for PostgreSQL

PgBouncer is lightweight and widely used. Install it with sudo apt install pgbouncer on Debian and Ubuntu. The main configuration file is /etc/pgbouncer/pgbouncer.ini:

[databases]
appdb = host=127.0.0.1 port=5432 dbname=appdb

[pgbouncer]
listen_addr = 127.0.0.1
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 500
default_pool_size = 20

userlist.txt holds the users allowed to connect, one per line in the form "username" "password-or-scram-secret". Restrict the file so only the postgres user can read it. Then restart the service and point the application at port 6432 instead of 5432:

sudo systemctl restart pgbouncer
psql -h 127.0.0.1 -p 6432 -U appuser appdb

Pool modes

ModeServer connection is releasedCompatibilityEfficiency
sessionWhen the client disconnectsFullLowest
transactionWhen each transaction endsMost applicationsHigh
statementAfter each statementVery limited, no multi-statement transactionsHighest

Transaction mode is the usual choice. Its main limitation is that session-level state does not carry over between transactions: SET commands, advisory locks held across transactions, LISTEN, and temporary tables may behave unexpectedly. Protocol-level prepared statements are supported in transaction mode since PgBouncer 1.21 when max_prepared_statements is set; on older versions, disable server-side prepared statements in your driver.

Monitoring PgBouncer

Connect to the admin console as a user listed in admin_users or stats_users:

psql -h 127.0.0.1 -p 6432 -U pgbouncer pgbouncer -c "SHOW POOLS;"

Watch cl_waiting: clients waiting for a server connection. If it is often above zero, the pool may be too small or queries are holding connections too long.

ProxySQL for MySQL and MariaDB

ProxySQL is a more feature-rich proxy for the MySQL protocol. Besides connection multiplexing, it can route queries by rules, for example sending reads to replicas, and cache selected results. It is configured through an admin interface on port 6032 using SQL:

INSERT INTO mysql_servers (hostgroup_id, hostname, port) VALUES (10, '127.0.0.1', 3306);
INSERT INTO mysql_users (username, password, default_hostgroup) VALUES ('appuser', 'app-password', 10);
LOAD MYSQL SERVERS TO RUNTIME; SAVE MYSQL SERVERS TO DISK;
LOAD MYSQL USERS TO RUNTIME; SAVE MYSQL USERS TO DISK;

Applications then connect to port 6033. ProxySQL needs its own monitoring user on the MySQL server to check backend health. If you use read replicas, query rules can send SELECT traffic to a reader hostgroup; see our guide on read replicas.

Sizing the pool

There is no universal number, but a few principles help:

  • The useful number of active database connections is usually close to a small multiple of the CPU cores available to the database, not hundreds.
  • Start with a modest pool, for example 10 to 20 server connections for a small VPS, and increase only if clients are waiting and the database still has spare CPU.
  • Keep max_connections on the database above the total of all pools plus a reserve for administration.
  • Fix long transactions first. A connection held by an idle transaction is unavailable to everyone else.

Practical checklist

  1. Count current connections: SELECT count(*) FROM pg_stat_activity; or SHOW STATUS LIKE 'Threads_connected';.
  2. Find idle connections and their sources before adding a pooler.
  3. Run the pooler on the same server as the application or the database and bind it to 127.0.0.1 or a private network.
  4. Choose transaction mode for PgBouncer unless the application depends on session state.
  5. Monitor waiting clients and query latency after the change.

Pooling is often one of the cheapest performance gains available, before any hardware upgrade. When you do need more capacity, compare plans on our pricing page.

FAQ

Do I need PgBouncer if my framework already has a connection pool?

Not always. Long-running applications with a built-in pool may be fine. PgBouncer helps most when many short-lived processes connect, such as PHP-FPM workers, or when several services share the same database.

Will a connection pooler make slow queries faster?

No. Pooling reduces connection overhead and protects the database from overload, but a query that is slow because of a missing index stays slow. Use EXPLAIN and proper indexing for that.

Is it safe to expose PgBouncer or ProxySQL to the internet?

Avoid it. Bind poolers to localhost or a private network, allow access only from the application servers in the firewall, and keep the ProxySQL admin port closed to the outside.

Related guides