PgBouncer Connection Pooling Setup
Intermediate15 minTrending
Deploy PgBouncer as a connection pooler to reduce PostgreSQL connection overhead and support thousands of concurrent clients.
Prerequisites
- -PostgreSQL running
- -PgBouncer installed (apt install pgbouncer or equivalent)
Steps
1
Configure PgBouncer databases
Edit pgbouncer.ini to define which databases to pool and the upstream PostgreSQL connection.
$ cat > /etc/pgbouncer/pgbouncer.ini << 'INI'
[databases]
mydb = host=127.0.0.1 port=5432 dbname=mydb
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
min_pool_size = 5
reserve_pool_size = 5
server_idle_timeout = 300
INI
Transaction pooling mode (pool_mode = transaction) gives the best connection reuse for most applications.
2
Create the authentication file
Add user credentials that PgBouncer uses to authenticate clients.
$ echo '"app_user" "scram-sha-256$4096:salt$stored_key:server_key"' > /etc/pgbouncer/userlist.txt
Generate the SCRAM hash from PostgreSQL: SELECT rolname, rolpassword FROM pg_authid WHERE rolname = 'app_user';
3
Start PgBouncer
Launch PgBouncer and verify it is listening for connections.
$ sudo systemctl start pgbouncer && sudo systemctl status pgbouncer
4
Connect through PgBouncer
Connect to PostgreSQL through the PgBouncer proxy port.
$ psql -h 127.0.0.1 -p 6432 -U app_user -d mydb -c 'SELECT 1;'
5
Monitor PgBouncer statistics
Connect to the PgBouncer admin console to view pool statistics.
$ psql -h 127.0.0.1 -p 6432 -U pgbouncer -d pgbouncer -c 'SHOW POOLS;'
Full Script
FAQ
Discussion
Loading comments...