PostgreSQLDev & Eng

Content type: Hands-on

10 min read

PostgreSQL with Next.js on Vercel: the per-instance pool that prevents too many connections in production

A fieldnotes guide published on Planet PostgreSQL shows how to set up a node-postgres pool per function instance on Vercel, without leaking a client in a transaction or hitting the database's connection limit.

Article · Dev & Eng
Reading
10 min
Code
7

PostgreSQL with Next.js on Vercel: the per-instance pool that prevents too many connections in production

A fieldnotes guide published on Planet PostgreSQL shows how to set up a node-postgres pool per function instance on Vercel, without leaking a client in a transaction or hitting the database's connection limit.

A fieldnotes guide published on Planet PostgreSQL shows how to set up a node-postgres pool per function instance on Vercel, without leaking a client in a transaction or hitting the database's connection limit.

The symptom that deceives

The endpoint works on your machine. After deployment, or during a peak hour, PostgreSQL starts responding with too many connections, or worse: requests keep waiting even though the database's CPU is practically idle. The most common reaction is to increase the number of function instances. This almost always makes things worse, because each new instance opens its own group of connections against the same database.

Before touching any limit, you need to know at which layer the request is stuck. A fieldnotes guide published on Planet PostgreSQL describes the full path of a connection in a Next.js application running on Vercel functions, with node-postgres 8.23.1, @vercel/functions 3.11.3 and Node.js 24. It's this path, not a guessed max value, that defines where the bottleneck is.

The path of a connection, layer by layer

A request in the App Router passes through four points before the query actually runs:

  1. It waits for a free client in the local pg pool, inside the function instance.
  2. If the database provider runs a pooler (PgBouncer, for instance), that client connects to the pooler.
  3. The pooler, in turn, may wait for a free backend in PostgreSQL.
  4. The query has reached the backend, but may still wait on a lock before executing.

In short: if a client gets stuck without being released, the queue forms inside the application itself, while PostgreSQL sees an idle connection. If many instances each open several clients, what runs out is the provider's connection budget. If a query is stuck on a lock, increasing the local pool just sends more traffic into the same wait. The error, the client acquisition time, the pool counters, the provider's metrics and the database activity need to be read together: a function duration timeout tells you when the platform gave up waiting, not where the time was spent.

A pool per instance, created only once

The pool needs to be created at module scope, so that requests served by the same instance reuse the same connections. With Fluid Compute, one instance can serve concurrent invocations, but it still owns a single pool. I install the application's dependencies like this:

bash
npm install pg@8.23.1 @vercel/functions@3.11.3 server-only
npm install --save-dev @types/pg@8.23.1

With DATABASE_URL defined as a server-side-only environment variable, using the provider's endpoint and TLS configuration, the pool looks like this in lib/db.ts:

ts
import 'server-only'
import { Pool } from 'pg'
import { attachDatabasePool } from '@vercel/functions'

const globalForPool = globalThis as typeof globalThis & {
  devfieldnotesPool?: Pool
}

function createPool() {
  const connectionString = process.env.DATABASE_URL
  if (!connectionString) throw new Error('Missing DATABASE_URL')

  const pool = new Pool({
    connectionString,
    max: 5,
    connectionTimeoutMillis: 1500,
    idleTimeoutMillis: 5000,
    application_name: 'devfieldnotes-nextjs',
  })

  pool.on('error', (error) => {
    console.error('database-pool-idle-error', { name: error.name })
  })

  attachDatabasePool(pool)
  return pool
}

export const pool = globalForPool.devfieldnotesPool ?? createPool()

if (process.env.NODE_ENV !== 'production') {
  globalForPool.devfieldnotesPool = pool
}

The max: 5 here is just an illustrative starting point: the right value depends on the database's connection budget, the observed concurrency and the typical query duration, not on a market convention. The attachDatabasePool function integrates the cleanup of idle connections into the function's lifecycle on Vercel; it doesn't release clients that the code itself left stuck, that remains the responsibility of whoever borrowed the client.

A transaction doesn't switch clients halfway through

This is where the most common, and most silent, mistake lives: calling BEGIN via pool.query() and then continuing to use pool.query() for the following calls. Each call can grab a different client from the pool, and the transaction simply stops existing as a unit. A transaction belongs to a specific connection; the client needs to be obtained once and used until COMMIT or ROLLBACK.

ts
import type { Pool, PoolClient } from 'pg'

export async function inTransaction<T>(
  pool: Pool,
  work: (client: PoolClient) => Promise<T>,
): Promise<T> {
  const client = await pool.connect()
  let discardClient = false

  try {
    await client.query('BEGIN')
    await client.query("SET LOCAL statement_timeout = '3s'")
    await client.query("SET LOCAL lock_timeout = '1s'")

    const result = await work(client)
    await client.query('COMMIT')
    return result
  } catch (error) {
    try {
      await client.query('ROLLBACK')
    } catch {
      discardClient = true
    }
    throw error
  } finally {
    client.release(discardClient)
  }
}

If ROLLBACK fails, the client is discarded from the pool instead of being returned: a client in an undefined state shouldn't go back into circulation. The statement_timeout and lock_timeout limits apply to each statement in isolation, not to the whole transaction: a callback with several instructions can, combined, take well over three seconds. One more thing worth watching: never call an external API, generate an embedding or wait on an AI model while the transaction is open. That keeps a client busy for the duration of the network wait. Resolve whatever is external before opening the transaction.

Connecting the pool to a route

A minimal endpoint, with no application table at all, is already enough to validate connectivity in a preview deployment:

ts
import { pool } from '@/lib/db'
import { inTransaction } from '@/lib/transaction'

export const runtime = 'nodejs'

export async function GET() {
  const requestId = crypto.randomUUID()

  try {
    const result = await inTransaction(pool, (client) =>
      client.query<{ database_time: string }>(
        'SELECT now()::text AS database_time',
      ),
    )

    return Response.json(result.rows[0], {
      headers: { 'Cache-Control': 'no-store' },
    })
  } catch (error) {
    console.error('database-read-failed', {
      requestId,
      name: error instanceof Error ? error.name : 'UnknownError',
      total: pool.totalCount,
      idle: pool.idleCount,
      waiting: pool.waitingCount,
    })

    return Response.json(
      { error: 'Database unavailable', requestId },
      { status: 503 },
    )
  }
}

The runtime = 'nodejs' declaration isn't cosmetic: the pg driver speaks TCP directly with PostgreSQL, and this behavior needs to be confirmed against the version of Next.js in use. In the error log, the pool's own totalCount, idleCount and waitingCount counters are worth more than the error message alone: they tell you whether the application had spare capacity or whether the local queue was already full when the request failed.

Reproducing the client leak before it happens in production

Editor's note: the code in this section (the local lab pool-lab.mjs) was not run as described and contains an unverified module import inconsistency (a reference to ./lib/transaction.js when the correct file, created earlier in this same tutorial, is lib/transaction.ts), in addition to missing the explicit step of recreating this lib folder in the disposable project before running the script. Treat this excerpt as a conceptual script, not as a ready-to-copy-and-paste command, and adjust the import path and folder structure before reproducing it locally.

The original guide describes a local lab that fixes max: 1 to force a single client to occupy the pool's entire capacity, and then verifies that a second query stays queued until the first client is released. To reproduce the script, create a disposable project folder, save the lib/transaction.ts shown earlier inside a lib subfolder, and save the script below as pool-lab.mjs next to that lib folder (both need to exist on disk before running the script). A trimmed-down version of this script:

js
import assert from 'node:assert/strict'
import { setImmediate } from 'node:timers/promises'
import { Pool } from 'pg'
import { inTransaction } from './lib/transaction.ts'

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 1,
})

const held = await pool.connect()
const queued = pool.query('SELECT 1 AS value').then(
  (result) => ({ ok: true, result }),
  (error) => ({ ok: false, error }),
)

await setImmediate()
assert.equal(pool.waitingCount, 1)
console.log('Um cliente retido coloca a próxima query na fila')

held.release()
const outcome = await queued
assert.equal(outcome.ok, true)
console.log('Liberar o cliente deixa a query enfileirada terminar')

await assert.rejects(inTransaction(pool, async (client) => {
  await client.query('CREATE TEMP TABLE pooling_rollback_probe (id integer)')
  await client.query('SELECT 1 / 0')
}))

const rolledBack = await pool.query(
  "SELECT to_regclass('pg_temp.pooling_rollback_probe') IS NULL AS cleared",
)
assert.equal(rolledBack.rows[0].cleared, true)
console.log('A transação que falhou desfez a criação da tabela')

await pool.end()

To run this locally, with the lib/transaction.ts folder already recreated next to the script (step described above), a disposable project is all it takes:

bash
npm init -y
npm pkg set type=module
npm install pg@8.23.1
node --env-file=.env.local pool-lab.mjs

The guide reports that these checks passed on Node.js 24.19.0 with pg 8.23.1, using PostgreSQL 18.7 served by PGlite 0.5.17 and pglite-socket 0.2.20, and that the TypeScript examples passed type checking with TypeScript 5.9.3. This is a single-client test, useful for validating the acquisition, release and rollback logic before any real traffic: it doesn't replace a concurrency test against the database provider actually used in production, with its pooler, its TLS and its network latency.

Sizing with all instances in mind, not just one

A max: 5 per instance looks conservative until you multiply it by the number of active instances. Twelve saturated instances with max: 5 each can occupy close to sixty backends in direct connection to PostgreSQL, not counting workers, Cron routes and preview deployments running in parallel during a release.

An initial capacity estimate: one hundred operations per second that each hold a client for 50 milliseconds imply around five clients occupied, on average. This is an average occupancy estimate, not a ceiling, and traffic spikes or slow queries call for additional headroom that's actually measured, not deduced on a spreadsheet.

With a provider pooler in the middle of the path, count the application-to-pooler and pooler-to-PostgreSQL connections separately. The application may have spare local capacity while the pooler, on the other side, is already waiting for a free backend. Reducing the time each client stays busy, by shortening transactions and investigating slow queries, pays off more than simply increasing max.

The provider's pooler contract is not optional

Poolers in transaction mode, such as PgBouncer, assign a backend to a transaction and return it right afterward. This has a direct consequence for session state: SET configurations outside the LOCAL scope, session-level advisory locks and SQL-level PREPARE have limited support in this mode. Protocol-level prepared statements follow their own rule. The exact combination of provider and driver in use needs to be checked against its documentation before assuming something will work.

Migrations, backups and any operation that needs a persistent session should use the connection method the provider documents for that purpose, not the application's traffic pooler. And the credential used by the application shouldn't have database administrator privileges: separating the routine read-and-write role from the migration role is part of a healthy permissions model, not an exaggeration of security.

Measure the wait before touching any limit

From the diagnostic connection, with the appropriate privileges, this query groups PostgreSQL activity by application and state:

sql
SELECT
  application_name,
  state,
  wait_event_type,
  wait_event,
  count(*) AS connections,
  max(now() - xact_start) AS oldest_transaction
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY application_name, state, wait_event_type, wait_event
ORDER BY connections DESC;

What matters here are idle in transaction connections, prolonged lock waits and a growing population of idle sessions. Combined with the application pool's totalCount, idleCount and waitingCount, and with the provider pooler's client and server metrics, this query shows which specific resource is close to its limit before the next traffic spike actually hits it. Increasing a max without this reading is treating the symptom while leaving the cause intact.

Translated from the Brazilian Portuguese original · Read the original