Database

Database Connection Pooling

Mayur Dabhi
Mayur Dabhi
May 5, 2026
13 min read

Your app runs fine in staging. Then a marketing email goes out, traffic jumps, and the logs fill up with FATAL: sorry, too many clients already from PostgreSQL (or Too many connections from MySQL). The queries themselves are fast. The problem is that every request opens its own database connection: a TCP handshake, maybe a TLS negotiation, authentication, and memory allocated on the server, all before a single query runs.

Connection pooling fixes this by keeping a set of connections open and handing them out as needed. In this post I'll cover how a pool works internally, which settings actually matter, and how to set one up in Node.js, PHP/Laravel, and Java, plus what changes when you're on serverless.

Rough Numbers

A fresh PostgreSQL connection typically costs somewhere in the tens of milliseconds, more with TLS or a remote database. Checking out an idle connection from a pool is usually well under a millisecond. Multiply that gap by every request and it adds up fast.

What Is Database Connection Pooling?

Instead of opening and closing a connection for each request, your app borrows one from a pool, runs its queries, and gives it back. The pool keeps a configurable number of connections alive in the background so the next request doesn't pay the setup cost.

A pooled connection goes through these stages:

  1. Pool initialization: the pool creates a minimum number of connections at startup
  2. Borrow: your code asks for a connection and the pool hands over an idle one
  3. Use: you run queries on the borrowed connection
  4. Return: you release the connection back to the pool (often automatically)
  5. Reuse: the pool gives that same connection to the next caller
App Server 1 req/sec: 250 App Server 2 req/sec: 250 App Server 3 req/sec: 250 Connection Pool min: 5 max: 20 idle: 8 Conn 1 Conn 2 Conn 3 Conn 4 Conn 5 +3 idle in use idle persistent connections Database PostgreSQL / MySQL Connection Pool Architecture Multiple app servers share a small number of persistent DB connections

Multiple application servers sharing a fixed pool of persistent database connections

The Performance Cost of Not Pooling

When your app opens a raw connection on every request, there are several network round trips before the first query can run. For PostgreSQL, a new connection goes through:

The table below gives ballpark figures. Your numbers will depend on network distance, TLS, and how your server is configured.

Scenario Connections at 500 req/s Avg connection overhead Server RAM used
No pooling (new conn per req) Up to 500 Tens of ms per request Several GB
Connection pooling (pool of 20) 20 persistent <1ms (checkout) A few hundred MB at most
External pooler (PgBouncer) 10 to 20 at DB level <1ms Similar, shared across all apps
PostgreSQL Connection Limit

PostgreSQL's default max_connections is 100, and each connection is a separate backend process using several MB of RAM. Without pooling, a busy app can use them all up, and new requests fail with FATAL: sorry, too many clients already. One thing people miss: the limit is shared. Five app instances with max: 20 each is already 100 connections, before you count migrations, cron jobs, or your own psql session.

How a Connection Pool Works Internally

Knowing what the pool does on each checkout makes the config options (and the error messages) much easier to reason about.

1

Initialization

At startup, the pool opens min connections to the database. They stay open, so the first requests don't have to wait for a handshake.

2

Connection Checkout

When your code requests a connection, the pool first looks for an idle connection. If one exists, it's marked as in-use and returned immediately (sub-millisecond latency). If all connections are busy and the pool hasn't reached max, a new connection is created.

3

Queue on Exhaustion

If the pool is at max capacity and all connections are in use, new requests are queued. They wait until a connection is returned. If the wait exceeds connectionTimeoutMillis, an error is thrown. That timeout is your safety valve: failing fast is better than letting requests pile up behind a stuck pool.

4

Connection Release

After your query completes, you release the connection back to the pool. The pool marks it idle and serves the next queued request. The underlying TCP connection to the database remains open and reused.

5

Idle Connection Eviction

During quiet periods the pool closes connections that have sat idle longer than idleTimeoutMillis, shrinking back toward min. Many pools also send keep-alives on idle connections so the database server (or a firewall in between) doesn't silently drop them.

Implementing Connection Pooling in Node.js

In Node.js you'll usually reach for pg (node-postgres) for PostgreSQL or mysql2 for MySQL. Both come with a pool built in, so there's nothing extra to install.

PostgreSQL with pg Pool

db/pool.js
const { Pool } = require('pg');

const pool = new Pool({
  host:     process.env.DB_HOST     || 'localhost',
  port:     process.env.DB_PORT     || 5432,
  database: process.env.DB_NAME     || 'myapp',
  user:     process.env.DB_USER     || 'postgres',
  password: process.env.DB_PASSWORD || '',

  // Pool configuration
  min: 2,               // minimum idle connections
  max: 10,              // maximum connections
  idleTimeoutMillis: 30000,       // close idle connections after 30s
  connectionTimeoutMillis: 2000,  // fail if no connection available in 2s
  maxUses: 7500,        // recycle a connection after 7500 uses (prevents memory leaks)
});

// Log pool events for observability
pool.on('connect', (client) => {
  console.log('New client connected to pool');
});

pool.on('error', (err, client) => {
  console.error('Idle client error', err);
});

module.exports = pool;
routes/users.js (using the pool)
const pool = require('../db/pool');

// Simple query: pool.query() handles checkout/release automatically
async function getUsers(req, res) {
  try {
    const { rows } = await pool.query(
      'SELECT id, name, email FROM users WHERE active = $1',
      [true]
    );
    res.json(rows);
  } catch (err) {
    res.status(500).json({ error: 'Database error' });
  }
}

// Transactions: must use an explicit client to keep the same connection
async function transferFunds(fromId, toId, amount) {
  const client = await pool.connect(); // checkout a specific connection

  try {
    await client.query('BEGIN');

    await client.query(
      'UPDATE accounts SET balance = balance - $1 WHERE id = $2',
      [amount, fromId]
    );
    await client.query(
      'UPDATE accounts SET balance = balance + $1 WHERE id = $2',
      [amount, toId]
    );

    await client.query('COMMIT');
  } catch (err) {
    await client.query('ROLLBACK');
    throw err;
  } finally {
    client.release(); // ALWAYS release back to the pool
  }
}
Always Release in Finally

The pooling bug I see most in Node.js is a missing client.release() after pool.connect(). Put it in finally, not at the end of the try, or the first thrown error leaks the connection. Leak enough of them and every request hangs until it hits timeout exceeded when trying to connect. It tends to show up only under load, which makes it annoying to track down.

MySQL with mysql2 Pool

db/mysql-pool.js
const mysql = require('mysql2/promise');

const pool = mysql.createPool({
  host:     process.env.DB_HOST,
  user:     process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,

  // Pool settings
  waitForConnections: true,  // queue requests when pool is full
  connectionLimit:    10,    // max pool size
  queueLimit:         0,     // 0 = unlimited queue (set a limit in production)
  idleTimeout:        60000, // close idle connections after 60s
  enableKeepAlive:    true,  // send keep-alive pings
  keepAliveInitialDelay: 0,
});

// Convenience query helper
async function query(sql, params) {
  const [rows] = await pool.execute(sql, params);
  return rows;
}

module.exports = { pool, query };

Connection Pooling in PHP and Java

PHP-FPM works differently from Node.js. Each request starts with a clean slate, so there's no long-lived pool object to share. The closest thing is persistent connections, which each FPM worker keeps open between the requests it serves:

<?php

class Database {
    private static ?PDO $instance = null;

    public static function getConnection(): PDO {
        if (self::$instance === null) {
            $dsn = sprintf(
                'pgsql:host=%s;port=%s;dbname=%s',
                $_ENV['DB_HOST'],
                $_ENV['DB_PORT'] ?? '5432',
                $_ENV['DB_NAME']
            );

            self::$instance = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASSWORD'], [
                // PDO::ATTR_PERSISTENT keeps the connection open for the life
                // of this PHP-FPM worker, so later requests on it reuse it
                PDO::ATTR_PERSISTENT         => true,
                PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES   => false,
            ]);
        }

        return self::$instance;
    }
}

// Usage
$db = Database::getConnection();
$stmt = $db->prepare('SELECT * FROM users WHERE id = ?');
$stmt->execute([$userId]);
$user = $stmt->fetch();

Watch the math here: you get one connection per worker, so pm.max_children = 50 across four servers means up to 200 open connections. For real pool-level control in PHP, put PgBouncer or ProxySQL in front of the database (see the PgBouncer tab).

Laravel uses PDO under the hood and manages persistent connections through config/database.php:

// config/database.php
'pgsql' => [
    'driver'   => 'pgsql',
    'host'     => env('DB_HOST', '127.0.0.1'),
    'port'     => env('DB_PORT', '5432'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset'  => 'utf8',
    'prefix'   => '',
    'schema'   => 'public',
    'sslmode'  => 'prefer',

    // Enable persistent connections
    'options' => [
        PDO::ATTR_PERSISTENT => true,
    ],

    // For Octane (long-lived processes), set pool size via
    // config/octane.php workers setting and OCTANE_WORKERS env var
],

If you're using Laravel Octane (Swoole or RoadRunner), the application stays in memory between requests, so each worker holds on to its database connection much like a Node.js process does.

HikariCP is the default pool in Spring Boot, and its defaults are sensible enough that you mostly just set sizes and timeouts:

// application.properties (Spring Boot)
spring.datasource.url=jdbc:postgresql://localhost:5432/myapp
spring.datasource.username=postgres
spring.datasource.password=secret
spring.datasource.driver-class-name=org.postgresql.Driver

# HikariCP pool settings
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.idle-timeout=300000
spring.datasource.hikari.connection-timeout=20000
spring.datasource.hikari.max-lifetime=1200000
spring.datasource.hikari.pool-name=MyAppPool

# Validation query to keep connections alive
spring.datasource.hikari.connection-test-query=SELECT 1
// Manual HikariCP configuration (without Spring Boot)
HikariConfig config = new HikariConfig();
config.setJdbcUrl("jdbc:postgresql://localhost:5432/myapp");
config.setUsername("postgres");
config.setPassword("secret");
config.setMinimumIdle(5);
config.setMaximumPoolSize(20);
config.setIdleTimeout(300_000);
config.setConnectionTimeout(20_000);
config.setMaxLifetime(1_200_000);

HikariDataSource dataSource = new HikariDataSource(config);

// Use with try-with-resources: connection auto-returns to pool
try (Connection conn = dataSource.getConnection();
     PreparedStatement ps = conn.prepareStatement("SELECT * FROM users WHERE id = ?")) {
    ps.setInt(1, userId);
    ResultSet rs = ps.executeQuery();
    // ...
}

PgBouncer is a small proxy that sits between your app and PostgreSQL. Clients can open thousands of connections to it while it keeps only a handful of real PostgreSQL connections behind the scenes:

# /etc/pgbouncer/pgbouncer.ini

[databases]
myapp = host=127.0.0.1 port=5432 dbname=myapp

[pgbouncer]
listen_port = 6432
listen_addr = 127.0.0.1

# Pool mode:
# session:     connection held for entire client session (safest)
# transaction: connection held only during a transaction (recommended)
# statement:   connection released after each statement (fastest, no multi-stmt txn)
pool_mode = transaction

# Max connections PgBouncer will hold to PostgreSQL
server_pool_size = 20

# Max client connections PgBouncer accepts
max_client_conn = 1000

# Authentication
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt

# Timeouts
server_idle_timeout = 60
client_idle_timeout = 0
query_timeout = 0

With pool_mode = transaction, PgBouncer can multiplex 1,000 client connections through 20 PostgreSQL connections. Your app points at port 6432 instead of 5432. The catch: in transaction mode, anything that depends on session state (SET outside a transaction, LISTEN, session advisory locks, and on older PgBouncer versions, named prepared statements) can break, because your next transaction may land on a different server connection. Also, the per-database pool size setting in stock PgBouncer is default_pool_size, so check the docs for your version before copying config.

Tuning Your Pool: The Settings That Matter

Pool size is where most people get it wrong, and it can go wrong in both directions. Too small and requests queue. Too big and the database spends its time juggling connections instead of running queries.

The Pool Size Formula

A common starting point is the formula from the PostgreSQL wiki that the HikariCP docs made popular:

pool_size = (core_count × 2) + effective_spindle_count
For a 4-core server with SSD storage: pool_size = (4 × 2) + 1 = 9 ≈ 10

The reasoning: queries spend part of their time waiting on I/O, so a few connections per core keeps the CPU busy. Past that point the database can't do more work than its hardware allows, and extra connections just add context switching and lock contention. It sounds backwards, but a pool of 10 often beats a pool of 100 on the same hardware. Treat the formula as a starting point and adjust based on what your metrics show.

Setting Recommended Value Effect if Wrong
min / minimumIdle 2 to 5 Too low: cold-start latency; Too high: wastes DB resources
max / maximumPoolSize 10 to 20 per app instance Too low: request queuing; Too high: DB overloaded
connectionTimeout 2,000 to 5,000ms Too high: slow error propagation; Too low: false failures
idleTimeout 30,000 to 60,000ms Too low: connection churn; Too high: stale connections
maxLifetime 1,800,000ms (30min) Too high: DB-side connection killed by firewall/NAT

Monitoring Pool Health

Pool problems usually look like "the app is slow" until you check the pool counters. Expose them somewhere you can see them:

Node.js: pool metrics endpoint
// Express endpoint to expose pool metrics (protect in production!)
app.get('/metrics/pool', (req, res) => {
  res.json({
    totalCount:   pool.totalCount,    // total connections in pool
    idleCount:    pool.idleCount,     // idle connections
    waitingCount: pool.waitingCount,  // requests waiting for a connection
  });
});

// Alert thresholds to watch:
// - waitingCount > 0 for sustained periods → pool too small
// - idleCount === totalCount always → pool too large
// - totalCount === max always → possible connection leak

Common Pooling Bugs and How to Fix Them

Bug Symptom Fix
Connection leak Pool exhausted; waitingCount grows indefinitely Always release() in finally block
Stale connections Random broken pipe errors after idle periods Set maxLifetime shorter than DB idle timeout; enable keep-alive
Pool too large DB CPU spikes, slower queries despite more connections Reduce max; use the pool size formula
Transaction on shared connection Interleaved queries corrupting transaction state Use explicit pool.connect() for transactions, not pool.query()
Serverless cold starts Rapid connection exhaustion on Lambda/Cloud Functions Use an external pooler like PgBouncer or RDS Proxy

Pooling in Serverless Environments

Serverless functions (AWS Lambda, Vercel Functions, Cloudflare Workers) break the usual model. Every concurrent invocation can be its own instance, and instances come and go on their own schedule. An in-process pool only helps within a single instance, so a traffic spike can turn into hundreds of instances, each with its own connections.

The usual fixes:

Lambda: reuse pool across invocations
const { Pool } = require('pg');

// Declare pool OUTSIDE the handler so it persists across warm invocations
let pool;

function getPool() {
  if (!pool) {
    pool = new Pool({
      connectionString: process.env.DATABASE_URL,
      max: 1, // Lambda: keep pool small, RDS Proxy handles the real pooling
      idleTimeoutMillis: 120_000,
      ssl: { rejectUnauthorized: false },
    });
  }
  return pool;
}

exports.handler = async (event) => {
  const client = await getPool().connect();
  try {
    const { rows } = await client.query('SELECT * FROM products LIMIT 10');
    return { statusCode: 200, body: JSON.stringify(rows) };
  } finally {
    client.release();
  }
};

What to Check Before Going to Production

My pre-launch checklist

  • Add up every pool. (max per instance × number of instances) plus workers, cron jobs, and migrations has to stay comfortably under max_connections. Autoscaling makes this number move, so plan for the max instance count, not the usual one.
  • Set maxLifetime below every idle timeout in the path. Cloud load balancers and NAT gateways drop idle TCP connections, and the pool only finds out when a query fails with Connection terminated unexpectedly or ECONNRESET.
  • Grep for pool.connect() and make sure each one has a matching release() in a finally.
  • Set a finite connection timeout and queue limit so a slow database turns into fast errors instead of a growing pile of hung requests.
  • If you add PgBouncer in transaction mode, test anything that relies on session state before you switch over.

When wouldn't I bother? A low-traffic internal tool or a CLI script that opens one connection and exits gains nothing from a pool. Classic PHP-FPM apps are often fine with plain connections until the connection count starts to hurt, at which point PgBouncer or ProxySQL is a better fix than persistent connections. And don't treat a bigger pool as a fix for slow queries. If waitingCount is high because each query takes two seconds, raising max just moves the queue into the database. Fix the query first.

Database Connection Pooling Performance Node.js PostgreSQL MySQL HikariCP
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.