Back to results for “Cloud & DevOps”
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?

Intermediate

Answer

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.

Common follow-ups: How do you determine an appropriate maximum pool size given both the database's connection limit and the number of running application instances?;What happens to a request if it needs a connection but the pool is already fully checked out?