advanced
Connection pooling
Reuse database or service connections with bounded pools, timeouts, queue limits, and per-instance capacity math.
Connection pooling reuses database (or HTTP) connections instead of opening a new TCP+auth handshake per request. Pools are **bounded**—when exhausted, callers wait or fail.
const pool = new Pool({ max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 5000 });
| Setting | Risk if wrong | |---------|----------------| | `max` too high | Overwhelms database `max_connections` | | `max` too low | Queueing and timeouts under load | | Per-instance pools | `instances × max` must fit DB budget | | Missing timeout | Hung requests pile up |
Size pools with math: if Postgres allows 200 connections and you run 10 app instances, per-instance `max` might be ~15–18 leaving headroom for admins and migrations.
On interviews: pool sizing formula; PgBouncer vs app-side pool; connection storms on deploy; serverless + DB challenges.
Common pitfalls: max pool 100 on every pod; no timeout on acquire; long transactions holding connections.
The trade-off is concurrency versus database safety and connection overhead.
Checklist:
- Calculate total connections across fleet.
- Set acquire timeouts and metrics.
- Keep transactions short.
- Use external pooler when needed (PgBouncer).