Ever watched your serverless Next.js API crash during a traffic spike with FATAL: sorry, too many clients already?
Every serverless function instance opens its own PostgreSQL connection, and Postgres cannot handle thousands of idle TCP sockets without burning RAM and CPU.
The good news is that proper connection pooling solves this completely. In this guide, we show you how to tune PgBouncer for serverless functions and node-postgres (pg.Pool) for long-running Node.js APIs.
Executive Summary
- Why Postgres Struggles: Each active PostgreSQL backend process consumes several megabytes of RAM, so raising
max_connectionsto 2,000 hurts throughput. - Use Transaction Pooling for Serverless: PgBouncer in
transactionmode multiplexes thousands of short-lived serverless requests over 20 to 40 real database connections. - Keep
pg.PoolSmall in Containers: For long-running Node.js servers, capmaxconnections per instance (usually 10 to 20) so total connections stay under Postgres limits. - Disable Prepared Statements in Transaction Mode: ORMs like Prisma and Drizzle require disabling client-side prepared statements when talking through PgBouncer transaction pooling.
Table of Contents
- Why Serverless APIs Exhaust PostgreSQL Connections
- PgBouncer Pooling Modes Compared
- Method 1: Configure PgBouncer for Serverless APIs
- Method 2: Tune
pg.Poolin Long-Running Node.js Servers - Frequently Asked Questions
- You May Also Like
- Primary Sources and References
Why Serverless APIs Exhaust PostgreSQL Connections
In a traditional server, one Node.js process maintains a single shared pool of 15 connections. In a serverless platform, 300 parallel requests can spin up 300 isolated function containers in seconds.
If each container opens even 2 connections, PostgreSQL suddenly faces 600 concurrent sockets and TLS handshakes. Once max_connections fills up, new user requests fail immediately.
PgBouncer Pooling Modes Compared
PgBouncer sits between your API and PostgreSQL, holding a small set of warm backend connections open. Choosing the right pool_mode makes all the difference.
| Pool Mode | When Connection Returns to Pool | Serverless Compatible? | Caveat |
|---|---|---|---|
| Session | Only when client disconnects | Poor (does not free idle serverless sockets) | Holds connection for full container lifetime |
| Transaction | Right after each SQL transaction finishes | Best (recommended for serverless) | No session-level SET, LISTEN, or named prepared statements (unless configured) |
| Statement | After every single SQL statement | Rarely used | Multi-statement transactions are disallowed |

Method 1: Configure PgBouncer for Serverless APIs
When deploying Next.js API routes or AWS Lambda functions, always route database traffic through PgBouncer in transaction mode (or a managed HTTP/WebSocket pooler).
Step 1: Set pool_mode = transaction in pgbouncer.ini
Configure PgBouncer to accept thousands of lightweight client connections while keeping real Postgres connections lean:
[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
pool_mode = transaction
max_client_conn = 2000
default_pool_size = 25
reserve_pool_size = 5Notice how max_client_conn = 2000 lets up to 2,000 serverless workers connect, while default_pool_size = 25 keeps PostgreSQL focused on executing fast queries across 25 warm connections.
Step 2: Update Your ORM / Driver Connection String
In transaction pooling, consecutive queries from your app might run on different backend Postgres processes. Disable client-side prepared statements in your driver so Postgres does not throw prepared statement "..." does not exist:
- Prisma: Append
?pgbouncer=truetoDATABASE_URL. - Postgres.js: Pass
{ prepare: false }when initializingpostgres(url, { prepare: false }). - node-postgres (
pg): Setmax: 1inside serverless functions so each function instance holds at most one lightweight client socket to PgBouncer.
Pro Tip: Keep a separate direct (non-pooled)
DIRECT_URLfor database migrations (prisma migrateordrizzle-kit), since schema migrations often use session-level locks and advisory locks.
Method 2: Tune pg.Pool in Long-Running Node.js Servers
If your API runs in Docker containers or Kubernetes pods rather than serverless functions, pg.Pool inside your Node.js app handles pooling directly.
Step 1: Size Your Pool Based on CPU Cores and Pod Count
More connections do not mean faster queries. Start with default_pool_size near (CPU cores 2) to (CPU cores 4) on your PostgreSQL server, then divide that total budget by your maximum number of Node.js pods.
For example, if Postgres allows 100 app connections and you run up to 5 Node.js containers, set max: 15 per container (75 total, leaving 25 for admin tasks and migrations).
Step 2: Set Timeouts and Graceful Shutdown
Configure strict timeouts so dead network sockets do not pile up, and close the pool cleanly on SIGTERM:
import { Pool } from "pg";
export const pool = new Pool({
connectionString: process.env.DATABASE_URL,
max: 15,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 3000,
});
process.on("SIGTERM", async () => {
await pool.end();
process.exit(0);
});Note: Always release clients inside a
try { ... } finally { client.release(); }block whenever you manually callpool.connect()for multi-step transactions. Forgettingclient.release()leaks connections until your entire API freezes.
Frequently Asked Questions
Why not just increase max_connections in PostgreSQL to 5,000?
Each PostgreSQL connection spawns a separate OS process that allocates memory and adds lock-contention overhead. Beyond a few hundred active connections, throughput actually drops sharply as CPU cores spend all their time context-switching.
Should I use PgBouncer even with a managed cloud Postgres database?
Yes, especially for serverless apps. Many managed Postgres providers include a built-in PgBouncer port (often port 6543 or a -pooler hostname) specifically for serverless and edge runtimes.
Can I use LISTEN/NOTIFY through PgBouncer transaction mode?
No. LISTEN/NOTIFY requires a persistent session connection. Run pub/sub listeners on a dedicated direct connection or use Redis for real-time notifications.
How do I know if my connection pool is too small?
Monitor your app logs for timeout exceeded when trying to connect (connectionTimeoutMillis) and watch PgBouncer’s SHOW POOLS; output for non-zero cl_waiting counts.
You May Also Like
We hope this guide helped you tune PostgreSQL connection pooling for serverless and high-traffic APIs. Written by the TeckScaler Editorial Engineering Team. Continue building fast backend architectures:
- Low-Latency Web Apps with Next.js, Node.js, and PostgreSQL.
- Read Safe JSON to YAML Conversion for Kubernetes and CI/CD Pipelines.
- Validate your Docker Compose and Kubernetes configs locally with our free JSON to YAML Converter.
Primary Sources and References
- PgBouncer Configuration Documentation (Official PgBouncer Documentation)
- PostgreSQL Connections and Authentication Config (Official PostgreSQL Documentation)
- node-postgres (
pg.Pool) API Reference (Official node-postgres Documentation)



