Connection Pooling
A connection pool keeps a set of open database connections and loans them out. Creating a TCP + auth handshake per query is too slow and will exhaust the server.
Detailed Explanation
A Postgres backend process (or a MySQL thread) costs memory. A Node process that connect()s on every request will hit max_connections under load. A pool (pg.Pool, MySQL createPool, Prisma's built-in pool, Prisma Data Proxy / PgBouncer in front) holds N sockets. query waits for a free one, runs, and returns it.
Size the pool per Node process, not per user. A serverless function with pool = 10 and 100 concurrent instances is 1000 connections. Use a small pool (1–5) on lambdas plus an external pooler (PgBouncer in transaction mode). A long-lived server might use connectionLimit around 10–20 per instance, tuned to CPU and the database's max.
Checkout rules: always release() in finally. A leaked client is a leaked slot; the pool empties and every request hangs. Transactions need one client for their whole life. Logging pool.totalCount / idleCount / waitingCount (pg) tells you if you are saturated.
Idle timeouts and server-side idle_in_transaction_session_timeout kill abandoned transactions. TLS and connectionString belong in env vars, not in the repo.
What it costs you: a mis-sized pool (too big: DB memory; too small: queue latency) and serverless connection storms. Also, transaction-mode poolers break session features (SET, temp tables, prepared statements) unless you understand the mode.
Reach for a pool in every Node process that talks to a network database. Reach for SQLite's single connection (or a tiny pool) in-process. Reach for a pooler in front of Postgres when instance count is bursty.
Health checks belong in the pool, not in every query. pg can run SELECT 1 on checkout; a dead idle connection then fails fast instead of hanging a user request. Log checkout wait time. If wait climbs while CPU is idle, you are either leaked or undersized. If the database CPU is pegged, shrinking the pool can improve latency by reducing lock and context-switch noise.
Code Examples
const { Pool } = require("pg");
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 10,
idleTimeoutMillis: 30_000,
});
async function getUser(id) {
const { rows } = await pool.query("SELECT email FROM users WHERE id = $1", [id]);
return rows[0];
}async function withClient(pool, fn) {
const client = await pool.connect();
try {
return await fn(client);
} finally {
client.release();
}
}Common Gotchas
Forgetting `release()` leaks the pool
wrap in `try/finally`. Hanging requests plus `waitingCount` growing is the symptom.
One large pool per serverless instance × instances = connection storm
sit behind PgBouncer and keep `max` tiny.
`pool.query` inside a transaction you started on `client` is a different connection
use `client.query` only.
The pool is per process
cluster workers do not share it. Multiply by worker count.