PostgreSQL Connection Pooling with PgBouncer
Intermediatev1.0.0
Configure PgBouncer for PostgreSQL connection pooling — transaction vs session pooling, sizing pool limits, monitoring connections, and handling prepared statements.
Content
Overview
PostgreSQL creates a new process for every client connection, consuming ~10MB of memory each. Without connection pooling, 500 application instances each opening 20 connections would require 10,000 PostgreSQL processes — crashing your server. PgBouncer solves this by multiplexing many client connections over a small pool of actual database connections.
Why This Matters
- -Each PostgreSQL connection costs ~10MB RAM + process overhead
- -Default max_connections is 100 — easily exhausted by modern apps
- -Opening a new connection takes 50-100ms (TCP + TLS + auth)
- -Connection pooling reduces this to < 1ms for pooled connections
Setup and Configuration
Step 1: Install PgBouncer
Step 2: Configure PgBouncer
Step 3: Choose Pool Mode
Step 4: Application Connection String
Best Practices
- -Use transaction pooling unless you specifically need session features
- -Set max_db_connections to 80% of PostgreSQL's max_connections
- -Monitor with: SHOW POOLS; SHOW STATS; SHOW CLIENTS;
- -Use prepared statements at the driver level with transaction pooling disabled
- -Set server_idle_timeout to reclaim unused connections
- -Run PgBouncer on the same host as the application for lowest latency
Common Mistakes
- -Setting pool size too high (defeats the purpose — still overwhelms PostgreSQL)
- -Using session pooling when transaction pooling would work
- -Using SET statements with transaction pooling (settings don't persist)
- -Not monitoring the pool (cl_waiting > 0 means clients are queuing)
- -Forgetting to update connection strings from direct PostgreSQL to PgBouncer
FAQ
Discussion
Loading comments...