StoicBuilder

HandbookXIII the AqueductConnection pooling

XIIIthe Aqueduct, Scale it

Connection pooling

1 min readUpdated 28 November

In plain words

A connection pool keeps a fixed number of database connections open and lends them to requests in turn, because opening a connection is slow and a database like Postgres can only hold a limited number.

Where you see it

During a traffic spike Harbor's logs fill with "FATAL: sorry, too many clients already". Each serverless function opened its own Postgres connection until the database hit its limit. PgBouncer in transaction mode lets thousands of clients share 40 server connections.

pgbouncer.iniconfig
[pgbouncer]pool_mode = transactionmax_client_conn = 2000default_pool_size = 40server_idle_timeout = 600
Up to 2,000 app connections share 40 real ones per database and user. In transaction mode a server connection goes back to the pool after each transaction.

What goes wrong

  1. A pool per instance, multiplied

    A pool of 10 sounds small until 30 instances and two workers each open one. Add them up across everything that connects, and keep the total under the database's limit with room for admin tools and migrations.

  2. Session features through a transaction pooler

    In transaction mode your next transaction may run on a different server connection, so session-level SET, advisory locks and LISTEN misbehave. Older PgBouncer versions also broke prepared statements, so check what your version and driver support.

  3. Holding a connection while waiting on something else

    Code that opens a transaction and then calls Stripe for two seconds keeps a pooled connection busy the whole time. Make slow outside calls before or after the transaction, not inside it.

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Count every process that connects to our Postgres database at peak, including API instances, workers, cron jobs and migrations, with each one's pool size, and compare the total with max_connections. Route app traffic through PgBouncer in transaction mode, set a timeout for acquiring a connection, and flag any code that keeps a transaction open during a network call.

Quick check

Sign in to earn +10 XP for it

Harbor runs 25 API instances, each with a pool of 10 connections, against a Postgres server whose max_connections is 100. What happens at peak?

Got a prompt that touches connection pooling?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.