PostgreSQL Connection Pooling with PgBouncer on a Small VPS

PostgreSQL Connection Pooling with PgBouncer on a Small VPS

PostgreSQL handles each client connection with its own backend process, and that design starts to hurt on a small VPS. A web app with a few workers and a background job runner can open far more connections than 1 or 2 GB of RAM can serve well. PgBouncer PostgreSQL connection pooling sits between your app and the database and reuses a small set of real server connections for many clients. This guide shows how it works, which pool mode to pick, and how to set it up on Ubuntu 24.04.

If your database already feels slow, check the basics first. A slow VPS diagnosis with htop, iotop, and vmstat will tell you whether RAM, disk, or CPU is the real bottleneck, because pooling fixes connection pressure, not a saturated disk or a missing index.

Why PostgreSQL runs out of connections on a small VPS

Every PostgreSQL connection costs memory. The backend process holds work memory, session state, and buffers. On a 1 GB VPS, a few dozen idle connections can eat RAM that your app and web server also need. Raise max_connections to 500 and the database will accept more clients, but each one still costs memory, and context switching between hundreds of backends slows queries down. That is the core of the postgresql max connections small vps problem: the limit is RAM, not the setting itself.

The PostgreSQL 17 installation and tuning guide for a VPS covers the base settings to get right first, including shared buffers sized for a small machine. Pooling works best on top of a sane base config.

PgBouncer PostgreSQL connection pooling in plain terms

PgBouncer is a lightweight connection pooler for PostgreSQL. Your app connects to PgBouncer on port 6432 instead of PostgreSQL on port 5432, and PgBouncer forwards queries over a much smaller pool of real server connections. When a client goes idle, its server connection returns to the pool for the next client.

Your app sees no difference in the SQL it sends, and PostgreSQL sees far fewer backends. PgBouncer itself uses very little memory, which is why it fits a small VPS: one small process replaces the cost of dozens of idle backends. It does not cache query results and it does not speed up a slow query.

PgBouncer pool modes: session, transaction, and statement

The pool mode decides when a server connection returns to the pool. Pick the wrong one and your app will break in confusing ways, so this choice matters more than any other setting.

Pool mode Connection returned to pool What breaks
session When the client disconnects Nothing, but pooling gains are small
transaction When each transaction ends Session features such as SET, LISTEN, advisory locks, and prepared statements tied to a session
statement After each single statement Multi-statement transactions, prepared statements, and anything that needs session state

Session mode is the safest and the least useful: a connection stays tied to one client for its whole life. Transaction mode is the usual pick for web apps, because each request runs in a transaction and the connection returns to the pool at commit or rollback. Statement mode breaks most real apps, so avoid it unless you know every query your app sends.

Pgbouncer transaction pooling has real limits. Anything that relies on session state will fail or behave oddly: SET variables do not carry over, LISTEN and NOTIFY do not work as expected, advisory locks release at transaction end, and server-side prepared statements need care. Most drivers handle this with client-side prepared statements, but check your stack before you switch. If your app depends on session features, stay in session mode.

Install PgBouncer on Ubuntu 24.04

Install from the Ubuntu repository, which is enough for a small VPS.

sudo apt update
sudo apt install pgbouncer
sudo systemctl status pgbouncer

The package ships a systemd unit and a default config at /etc/pgbouncer/pgbouncer.ini. Before changing settings, sort out authentication: PgBouncer needs to prove to PostgreSQL that a client is who it claims to be.

Create the database user your app will use, then create the auth file PgBouncer reads. The auth_file holds usernames and password hashes, and it should be readable only by the postgres user:

sudo -u postgres psql -c "SELECT '"' || usename || '" "' || passwd || '"' FROM pg_shadow WHERE usename = 'app_user';" > /etc/pgbouncer/userlist.txt
sudo chown postgres:postgres /etc/pgbouncer/userlist.txt
sudo chmod 640 /etc/pgbouncer/userlist.txt

If PostgreSQL uses SCRAM-SHA-256 passwords, set auth_type = scram-sha-256. If it still uses MD5, use auth_type = md5. A mismatch here is the most common reason a fresh install refuses logins.

A sane pgbouncer.ini for a 1-2 GB VPS

Start small. Here is a config that suits a typical small VPS running one app database:

[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 = 100
default_pool_size = 10
min_pool_size = 2
reserve_pool_size = 3
reserve_pool_timeout = 3
server_idle_timeout = 600
server_lifetime = 3600
max_db_connections = 15
admin_users = postgres
stats_users = postgres

What the numbers mean: max_client_conn caps clients at 100, while default_pool_size caps real backends at 10 per database and user pair. min_pool_size keeps 2 connections warm, and reserve_pool_size adds up to 3 extra connections when clients wait longer than reserve_pool_timeout seconds.

max_db_connections caps total server connections for the database, so one user cannot take the whole pool. server_idle_timeout closes connections idle for 600 seconds, and server_lifetime recycles each backend after an hour. Binding to 127.0.0.1 matters: PgBouncer should not listen on a public interface.

Size the pool from your RAM. Set default_pool_size so the pool plus shared buffers, your app, and the operating system still fit. Ten is a reasonable start for a 1-2 GB machine; raise it only when SHOW POOLS shows clients waiting while RAM still has room. If you are still choosing a database, the MySQL versus PostgreSQL comparison for a 2 GB VPS lays out the trade-offs.

Point your app at PgBouncer and test it

Change only the connection string, keeping the database name, username, and password the same:

DATABASE_URL=postgresql://app_user:[email protected]:6432/appdb

Restart the app, then open a test connection through the pooler:

psql "postgresql://app_user:[email protected]:6432/appdb" -c "SELECT 1;"

Run your normal workload for a few minutes, then open the admin console with a user listed in admin_users and run SHOW POOLS:

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

Look at sv_active, sv_idle, and cl_waiting. cl_waiting should sit at zero most of the time; a count that stays above zero means clients queue for a backend, so raise default_pool_size slightly or find the slow queries holding connections.

Enable the service so it survives a reboot, and restart it after any config change. Then confirm it is running:

sudo systemctl enable pgbouncer
sudo systemctl restart pgbouncer
sudo systemctl status pgbouncer

Verify with SHOW POOLS and watch for problems

SHOW POOLS gives the per-database picture, SHOW STATS shows request counts and average wait times, and SHOW CLIENTS and SHOW SERVERS list each connection:

psql -h 127.0.0.1 -p 6432 -U postgres -d pgbouncer -c "SHOW STATS;"
psql -h 127.0.0.1 -p 6432 -U postgres -d pgbouncer -c "SHOW CLIENTS;"
psql -h 127.0.0.1 -p 6432 -U postgres -d pgbouncer -c "SHOW SERVERS;"

Average wait time in SHOW STATS should stay low; a rising wait time with a full pool means the pool is too small or queries hold connections too long. Idle server connections far above min_pool_size for hours mean the pool is bigger than the workload needs.

Watch the logs for the usual failures. Auth errors point at auth_type or a stale userlist.txt after a password change, so regenerate the file whenever you change a database password. Errors about prepared statements point at transaction mode meeting an app that expects session state; switch that app to session mode or turn off server-side prepared statements in the driver.

When PgBouncer is the wrong fix

Pooling helps when you have many mostly idle connections. It does not help when a handful of queries are slow, when the disk is saturated, or when the database needs more RAM than the VPS has. If SHOW POOLS shows no waiting clients while pages still crawl, the problem sits in the queries or the hardware.

It also adds a moving part: one more service to monitor and one more hop between the app and the database. On a VPS with a single app and a small, steady connection count, direct connections are simpler and fine. Add PgBouncer PostgreSQL connection pooling when the connection count grows past what the RAM handles well. Start with transaction mode and a pool of around 10, then adjust from what SHOW POOLS shows.

Ditulis oleh

Firdaus Safari Putra

Founder, PT FirKaizen Digital Solutions

Firdaus Safari Putra adalah founder PT FirKaizen Digital Solutions. Ia membangun dan mengoperasikan infrastruktur server di balik panduan ini, dan menulis berdasarkan apa yang benar-benar ia jalankan, uji, dan ukur — bukan teori.