Mustlist

Connection pooling for a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

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.

Forweb-appsaasapidashboarde-commerce
Not forstatic-export-sitebrowser-only-app-using-a-hosted-data-api

Must-have checklist

11 must · 4 should

Must

01

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.

Performance
02

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.

Performance
03

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.

Performance
04

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.

Performance
05

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.

Data
06

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.

Data
07

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.

Performance
08

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.

Data
09

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.

Performance
10

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.

Performance
11

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.

Security

Should

12

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.

Security
13

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.

Performance
14

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.

Cost
15

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.

Performance

Decisions to make

Asked before building

01Where 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 compared
RecommendedFits your answers

Small app pool behind a provider's transaction-mode pooler

Examples, not endorsements: Neon pooled endpoint, Supabase Supavisor, Supabase dedicated pooler, Amazon RDS Proxy

Best fit when
  • The app runs on serverless or autoscaling hosts whose instance count you don't control
  • Your Postgres provider offers a pooled endpoint or proxy
Avoid when
  • A component needs session state on one connection (give that part the direct URL)
  • The pooler runs in a different region from your functions
Trade-offs
  • 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

Best fit when
  • You host Postgres yourself or your provider has no pooler
  • You need control over pool sizes, timeouts and prepared statement limits
Avoid when
  • Nobody can patch and monitor another network service
Trade-offs
  • 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

Best fit when
  • Edge or Workers runtimes where a TCP pool can't outlive a request
  • Classic serverless with many cold starts and mostly one-shot queries
Avoid when
  • 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
Trade-offs
  • 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

Best fit when
  • A fixed number of Node.js servers or containers runs the app
  • Workers need LISTEN/NOTIFY or session advisory locks
Avoid when
  • Serverless or autoscaling hosts where instance count follows traffic
Trade-offs
  • 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

pg>=8.0.0 <9.0.0
  • Pool defaults: max 10, idleTimeoutMillis 10000, connectionTimeoutMillis 0 (waits forever); set an acquire timeout so a full pool fails fast.
  • Run a transaction on one client from pool.connect() and release it in finally; never send BEGIN or COMMIT through pool.query.
  • 8.x treats sslmode=require as verify-full with a warning, and pg 9 will switch to libpq semantics: write sslmode=verify-full.
Official docsnode-postgres.com
postgres>=3.0.0 <4.0.0
  • Pass prepare: false through a transaction pooler without prepared statement support (PgBouncer before 1.21, Supabase's shared pooler).
  • idle_timeout defaults to 0, so connections stay open until sql.end(); set it in serverless.
Official docsgithub.com
postgres>=4.0.0 <5.0.0
  • ssl: 'require' encrypts without checking the certificate; use ssl: 'verify-full'.
  • Set idle_timeout and the new queue_timeout (both default 0). Keep prepare on unless the pooler lacks prepared statements.
  • The server now infers parameter types, which changes how a Date is written outside UTC; infer: true restores v3 behaviour.
Official docsgithub.com
@prisma/client>=6.0.0 <7.0.0
  • Pool size is connection_limit in the URL; on serverless without a pooler, start at 1. Prisma Migrate uses directUrl.
  • Add pgbouncer=true only for PgBouncer before 1.21.0 or a pooler with similar limits.
Official docswww.prisma.io
@prisma/client>=7.0.0 <8.0.0
  • Pooling comes from the driver adapter: pass a configured pg Pool to new PrismaPg(pool); connection_limit no longer applies.
  • The CLI reads datasource.url from Prisma Config, so set it to the direct URL. Install prisma@7: npm latest is an 8.x release candidate.
Official docswww.prisma.io
@vercel/functions>=3.0.0 <4.0.0
  • 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.
Official docsvercel.com
@neondatabase/serverless>=1.0.0 <2.0.0
  • neon() over HTTP is a tagged template with only non-interactive sql.transaction([...]); interactive transactions need Pool or Client, 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.
drizzle-orm>=0.35.0 <1.0.0
  • Pass your own module-scope pool, drizzle({ client: pool }), to control limits and attachDatabasePool; point drizzle-kit's dbCredentials.url at the direct URL.
  • drizzle-orm/neon-http has no db.transaction(); use neon-serverless or a TCP driver for transactions.
Official docsorm.drizzle.team

Verify checks

9 checks
01

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.

integrationPerformance
02

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.

e2ePerformance
03

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.

integrationPerformance
04

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.

integrationData
05

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.

integrationPerformance
06

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.

scanData
07

The migration command reads the direct URL and succeeds while the app serves traffic through the pooler.

integrationData
08

Connecting with a wrong host name or an untrusted certificate fails, and pg_stat_ssl shows ssl true for the app's connections.

integrationSecurity
09

The runtime role gets a permission error for CREATE, ALTER and DROP, while the migration role on the direct URL succeeds.

integrationSecurity

Common mistakes

  • Constructing a pool or ORM client inside a route handler, Server Action or component, or skipping the globalThis cache in development.
  • Pointing serverless code at the direct endpoint with the driver's default pool size.
  • Running migrations, pg_dump or LISTEN through the transaction pooler.
  • Relying on SET, session advisory locks or SQL PREPARE through a transaction pooler.
  • Setting max: 1 on Fluid compute, or leaving the acquire timeout at 0.
  • Trusting sslmode=require or rejectUnauthorized: false to protect against interception.

Sources

37 sources
PostgreSQL: Connection settings (max_connections, reserved slots)www.postgresql.orgPostgreSQL: How connections are establishedwww.postgresql.orgPostgreSQL: Client connection defaults (statement_timeout, idle_in_transaction_session_timeout)www.postgresql.orgPostgreSQL: ALTER ROLEwww.postgresql.orgPostgreSQL: SET (SET LOCAL)www.postgresql.orgPostgreSQL: Explicit locking (advisory locks)www.postgresql.orgPostgreSQL: libpq SSL support (sslmode)www.postgresql.orgPgBouncer: Features (session vs transaction pooling)www.pgbouncer.orgPgBouncer: Configuration (max_prepared_statements, pool sizes)www.pgbouncer.orgPgBouncer: Changelogwww.pgbouncer.orgnode-postgres: Pool APInode-postgres.comnode-postgres: SSLnode-postgres.comnode-postgres: Queries (prepared statements)node-postgres.compg-connection-string: sslmode handling (source)github.comPostgres.js README (options, prepared statements, connection poolers)github.comVercel: @vercel/functions API reference (attachDatabasePool)vercel.comVercel: Efficiently manage database connection pools with Fluid computevercel.comVercel: Fluid computevercel.comVercel: Configuring regions for Vercel Functionsvercel.comattachDatabasePool source (vercel/vercel)github.comPrisma ORM v7: Connection poolwww.prisma.ioPrisma ORM v7: Configure Prisma Client with PgBouncerwww.prisma.ioPrisma ORM v7: Deploy to Vercelwww.prisma.ioPrisma ORM: Upgrade to v7www.prisma.ioPrisma ORM: Next.js development practices (hot reload)www.prisma.ioPrisma ORM v6: Database connections (serverless)www.prisma.ioNeon: Connection poolingneon.comNeon: Choosing a connection methodneon.comNeon: Connecting from Vercelneon.comNeon serverless driverneon.comSupabase: Connect to your databasesupabase.comAmazon RDS Proxy: Avoiding pinningdocs.aws.amazon.comDrizzle: Connect to Supabaseorm.drizzle.teamDrizzle: Connect to Neonorm.drizzle.teamNext.js: Data security guidenextjs.orgNext.js: runtime route segment confignextjs.orgNext.js: Environment variablesnextjs.org