Connection pooling
Local baseline: Node.js 22.16.0. Dependency-free application model; no external service execution. No third-party packages or external connections.
Try the local example
let releases=0;const pool={async connect(){return {async query(){throw Error('fixture failure');}, release(){releases++;}};}};async function read(pool){const client=await pool.connect();try{return await client.query();}finally{client.release();}}try {await read(pool);} catch(error){console.log(error.message);}console.log(releases);Run node main.mjs in a disposable directory with the files shown. Expected standard output:
fixture failure1How it works
With pg, use pool.query for an independent query, or pool.connect when work must stay on one client. Use try/finally around checked-out work. A pool is generally application-scoped, not created per request. A pool limit is per pool and process; consider all application replicas and database capacity. Timeouts, waiting requests and idle-client errors need operational handling. The local model only demonstrates ownership and cleanup on a thrown error; it does not emulate network or database behavior.
Integration example — staged
Static candidate only. Exact package and server versions, dependency/advisory review, integration and compilation NOT RUN. Use only a reviewed disposable fixture; no real connection settings.
// Partial pg example: pool is application-owned and already configured.export async function countBooks(pool) { const client=await pool.connect(); try { const result=await client.query('SELECT count(*) AS total FROM book'); return result.rows[0].total; } finally {client.release();}}Returns the driver-decoded count (often a string for PostgreSQL bigint). NOT RUN.
Common mistake
Do not place release only after successful work. A rejected query can otherwise leave a client checked out and eventually exhaust the pool.
Practice
Change the fake query to succeed and verify that the release count is still one. Explain what happens if connect itself rejects.
Documentation: primary source. Candidate lookup: node-connection-pooling-lookup. Prerequisite: node-sql-drivers-and-parameters (platform route unverified).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Connection pooling — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
When should a checked-out client be released?
How many pools should a typical service create?
What does the local fake prove?