Node.js Developer interview question · Most asked
How do you work with relational databases efficiently in Node.js?
Summary
Use a connection pool (pg.Pool, mysql2 pools) shared across requests, parameterized queries, transactions with proper release in finally, and an ORM or query builder (Prisma, Drizzle, Kysely, TypeORM, Sequelize) when it helps productivity.
Longer Answer
Size pools against DB limits (pool size × instances), always release clients, avoid N+1 queries, and set statement timeouts. For serverless, use external poolers (PgBouncer, RDS Proxy) or HTTP-based drivers.
Code Example
import pg from "pg";
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 10 });
export async function transfer(from, to, amount) {
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
await client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
await client.query("COMMIT");
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}
Key Points
- Shared connection pool
- Parameterized queries
- Release clients in
finally - Pool size vs DB max connections
More most-asked Node.js Developer questions
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- What are streams in Node.js and what is backpressure?
- What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- What are the differences between CommonJS and ES modules in Node.js?