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

← All Node.js Developer questions