Connection pooling helps your app reuse database connections instead of opening a new one every time. This makes your app faster and uses less resources.
0
0
Connection pooling concept in Node.js
Introduction
When your app talks to a database many times quickly.
When you want to avoid delays caused by opening new connections.
When you want to limit how many connections your app uses at once.
When you want to improve app performance under heavy load.
Syntax
Node.js
const { Pool } = require('pg');
const pool = new Pool({
user: 'username',
host: 'localhost',
database: 'mydb',
password: 'password',
port: 5432,
max: 10, // max connections
idleTimeoutMillis: 30000 // close idle connections after 30 seconds
});This example uses the pg library for PostgreSQL in Node.js.
The max option sets how many connections can be open at once.
Examples
Basic pool setup with default max connections.
Node.js
const { Pool } = require('pg');
const pool = new Pool({
user: 'user1',
host: 'localhost',
database: 'testdb',
password: 'pass123',
port: 5432
});Pool with max 5 connections and closes idle ones after 10 seconds.
Node.js
const { Pool } = require('pg');
const pool = new Pool({
max: 5,
idleTimeoutMillis: 10000
});Using the pool to run a query and then closing all connections.
Node.js
pool.query('SELECT NOW()', (err, res) => { if (err) throw err; console.log(res.rows[0]); pool.end(); });
Sample Program
This program creates a pool with up to 3 connections. It runs a simple query to get the current time from the database, prints it, and then closes the pool.
Node.js
import { Pool } from 'pg'; const pool = new Pool({ user: 'postgres', host: 'localhost', database: 'testdb', password: 'secret', port: 5432, max: 3, idleTimeoutMillis: 20000 }); async function fetchTime() { try { const res = await pool.query('SELECT NOW()'); console.log('Current time from DB:', res.rows[0].now); } catch (err) { console.error('Error running query', err); } finally { await pool.end(); } } fetchTime();
OutputSuccess
Important Notes
Always close the pool with pool.end() when your app stops to free resources.
Using a pool avoids the overhead of connecting to the database every time you run a query.
Set max carefully to avoid overloading your database with too many connections.
Summary
Connection pooling reuses database connections to improve speed and resource use.
It is useful when your app runs many database queries quickly.
Always configure and close your pool properly to keep your app healthy.