← Back to PostgreSQL, page 5

postgresql-0088 · Hard senior

Design connection management for 2,000 application instances talking to one PostgreSQL primary.

Each PostgreSQL connection is a process using memory, and performance drops well before max_connections when thousands are active. Put a pooler such as PgBouncer between the applications and the database, usually in transaction mode, so a few hundred server connections serve thousands of clients. Size the pool to the database's cores and I/O, keep transactions short, and avoid session state that transaction pooling breaks.

Full answer

Why direct connections fail at this scale: 2,000 instances with 10 connections each would need 20,000 backends. Each costs several megabytes and adds contention on shared structures such as the lock manager and snapshot building, so throughput falls as connections rise.

A typical design:

  • Application-side pools stay small (2 to 5 connections per instance).
  • PgBouncer runs in transaction pooling mode, close to the database or as a sidecar, with a server pool of roughly 2 to 4 times the database's CPU cores for an OLTP workload.
  • A separate pool or role for long-running jobs, so reports do not starve web requests.
  • Timeouts: statement_timeout per role, idle_in_transaction_session_timeout, and pooler query and client timeouts.

What transaction pooling breaks, because consecutive transactions from one client may use different server connections:

  • Session-level SET (use SET LOCAL), advisory locks held across transactions, LISTEN, temporary tables that outlive a transaction, and WITH HOLD cursors.
  • Server-side prepared statements, unless the pooler supports them (PgBouncer 1.21+ can track protocol-level prepared statements).

Operational checks: watch pooler wait times (clients waiting for a server connection) as the main saturation signal, and scale reads with replicas rather than more primary connections.

Key points

  • Connections are processes and do not scale to thousands
  • Use a pooler in transaction mode
  • Size server pools to hardware
  • Transaction pooling breaks session state
  • Watch client wait time in the pooler

Common mistakes

  • Raising max_connections to 10,000
  • Using session SET with transaction pooling

Follow-ups

  • When would session pooling be required?
  • How do serverless functions change pooling?

Tips

  • Size the pool from cores