Tune PostgreSQL Connection Pooling for Serverless APIs

Tune PostgreSQL Connection Pooling for Serverless APIs

Learn how to tune PostgreSQL connection pooling with PgBouncer transaction mode and node-postgres pg.Pool to stop connection exhaustion in serverless APIs.

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_connections to 2,000 hurts throughput.
  • Use Transaction Pooling for Serverless: PgBouncer in transaction mode multiplexes thousands of short-lived serverless requests over 20 to 40 real database connections.
  • Keep pg.Pool Small in Containers: For long-running Node.js servers, cap max connections 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

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 ModeWhen Connection Returns to PoolServerless Compatible?Caveat
SessionOnly when client disconnectsPoor (does not free idle serverless sockets)Holds connection for full container lifetime
TransactionRight after each SQL transaction finishesBest (recommended for serverless)No session-level SET, LISTEN, or named prepared statements (unless configured)
StatementAfter every single SQL statementRarely usedMulti-statement transactions are disallowed
Tune PostgreSQL Connection Pooling for Serverless APIs Data Chart

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 = 5

Notice 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=true to DATABASE_URL.
  • Postgres.js: Pass { prepare: false } when initializing postgres(url, { prepare: false }).
  • node-postgres (pg): Set max: 1 inside serverless functions so each function instance holds at most one lightweight client socket to PgBouncer.

Pro Tip: Keep a separate direct (non-pooled) DIRECT_URL for database migrations (prisma migrate or drizzle-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 call pool.connect() for multi-step transactions. Forgetting client.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:

Primary Sources and References

Leave a Reply

Your email address will not be published. Required fields are marked *