Node.js › Databases
What is a database connection pool, and why does a Node.js application need one rather than opening a new connection per request?
IntermediateAnswer
A connection pool maintains a set of already-established database connections that are reused across requests rather than opening and closing a new (relatively expensive to establish) connection for every single database operation -- without pooling, connection setup overhead would dominate request latency, and a sudden traffic spike could exhaust the database's own maximum connection limit far more easily.
const { Pool } = require('pg');
const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 20 });
const result = await pool.query('SELECT * FROM users WHERE id = $1', [userId]);Real-world example An API configures its PostgreSQL connection pool with a maximum of 20 connections per instance, calculated so that across all running instances the total never exceeds the database server's own configured connection limit, preventing 'too many connections' errors under load.