AceDevHub
Advanced Node.js Interview QuestionsAdvancedScenario

Node.js · Question 99

How would you set up PostgreSQL connection pooling in Node.js?

Direct answer

Create one pg Pool at startup with max connections sized to Postgres limit ÷ API instances — reuse across requests, await pool.query with parameterized SQL, pool.end() on shutdown; monitor waitingCount for saturation.

Scenario: AceDevHub API serves concurrent interview page queries without opening a new TCP connection per request — raw pg Pool, no ORM.

  1. Singleton pool — export pool from db/plugin; module cache ensures one instance (Q36).
  2. Sizing — max: 20 per instance; Postgres max_connections ÷ replicas.
  3. Parameterized queries — pool.query('... WHERE slug = $1', [slug]).
  4. Shutdown — await pool.end() in graceful shutdown (Q73).
scenario-pg-pool.mjs
import pg from "pg";

const pool = new pg.Pool({
  connectionString: config.databaseUrl,
  max: 20,
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 5_000,
});

export async function findTopicBySlug(slug) {
  const { rows } = await pool.query(
    `SELECT id, slug, title FROM interview_topics WHERE slug = $1`,
    [slug]
  );
  return rows[0] ?? null;
}

// Health: await pool.query('SELECT 1')