Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 138/ 160
07. Indexing, Query Optimization & Performance Tuning

Connection Pooling (PgBouncer) & Statement Timeouts

Protect databases from connection storms with pools and statement timeouts.

IntermediatePgBouncer · Pool Modes3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Minimal PgBouncer settings

pool_mode = transaction, default_pool_size = 50, max_client_conn = 2000: 2,000 clients share 50 server connections per database and user pair.

Key takeaway: Keep server connections small and shared; transaction pooling scales furthest.

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.

Safer defaults for the application roleQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1ALTER ROLE api2SET3  statement_timeout = '5s';45ALTER ROLE api6SET7  idle_in_transaction_session_timeout = '30s';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Choose the target

Identify the table or database object the statement will modify.

1/7
query.sql
1SET2  lock_timeout = '3s';
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/2
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
ALTER ROLE ALTER ROLE SET

Note: Representative PostgreSQL statuses; role defaults apply to new sessions unless overridden, while SET changes the current session.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

and for migrations:

Key takeaway: Every production role needs statement and idle-in-transaction timeouts.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Capacity

Count your real connections

Multiply instances × pool size (plus workers, cron jobs and admin tools) and compare with max_connections.

Focus at this step

40 pods × 25 = 1,000 > max_connections 100

What to watch at this step
Check
after every scale-up
Tip: use ← → to move between steps

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

Application-side pool only
Best for: A few application instances

Strengths: Simple; full session features.

Watch out: Total connections grow with every new instance.

PgBouncer session mode
Best for: Apps that rely on session state

Strengths: Caps connections; everything behaves like a direct connection.

Watch out: A server connection is held for the whole client session, so little sharing.

PgBouncer transaction mode
Best for: Many instances or serverless functions

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?
Interview tip: Do the multiplication out loud (instances × pool size) to show the problem, then propose PgBouncer in transaction mode plus per-role timeouts. That's the full production answer.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Connection Pooling (PgBouncer) & Statement Timeouts with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Table Partitioning (Range, List, Hash) & Partition Pruning
Next topic
Identifying Slow Queries (pg_stat_statements & Slow Query Logs)