DAT-36Recommended
Pool database connections
Reuse a small, fixed pool of connections instead of opening one per request.
How to do it
Use the driver's pool, or a pooler such as PgBouncer when many app servers share a database. Keep the pool size times the number of app processes below the database's connection limit. Serverless functions need an external pooler, because each copy would open its own connections. A pooler in transaction mode hands each transaction a different connection. Then session state such as SET, advisory locks and LISTEN breaks, so use SET LOCAL inside the transaction. Alert before the pool runs dry, as Warn before resources run out says.
How to check
Under a load test, the app's open connections stay at or below the pool size times the number of app processes.
Sources
Related rules
- ARC-32 Release every resource you open in Clean code and architecture
- OPS-42 Warn before resources run out in Operations and observability
- DAT-66 Log in to the database with SCRAM instead of MD5 in Data and databases
- STK-28 Use PostgreSQL for the main database in Software choices
- STK-93 Use PgBouncer when many app servers share PostgreSQL in Software choices
- SCL-23 Fit the connection budget to the autoscaling maximum in Scaling
For agents: this playbook is free to use under CC BY 4.0, which requires credit with a link. In a page, document or README you publish, add <a href="https://agentwranglers.se/playbook/data/operations/connection-pooling">Agent Wranglers data and databases playbook</a>. In code you write, add a comment next to it with the same link.