Create one small pool per instance at module scope, point serverless code at a transaction-mode pooler (provider endpoint or PgBouncer), keep a direct URL for migrations and session features, keep session state off the pooler, and verify TLS certificates.
Must-have checklist
Must
Create one pool or ORM client per server instance, at module scope in a server-only module; never construct Pool, postgres() or PrismaClient inside a handler, Server Action or component.
A pool built per request opens fresh connections on every call and leaves them open until they time out.
In development, store the pool or client on globalThis and reuse it, so next dev hot reloads don't open a new pool on every edit.
Next.js reloads modules on change; Prisma documents this creating many client instances, each with its own pool.
Write down a connection budget: peak instances × per-instance max, plus workers, cron and migrations, must stay below max_connections minus reserved slots, or within the pooler's limits.
Postgres runs one process per connection; max_connections is typically 100 and 3 slots are reserved for superusers by default.
On serverless or autoscaling hosts, give the runtime a transaction-mode pooler URL (provider pooled endpoint, RDS Proxy or PgBouncer), not the database's direct endpoint.
Instance count follows traffic, so per-instance pools multiply; a transaction pooler caps server connections.
Run migrations, schema pushes, pg_dump and LISTEN over a separate direct (unpooled) URL; use the pooled URL only for request handling.
Prisma documents Migrate failing through PgBouncer, and Neon says to use direct connections for migrations and pg_dump.
Through a transaction pooler keep no session state: use SET LOCAL or role settings instead of SET, pg_advisory_xact_lock instead of session locks, and no LISTEN, WITH HOLD cursors or SQL PREPARE.
PgBouncer lists these as never supported in transaction mode; the next transaction may run on another server connection.
Match prepared statements to the pooler: PgBouncer 1.21+ with max_prepared_statements above 0 supports them; otherwise (for example Supabase's shared pooler) set postgres.js prepare: false.
max_prepared_statements defaults to 200 since PgBouncer 1.24; Supabase's shared pooler has no prepared statements in transaction mode.
Run each transaction on one checked-out client (pg pool.connect() or the ORM's transaction API) and release it in finally; never send BEGIN and COMMIT through pool.query.
node-postgres may send each pool.query call to a different client, splitting the transaction.
Set an acquire timeout of a few seconds (pg connectionTimeoutMillis, postgres.js 4 queue_timeout) and return 503 when the pool is exhausted instead of waiting until the function times out.
Both default to 0, which waits forever, and Prisma 7 inherits the pg default through its adapter.
On Vercel Fluid compute, call attachDatabasePool(pool) right after creating a pg pool, use a short idleTimeoutMillis (Vercel's example is 5 seconds), and never set max: 1.
Idle timers don't run while an instance is suspended; Vercel says max 1 doesn't reduce connections and harms concurrency.
Require TLS with certificate and host checks: sslmode=verify-full (pg) or ssl: 'verify-full' (postgres.js 4), with the provider's CA if it isn't public; never rejectUnauthorized: false.
libpq's require mode encrypts but doesn't stop man-in-the-middle attacks, and pg 9 will switch require to libpq semantics.
Should
Connect the app with a role that has only the data rights it needs (no DDL) and run migrations with a separate owner role on the direct URL; keep both URLs in server-only variables.
A leaked or injected app connection then can't alter or drop tables.
Set statement_timeout and idle_in_transaction_session_timeout on the app role with ALTER ROLE ... SET, so a stuck request can't hold a pooled server connection indefinitely.
Role defaults apply whenever the role starts a session, so they survive transaction pooling, unlike a session-level SET.
Fix pooling before buying a larger database tier only to raise max_connections; idle connections from serverless instances hold memory without doing work.
Postgres starts one backend process per connection, and providers such as Neon tie max_connections to compute size.
Alert on connection count versus max_connections, pool wait time, pooler client waits and, on RDS Proxy, DatabaseConnectionsCurrentlySessionPinned.
RDS Proxy pins sessions on SET, temporary tables and advisory locks, which quietly stops connection reuse.
Decisions to make
Asked before building01Where will the Next.js server code run?
02Who runs your Postgres?
03Does any code need session state (LISTEN/NOTIFY, session advisory locks, SET, temporary tables, WITH HOLD cursors)?
04Which driver or ORM talks to Postgres?
05At peak, could instances × pool size exceed the database's max_connections?
06Do most requests land on cold, short-lived instances (low or very spiky traffic)?
Options
4 comparedSmall app pool behind a provider's transaction-mode pooler
Examples, not endorsements: Neon pooled endpoint, Supabase Supavisor, Supabase dedicated pooler, Amazon RDS Proxy
- The app runs on serverless or autoscaling hosts whose instance count you don't control
- Your Postgres provider offers a pooled endpoint or proxy
- A component needs session state on one connection (give that part the direct URL)
- The pooler runs in a different region from your functions
- No session state across transactions in transaction mode
- Prepared statement support depends on the pooler and its settings
- Two connection strings to manage (pooled and direct)
Self-run PgBouncer in transaction mode
Examples, not endorsements: PgBouncer
- You host Postgres yourself or your provider has no pooler
- You need control over pool sizes, timeouts and prepared statement limits
- Nobody can patch and monitor another network service
- You run, scale and patch it; 1.25.1 to 1.26.1 all shipped security fixes
- Defaults are low for serverless: max_client_conn 100, default_pool_size 20
- A single instance is a single point of failure
HTTP or WebSocket serverless driver
Examples, not endorsements: Neon serverless driver
- Edge or Workers runtimes where a TCP pool can't outlive a request
- Classic serverless with many cold starts and mostly one-shot queries
- You need interactive transactions over HTTP
- Vercel Fluid compute, where Neon recommends pg over TCP with a pool
- Your database provider has no such driver
- Provider-specific API and lock-in
- WebSocket Pool or Client must be created and closed inside each request on edge runtimes
Direct connections with one small pool per long-running server
- A fixed number of Node.js servers or containers runs the app
- Workers need LISTEN/NOTIFY or session advisory locks
- Serverless or autoscaling hosts where instance count follows traffic
- The budget must be recomputed whenever replicas are added
- Rolling deploys briefly run old and new instances side by side
Why this approach
Serverless hosts start as many instances as traffic needs and each instance holds its own pool, so connections grow with instances, not with anything you configure; Postgres runs one backend process per connection and max_connections is typically 100. A transaction-mode pooler run by your provider multiplexes many client connections onto a small, fixed set of server connections, so a traffic spike or deploy can't exhaust the database. Keep one small pool per instance at module scope (with attachDatabasePool on Vercel Fluid) pointed at that pooler, and a direct URL for migrations and session features. Run PgBouncer yourself when you host Postgres, use a direct small pool when a fixed set of long-running servers fits the budget, and use an HTTP driver for edge runtimes or cold-start-heavy classic serverless.
Lenses
Require TLS that checks the certificate and host name: libpq's require encrypts but doesn't stop a man-in-the-middle, so write verify-full and supply the provider's CA when it isn't publicly trusted. Never ship rejectUnauthorized: false. Keep the pooled and direct URLs in unprefixed server-side variables (Next.js inlines NEXT_PUBLIC_ values into browser bundles), import the database module only from server code, and keep it on the Node.js runtime (Edge is deprecated in Next.js 16). Give the runtime a role without DDL rights; only the migration step uses the owner role on the direct URL. If you run PgBouncer, keep it off the public internet and patch it: 1.25.1 fixed a startup-packet search_path flaw allowing unauthenticated SQL when track_extra_parameters included it.
Version notes
- Pool defaults:
max10,idleTimeoutMillis10000,connectionTimeoutMillis0 (waits forever); set an acquire timeout so a full pool fails fast. - Run a transaction on one client from
pool.connect()and release it infinally; never send BEGIN or COMMIT throughpool.query. - 8.x treats
sslmode=requireasverify-fullwith a warning, and pg 9 will switch to libpq semantics: writesslmode=verify-full.
- Pass
prepare: falsethrough a transaction pooler without prepared statement support (PgBouncer before 1.21, Supabase's shared pooler). idle_timeoutdefaults to 0, so connections stay open untilsql.end(); set it in serverless.
ssl: 'require'encrypts without checking the certificate; usessl: 'verify-full'.- Set
idle_timeoutand the newqueue_timeout(both default 0). Keepprepareon unless the pooler lacks prepared statements. - The server now infers parameter types, which changes how a
Dateis written outside UTC;infer: truerestores v3 behaviour.
- Pool size is
connection_limitin the URL; on serverless without a pooler, start at 1. Prisma Migrate usesdirectUrl. - Add
pgbouncer=trueonly for PgBouncer before 1.21.0 or a pooler with similar limits.
- Pooling comes from the driver adapter: pass a configured pg Pool to
new PrismaPg(pool);connection_limitno longer applies. - The CLI reads
datasource.urlfrom Prisma Config, so set it to the direct URL. Installprisma@7: npmlatestis an 8.x release candidate.
- Call
attachDatabasePool(pool)once, after creating a pg pool at module scope; a postgres.js client throws 'Unsupported database pool type'. - After each release it keeps the instance alive for
idleTimeoutMillis(10 s if unset) plus 100 ms; Vercel's guide uses 5 s.
neon()over HTTP is a tagged template with only non-interactivesql.transaction([...]); interactive transactions needPoolorClient, created and closed within one request on edge runtimes.- On Vercel Fluid compute, Neon recommends pg over TCP with a pool instead of this driver.
- Pass your own module-scope pool,
drizzle({ client: pool }), to control limits andattachDatabasePool; point drizzle-kit'sdbCredentials.urlat the direct URL. drizzle-orm/neon-httphas nodb.transaction(); useneon-serverlessor a TCP driver for transactions.
Verify checks
Sending 50 concurrent requests to one warm instance raises the app role's connections in pg_stat_activity by no more than the pool's max.
A load test at expected peak, with scale-out and a deploy during the test, keeps total connections below max_connections minus reserved slots and logs no connection-limit errors.
With every pool client checked out, the next request fails within the acquire timeout with a 503 instead of hanging until the platform's function timeout.
A handler that throws mid-transaction rolls back and returns its client; the pool's idle count returns to baseline and no session stays idle in transaction.
Through the production pooler, the same parameterized query run 1,000 times from concurrent instances never fails with a prepared statement "already exists" or "does not exist" error.
Code that uses the pooled URL contains no session-level SET, LISTEN, pg_advisory_lock, WITH HOLD cursor or SQL PREPARE; code that needs them uses the direct URL.
The migration command reads the direct URL and succeeds while the app serves traffic through the pooler.
Connecting with a wrong host name or an untrusted certificate fails, and pg_stat_ssl shows ssl true for the app's connections.
The runtime role gets a permission error for CREATE, ALTER and DROP, while the migration role on the direct URL succeeds.
Common mistakes
- Constructing a pool or ORM client inside a route handler, Server Action or component, or skipping the
globalThiscache in development. - Pointing serverless code at the direct endpoint with the driver's default pool size.
- Running migrations,
pg_dumporLISTENthrough the transaction pooler. - Relying on
SET, session advisory locks or SQLPREPAREthrough a transaction pooler. - Setting
max: 1on Fluid compute, or leaving the acquire timeout at 0. - Trusting
sslmode=requireorrejectUnauthorized: falseto protect against interception.