Why Connections Are Expensive
Stand up PostgreSQL with a tight connection limit, watch it refuse clients at the wall, then add pgbouncer as a connection pool and watch thirty clients share five backend processes — all from first principles.
Most apps connect to Postgres and never think about it — until the database starts refusing connections at the worst moment. This course builds the mental model from scratch: we spin up a Postgres with max_connections=20, open more sessions than it allows, and capture the FATAL error first-hand. Then we add pgbouncer as a connection pool in the same docker-compose stack, route traffic through it, and use its admin console to watch thirty clients share five backend processes in real time. Every number in this course came off a real running stand.
What you'll build
- Explain why each PostgreSQL connection spawns an OS process and what that costs
- Hit the max_connections wall and read the error in pg_stat_activity
- Add pgbouncer to a docker-compose stack with correct ini and userlist
- Connect to a database transparently through pgbouncer on port 6433
- Read SHOW POOLS, SHOW CLIENTS, SHOW SERVERS and SHOW STATS in the admin console
Contents
- A database with a deliberately low connection limit
- Start it
- Connect directly to PostgreSQL
- The table we will fill and query
- Create the table
- Two hundred thousand events, repeatably
- Load the rows
- Reading the live configuration
- Confirm the limit is twenty
- Seeing connections as OS processes
- One connection in the view
- Twenty-five clients trying to connect at once
- The wall
- The survivors in pg_stat_activity
- Twenty backends at the wall
- The per-process memory cost
- Four megabytes, multiplied by every connection
- Connect through the pool
- The pool is transparent
- PostgreSQL answers through pgbouncer
- Thirty clients hitting the pool at once
- Thirty clients, zero rejections
- Five backends served thirty clients
- The pgbouncer admin console
- The admin console command set
- The pool state at a glance
- The pool under load
- All client connections in detail
- The server-side connections pgbouncer holds
- Aggregate throughput counters
- What you built and what comes next