Connection Pooling (PgBouncer) & Statement Timeouts
Protect databases from connection storms with pools and statement timeouts.
In plain words
Instead of everyone opening their own line to the database, they share a few lines in turn. Timeouts hang up on anyone who takes too long.
Think of it like…
A restaurant with eight tables and a queue at the door: seating everyone at once would be chaos, so a host lets people in as tables free up (the pool). A rule that nobody keeps a table for more than two hours (the timeout) stops one slow diner blocking the evening.
Where you’ve seen it
An API scales to 40 pods with 25 connections each, 1,000 in total, and PostgreSQL starts refusing connections. Putting PgBouncer in transaction mode in front, with 60 server connections, serves the same traffic, and a 5-second statement_timeout stops a runaway report from exhausting the pool.
Words you’ll hear
- max_connections
- PostgreSQL's limit on concurrent connections (default 100).
- Transaction pooling
- PgBouncer mode where a client holds a server connection only for one transaction.
- statement_timeout
- Cancels any statement that runs longer than the limit.
- idle_in_transaction_session_timeout
- Ends sessions that leave a transaction open and idle.
Visual diagram
Theory & example queries
Why pools, and how big
Opening a PostgreSQL connection forks a process and takes several megabytes of memory; idle connections still cost memory and snapshot overhead. The database does its best work with a modest number of active queries, roughly a small multiple of its CPU cores, so more connections than that just queue inside the server and contend for locks and cache.
Application-side pools (HikariCP, SQLAlchemy, node-postgres Pool) reuse connections within one process. With many instances, a central pooler like PgBouncer caps the total. In transaction mode, a client gets a server connection only for the duration of a transaction, so a few dozen server connections can serve hundreds of clients. Session-level features (SET without LOCAL, advisory locks held across transactions, LISTEN/NOTIFY, and on older PgBouncer versions, prepared statements) don't work reliably in that mode.
pool_mode = transaction, default_pool_size = 50, max_client_conn = 2000: 2,000 clients share 50 server connections per database and user pair.
Timeouts that protect the database
statement_timeout cancels queries that run too long, so one bad report can't hold a connection and its locks for an hour. Set it per role (ALTER ROLE api SET statement_timeout = '5s') or per transaction, with a higher limit for reporting roles. lock_timeout makes statements give up instead of queueing forever behind a lock, which is essential for migrations.
idle_in_transaction_session_timeout ends sessions that opened a transaction and then went idle, such as a crashed worker, which would otherwise hold locks and block VACUUM. Pair these with pool-side timeouts (how long a client waits for a free connection) and fail fast with a clear error, rather than letting requests pile up.
ALTER ROLE apiSET statement_timeout = '5s';ALTER ROLE apiSET idle_in_transaction_session_timeout = '30s';PostgreSQL is the lesson baseline unless noted otherwise.
Identify the table or database object the statement will modify.
SET lock_timeout = '3s';PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output
Note: Representative PostgreSQL statuses; role defaults apply to new sessions unless overridden, while SET changes the current session.
and for migrations:
Key takeaway: Every production role needs statement and idle-in-transaction timeouts.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Count your real connections
Multiply instances × pool size (plus workers, cron jobs and admin tools) and compare with max_connections.
40 pods × 25 = 1,000 > max_connections 100
When to use it & trade-offs
What it is
Every PostgreSQL connection is a separate server process using memory, so thousands of open connections slow the database down or hit max_connections. A connection pool, in the application or a proxy like PgBouncer, keeps a small number of real database connections and shares them among many clients. Timeouts such as statement_timeout, lock_timeout and idle_in_transaction_session_timeout stop one slow or stuck session from taking everything else down.
Why it matters: Scaling an app from 2 to 50 instances, each with a pool of 20, quietly means 1,000 database connections, and outages from "too many connections" or a pile-up of slow queries are very common. Pool sizing and timeouts are standard backend and production-readiness interview topics.
When to reach for it
- Any app running many instances or serverless functions
- Protecting the database from slow or runaway queries
- Safe schema migrations with lock_timeout
When to avoid or be careful
- Raising max_connections to thousands instead of pooling
- No statement_timeout on application roles
- Relying on session-level SET or advisory locks through a transaction-mode pooler
Application pool vs PgBouncer session mode vs transaction mode
Strengths: Simple; full session features.
Watch out: Total connections grow with every new instance.
Strengths: Caps connections; everything behaves like a direct connection.
Watch out: A server connection is held for the whole client session, so little sharing.
Strengths: A few server connections serve many clients.
Watch out: Session state doesn't persist between transactions.
Interview signals & numbers to know
When this topic comes up
- “FATAL: sorry, too many clients already”
- “How would you scale to 100 app servers?”
- Serverless functions and databases
- Requests hanging under load
- idle in transaction sessions
Benchmarks & rules of thumb
- 100
- default max_connections
- Several MB
- memory per PostgreSQL connection
- Tens
- typical server-side pool size
Common mistakes & follow-ups
Common interview mistakes
- Scaling app instances without recalculating total connections.
- Setting max_connections = 5000, which wastes memory and slows the database under load.
- Using SET search_path or advisory locks through PgBouncer in transaction mode and getting inconsistent behaviour.
Likely interviewer follow-ups
- Why not just increase max_connections?
- What breaks when you switch PgBouncer to transaction pooling?
- Which timeouts would you set on an API's database role, and why?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Connection Pooling (PgBouncer) & Statement Timeouts with hands-on SQL practice and interview Q&A.