Full answer
Why a pool
- Opening a Postgres connection is slow (network, authentication, process start on the server) and the server allows a limited number of connections. A pool keeps a few open connections and lends them out.
- Create one Pool at start up and share it. Do not create a pool per request. new Pool({ max: 10 }) is typical, and the total over all app instances must stay below the server's max_connections (or use PgBouncer).
Querying
- pool.query(text, values) borrows a connection for one statement and returns it automatically.
- Use parameters: pool.query('SELECT * FROM students WHERE id = $1', [id]). The values are sent separately from the SQL, which prevents SQL injection and allows plan reuse.
- Results: result.rows (array of objects), result.rowCount, result.fields.
- Column types: bigint and numeric come back as strings because JavaScript numbers cannot hold them exactly. Cast in SQL (count(*)::int) or set a type parser when you are sure it is safe.
Transactions
- A transaction belongs to one connection, so pool.query cannot be used between BEGIN and COMMIT (each call may use a different connection).
- const client = await pool.connect(); try { await client.query('BEGIN'); ...; await client.query('COMMIT'); } catch (err) { await client.query('ROLLBACK'); throw err; } finally { client.release(); }
- Forgetting release() leaks a connection, and the pool runs dry (see the pitfalls item).
Operations
- Handle pool.on('error') for errors on idle clients.
- Close with await pool.end() when the process shuts down.
- Watch pool.totalCount, idleCount and waitingCount for metrics.
- Use migrations for schema changes, and an ORM or query builder when you want one, but the same pooling rules apply.
javascript
const { Pool } = require('pg');
async function main() {
// Connection settings come from PGHOST, PGPORT, PGUSER, PGDATABASE and PGPASSWORD.
const pool = new Pool({ max: 3 });
await pool.query('DROP TABLE IF EXISTS demo_students');
await pool.query('CREATE TABLE demo_students (id serial PRIMARY KEY, name text NOT NULL, marks int NOT NULL)');
// Parameterized insert with RETURNING
const inserted = await pool.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2) RETURNING id, name', ['Asha', 78]);
console.log('inserted:', JSON.stringify(inserted.rows[0]));
// A hostile value is just data
await pool.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2)', ["Robert'); DROP TABLE demo_students;--", 40]);
const count = await pool.query('SELECT count(*) AS total, count(*)::int AS total_int FROM demo_students');
console.log('count as returned:', JSON.stringify(count.rows[0]), '| typeof total:', typeof count.rows[0].total);
// A transaction on one client: the second insert fails, so both are rolled back.
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2)', ['Ravi', 64]);
await client.query('INSERT INTO demo_students (name, marks) VALUES ($1, $2)', [null, 50]); // violates NOT NULL
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
console.log('transaction failed with code', err.code, '-> rolled back');
} finally {
client.release();
}
const after = await pool.query('SELECT name FROM demo_students ORDER BY id');
console.log('rows after rollback:', after.rows.length, '| Ravi saved:', after.rows.some((r) => r.name === 'Ravi'));
// Pool statistics
console.log('pool total/idle/waiting:', pool.totalCount > 0, pool.idleCount === pool.totalCount, pool.waitingCount);
await pool.query('DROP TABLE demo_students');
await pool.end();
}
main();The script needs a running PostgreSQL server and PG environment variables (it was run against PostgreSQL 17). It creates and drops its own table. Install first with npm install pg (run here with pg 8.23.1). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): inserted: {"id":1,"name":"Asha"} count as returned: {"total":"2","total_int":2} | typeof total: string transaction failed with code 23502 -> rolled back rows after rollback: 2 | Ravi saved: false pool total/idle/waiting: true true 0
Key points
- One Pool per process, shared by all requests.
- pool.query for one statement, pool.connect for a transaction.
- Always release the client in finally.
- Use $1 parameters, never string concatenation.
- bigint and numeric arrive as strings.
Common mistakes
- Creating a new Pool for every request.
- Building SQL with template strings and user input.
- Using pool.query between BEGIN and COMMIT.
- Forgetting client.release() on an error path.
- Assuming count(*) is a JavaScript number.
Follow-ups
- How do you choose the pool size?
- What does PgBouncer add?
- How do you run a migration safely in a deployment?
Tips
- Start with 'one pool, shared'.
- Explain why a transaction needs one client.
- Mention parameters as the injection defence.