Configuring PostgreSQL Streaming Replication and PgBouncer on Ubuntu: 6 Months of Production Experience

The Single-Node Pain and 6 Months of Production Lessons

Six months ago, all of my team’s data still lived on a single PostgreSQL instance running on Ubuntu Server. Everything went smoothly until one Friday night, when traffic suddenly quadrupled. The application started throwing too many connections errors nonstop. CPU hit 100%, and then the VPS provider performed unexpected hardware maintenance, leaving our service frozen for 40 minutes.

That incident forced me to split the load immediately. I chose to pair PostgreSQL Streaming Replication with PgBouncer on Ubuntu Server 22.04—a setup I have deployed across more than 20 VPS clusters for small and medium-sized projects. After half a year in production, this configuration has proven rock-solid: lightweight, easy to manage, and no more sleepless nights over database crashes.

How Streaming Replication and PgBouncer Work Together

Imagine a coffee shop with two barista stations and a coordinator right at the door. The coordinator collects orders from customers to prevent bottlenecks, while the two stations split the work and keep a backup ready.

PostgreSQL Streaming Replication (Primary – Standby)

Every data change in PostgreSQL goes through the WAL (Write-Ahead Log) before being written to disk. With Streaming Replication, the main server (Primary) streams this WAL in real time to a backup server (Standby).

  • Primary Node: Handles all write operations (INSERT, UPDATE, DELETE) and default read queries.
  • Standby Node: Continuously receives and replays WAL records with only a few milliseconds of lag. Running in read-only mode, it is ideal for offloading analytics queries, generating reports, or taking over immediately if the Primary goes down.

PgBouncer: The Connection Pooler

PostgreSQL has a resource-heavy quirk: each new connection spawns a dedicated OS process, consuming roughly 5–10 MB of RAM. If your backend opens just 300 idle connections, a 2 GB RAM VPS will hit OOM (Out of Memory) almost instantly.

PgBouncer sits in the middle to handle connection pooling. Hundreds of requests from the app pour into PgBouncer, while it only maintains a few dozen actual connections to PostgreSQL and rotates them per transaction. On my setup (a 2 vCPU, 4 GB RAM VPS), enabling PgBouncer dropped PostgreSQL’s RAM usage from 3.1 GB down to around 1.8 GB with the exact same request volume.

Hands-On: Building a PostgreSQL + PgBouncer HA Cluster on Ubuntu 22.04

This lab uses two Ubuntu Server 22.04 machines with PostgreSQL 14 pre-installed, communicating over a private network to minimize latency:

  • Primary Node: 10.0.0.10
  • Standby Node: 10.0.0.11

Step 1: Configure the Primary Node

Log in to the Primary (10.0.0.10) server and create a dedicated user solely for replication:

sudo -u postgres psql -c "CREATE USER replicator WITH REPLICATION ENCRYPTED PASSWORD 'YourStrongPassword';"

Open the configuration file /etc/postgresql/14/main/postgresql.conf to enable WAL streaming:

sudo nano /etc/postgresql/14/main/postgresql.conf

Find and update the parameters below. To tighten security, you can replace '*' with 'localhost,10.0.0.10' so PostgreSQL only listens on the private network:

listen_addresses = '*'
wal_level = replica
max_wal_senders = 10
wal_keep_size = 512MB
hot_standby = on

Grant the Standby Node permission to connect via /etc/postgresql/14/main/pg_hba.conf, then restart PostgreSQL:

echo "host    replication     replicator      10.0.0.11/32            scram-sha-256" | sudo tee -a /etc/postgresql/14/main/pg_hba.conf
sudo systemctl restart postgresql

Step 2: Pull Data and Activate the Standby Node

On the Standby (10.0.0.11) server, stop the PostgreSQL service and wipe the default data directory. The pg_basebackup tool will pull all data from the Primary:

sudo systemctl stop postgresql
sudo rm -rf /var/lib/postgresql/14/main/*
sudo -u postgres pg_basebackup -h 10.0.0.10 -U replicator -p 5432 -D /var/lib/postgresql/14/main -Fp -Xs -R -P

The -R flag is especially handy because it automatically creates the standby.signal file and writes the connection settings into postgresql.auto.conf. Now just start the service back up on the Standby:

sudo systemctl start postgresql

Head back to the Primary to verify that both nodes have completed the handshake:

sudo -u postgres psql -x -c "SELECT client_addr, state, sync_state FROM pg_stat_replication;"

Once you see the state column showing streaming alongside the IP 10.0.0.11, your data is syncing in real time.

Step 3: Install and Tune PgBouncer

From my experience, placing PgBouncer directly on the application server or a dedicated proxy node works best. This lets you reroute connections almost instantly if anything happens to the Primary. Installing the package on Ubuntu is straightforward:

sudo apt update && sudo apt install -y pgbouncer

Grab the hashed password string for your application user (e.g., app_user) from the Primary to add to the authentication file:

sudo -u postgres psql -Atq -c "SELECT concat('"', usename, '" "', passwd, '"') FROM pg_shadow WHERE usename='app_user';"

Paste the printed output into /etc/pgbouncer/userlist.txt. Next, open /etc/pgbouncer/pgbouncer.ini and configure it as follows:

[databases]
app_db = host=10.0.0.10 port=5432 dbname=app_db

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

Using pool_mode = transaction allows just 25 real PostgreSQL connections to comfortably serve up to 500 application connections. Keep one caveat in mind, though: in this mode, session-level features such as LISTEN/NOTIFY or prepared statements (on PgBouncer versions older than 1.21) can break. If you use an ORM like Prisma or SQLAlchemy, remember to disable prepared statements or upgrade PgBouncer to version 1.21+.

Restart PgBouncer and test a query through port 6432:

sudo systemctl restart pgbouncer
psql -h 127.0.0.1 -p 6432 -U app_user -d app_db -c "SELECT version();"

Step 4: Practice Failover Before Going to Production

Don’t wait for a real outage to start reading the docs. Try forcefully stopping the PostgreSQL service on the Primary, then run the command below on the Standby to promote it to the new Primary:

sudo -u postgres pg_ctlcluster 14 main promote

Once promoted, update host=10.0.0.11 in /etc/pgbouncer/pgbouncer.ini and run sudo systemctl reload pgbouncer. Your entire application will automatically reconnect to the new database within seconds—no code changes or app restarts required.

Many people ask why I don’t set up auto-failover. In a small 2-node cluster without a third witness node, auto-failover is prone to split-brain during network blips. Having both servers believe they are the Primary leads to data divergence that is a nightmare to recover from. Pairing Telegram alerts with a manual promotion that takes less than a minute gives me far more peace of mind.

Is It Worth Deploying for Your System?

After 6 months of running PostgreSQL Streaming Replication alongside PgBouncer, our database RAM consumption dropped by nearly 40%. Heavy reporting queries are offloaded to the Standby, making user-facing API responses noticeably smoother. Whenever hardware upgrades are needed, I simply promote the Standby and repoint PgBouncer in under a minute.

If your database is still running on a single node and starting to hit connection limits, spend a weekend trying this architecture on two test VPS instances. Practice killing the Primary a few times to get comfortable with the workflow—you’ll find that High Availability is much cleaner to manage than it seems.

Share: