DEV Community

Young Gao
Young Gao

Posted on

Database Connection Pooling: Why Your App Crashes Under Load (Fix Guide 2026)

100 concurrent users. 100 database connections. PostgreSQL default max_connections is 100. Connection 101 gets rejected. Your app returns 500.

The Problem

Opening a database connection takes 20-50ms (TCP handshake, auth, SSL). Without pooling, every request opens a new connection. Under load, you exhaust the DB connection limit.

Connection Pool Basics

A pool maintains a set of open connections. Requests borrow a connection, use it, and return it.

import { Pool } from "pg";
const pool = new Pool({ max: 20, idleTimeoutMillis: 30000, connectionTimeoutMillis: 5000 });
Enter fullscreen mode Exit fullscreen mode

Sizing Your Pool

Formula: pool_size = (core_count * 2) + disk_spindles. For SSD with 4 cores: (4 * 2) + 1 = 9. Start with 10-20 and benchmark.

More connections does NOT mean better performance. Beyond the optimal point, context switching overhead degrades throughput.

Connection Leaks

The #1 pool killer. Borrow a connection and never return it:

// BAD - connection never released on error
const client = await pool.connect();
await client.query("SELECT ..."); // if this throws, client leaks

// GOOD - always release in finally
const client = await pool.connect();
try { await client.query("SELECT ..."); }
finally { client.release(); }
Enter fullscreen mode Exit fullscreen mode

PgBouncer for Multi-Service

Multiple services sharing one PostgreSQL? Application-level pools multiply. 5 services x 20 connections = 100 connections. PgBouncer sits between apps and DB, multiplexing thousands of app connections onto fewer DB connections.

Monitoring Your Pool

Track: total connections, idle connections, waiting queries, connection wait time. Alert when waiting > 0 sustained.


Part of my Production Backend Patterns series. Follow for more practical backend engineering.


If this was useful, consider:


You Might Also Like

Follow me for more production-ready backend content!


If this helped you, buy me a coffee on Ko-fi!

Top comments (0)