Why Your Next.js App Overflows PostgreSQL Connections (And How to Fix It)
Your Next.js app has one database module. It creates one pool, lazily, and every route imports it. The pool's max is small and the database plan's connection limit is known. The arithmetic fits. Then, at the busiest moment of the day, every query fails at once:
PostgresError: remaining connection slots are reserved for roles with the SUPERUSER attribute code: '53300' Session lookups, API routes, background callbacks, all of them, from a single app instance. Counting connections on the database side shows far more than one pool's worth, all from the same process.
That is what happened to a production Next.js app we run on a small managed PostgreSQL cluster. The cause was not a leak and not a slow query. Next.js compiles server code into several separately bundled entry kinds, and each compiled copy of your database module has its own module scope. A let pool = null singleton that is correct in plain Node becomes one pool per copy, each opening up to max connections.
The fix is one line: keep the client on globalThis instead of in module scope. This post reproduces the problem on a clean Next.js 16 app against a PostgreSQL with a 12-connection limit, shows the fix, and adds a boot-time check so the budget cannot drift again.
How Next.js Compiles Your Database Module
A Next.js production build does not produce one server program. Route handlers, pages with their server components and server actions, the proxy.ts file (the former middleware), and the instrumentation.ts hook are compiled as separate entry kinds, each with its own module graph. A module imported by more than one of them is compiled into each, and the compiled copies do not share state. What does survive across copies is the JavaScript global object: every copy runs in the same Node.js process and sees the same globalThis.
This is easy to misdiagnose from the build output. In our app the database module appeared in 13 chunk files, which suggested 13 pools. Several files carry the same module id, which the runtime instantiates once, so the real count was three. The number that matters is how many entry kinds reach the module, and the reliable way to get it is to count at runtime.
Prerequisites
- Node.js 24. The examples use Next.js 16.4.3 with Turbopack, the default bundler, and postgres.js 3.4.9. The behavior is the same with Drizzle or any other client built on a pool.
- A PostgreSQL you can start with a low limit. The examples use PostgreSQL 18.4 with
max_connections=12, and a non-superuser role inDATABASE_URL, because superusers bypass the reserve and never see the error. -
psqlas a superuser, to count backends inpg_stat_activity.
Step 1: Count the Pools One Process Creates
Start from the pattern most codebases have. The pool is created lazily so that next build does not open a connection, and the module logs when it does. The application_name is what lets pg_stat_activity attribute each backend to a pool:
// src/lib/db.js import postgres from "postgres"; // The usual lazy singleton. Correct in plain Node; wrong in a Next.js build. let sql = null; export function getSql() { if (!sql) { console.log(`[db] creating a pool (module-level) in pid ${process.pid}`); sql = postgres(process.env.DATABASE_URL, { max: 5, connection: { application_name: "demo-module-level" }, }); } return sql; } Use it from every kind of server entry point. Each one runs the same query, select pg_backend_pid(), pg_sleep(0.3), so that concurrent requests hold distinct connections the way real queries do, and returns the backend pid. A route handler looks like this:
// src/app/api/route-handler/route.js import { getSql } from "@/lib/db"; import { probe } from "@/lib/query"; export const dynamic = "force-dynamic"; export async function GET() { const r = await probe(getSql(), "route handler"); return Response.json(r, { status: r.error ? 503 : 200 }); } The same two lines go into a server component page, a server action called from a page, register() in instrumentation.js, and a Node-runtime proxy.js that answers /proxied itself. Build, start, and send one request to each. The server log shows the module's constructor running four times in one process:
[db] creating a pool (module-level) in pid 27457 [instrumentation] {"where":"instrumentation register()","backendPid":27492} [db] creating a pool (module-level) in pid 27457 [db] creating a pool (module-level) in pid 27457 [db] creating a pool (module-level) in pid 27457 And the database sees four backends for what the code calls one pool:
$ psql -c "select application_name, count(*) from pg_stat_activity where application_name like 'demo-%' group by 1" demo-module-level|4 Route handlers share one copy among themselves, and pages share one copy with server actions, so adding routes does not add pools. Adding an entry kind does. Without the proxy, the count is three.
Step 2: Push It Over the Limit
With max_connections=12 and the default superuser reserve of 3, an ordinary role gets 9 slots. The instrumentation and proxy copies each hold one idle connection already, and the route-handler and page copies can open 5 each, so the process can ask for 12. Send 8 concurrent requests to the route handler and 8 to the server component at the same time:
$ for i in $(seq 8); do curl -s -o /dev/null -w "%{http_code}\n" localhost:3123/api/route-handler & done $ for i in $(seq 8); do curl -s -o /dev/null -w "%{http_code}\n" localhost:3123/server-component & done In our run, 13 requests returned 200 and three returned 503 carrying the error from the introduction. Afterwards the module-level pools hold 9 backends between them, every slot the role is allowed, while a single pool with max: 5 could never hold more than 5:
{"where":"route handler","error":"53300 remaining connection slots are reserved for roles with the SUPERUSER attribute"} demo-module-level|9 This is the small-scale version of the outage. Our production cluster is the smallest managed plan, with 22 usable backend connections after the reserve, and the app ran pools of 5 and 3 plus one LISTEN connection, 9 per process, 18 while a rolling deploy briefly runs two processes. That budget was correct for one copy. Three copies of the module turned 8 pooled connections into 24, more than the whole cluster, before counting the second process. Every query failed with 53300 at the same moment, including session lookups, so the app was down rather than slow.
Step 3: Keep the Client on globalThis
Move the instance from module scope to the global object. Each copy still runs its own getSql, but all of them find the same client:
// src/lib/db-global.js import postgres from "postgres"; const g = globalThis; export function getSql() { if (!g.__sql) { console.log(`[db-global] creating a pool (globalThis) in pid ${process.pid}`); g.__sql = postgres(process.env.DATABASE_URL, { max: 5, connection: { application_name: "demo-globalthis" }, }); } return g.__sql; } The same burst against entry points that use this module gives 16 responses with status 200, one constructor call in the log, and exactly the pool's max on the database side:
[db-global] creating a pool (globalThis) in pid 28708 demo-globalthis|5 Use a project-specific key such as __myapp_sql, because globalThis is shared with every dependency in the process. And keep the constructor lazy: an eagerly created client, export const sql = postgres(url), is constructed the moment each copy of the module is evaluated, whether or not that copy ever runs a query.
Step 4: Check the Budget at Boot
The fix removes the multiplication, but the budget still drifts: a pool gets raised for a job queue, an instance count changes, the database plan changes. A check in register() that reads the server's limits and compares them with what the process will open makes the drift visible in the logs before it becomes an outage.
// src/lib/db-budget.js import { getSql } from "./db-global"; // Connections one process may open: every pool's `max`, plus any LISTEN clients. export const PER_PROCESS = 5; export async function checkConnectionBudget(instances = Number(process.env.APP_INSTANCE_COUNT ?? 1)) { const [s] = await getSql()` select current_setting('max_connections')::int as max_connections, current_setting('superuser_reserved_connections')::int as superuser_reserved, coalesce(nullif(current_setting('reserved_connections', true), ''), '0')::int as reserved`; const usable = s.max_connections - s.superuser_reserved - s.reserved; const needed = PER_PROCESS * (instances + 1); const verdict = { ...s, usable, perProcess: PER_PROCESS, instances, neededDuringDeploy: needed, fits: needed <= usable }; console[verdict.fits ? "log" : "error"]("[db-budget]", JSON.stringify(verdict)); return verdict; } Against the 12-connection test server it reports:
[db-budget] {"max_connections":12,"superuser_reserved":3,"reserved":0,"usable":9,"perProcess":5,"instances":1,"neededDuringDeploy":10,"fits":false} Two details in the query are deliberate. It plans for instances + 1, because a rolling deploy runs the old and the new process together for a moment. And it subtracts both reserves: superuser_reserved_connections (default 3) exists on every version, and PostgreSQL 16 added reserved_connections (default 0) without replacing it. Our first version read reserved_connections and fell back to the old setting only when it was absent, which on PostgreSQL 16 and later returns 0 and overstates the usable slots by 3. On a 25-slot cluster that is the difference between "fits" and "every query fails".
Troubleshooting & Gotchas
The count of chunk files is not the count of pools
Searching .next/server for your pool's application_name finds every chunk file that carries a copy of the module, and several of them share one module id, which the runtime instantiates once. Count constructor calls at runtime, or backends by application_name in pg_stat_activity.
webpack and next dev are not exempt
The same app built with next build --webpack created three pools instead of four: the instrumentation hook, the proxy, and one shared by route handlers, pages, and actions. The development server created the same four as the production build, and hot reloading re-evaluates modules on top of that. The fix is the same in every case.
A client component can add one more copy
If a client component reaches the database module through an import chain, for example a barrel file that re-exports both a date helper and the client, the module is also compiled into the client-component SSR layer. import "server-only" at the top of the database module catches that: on Next.js 16, next build fails with 'server-only' cannot be imported from a Client Component module and names the offending import.
Only add it if nothing outside Next.js loads the module. The server-only specifier resolves inside the Next.js bundler, not in plain Node, so a seed or maintenance script that runs the same module through tsx or node dies with ERR_MODULE_NOT_FOUND. We learned this from a migrate job that imports the database module in exactly that way: the migrations applied and the deploy then failed on the next step. Neither next build nor a test suite that stubs server-only warns about it, so if you have such scripts, leave the guard off the database module and rely on the build failing when a client import reaches a module that uses postgres.
The error text depends on the PostgreSQL version
All of these are SQLSTATE 53300. PostgreSQL 15 and earlier say remaining connection slots are reserved for non-replication superuser connections. PostgreSQL 16 and later say remaining connection slots are reserved for roles with the SUPERUSER attribute, or name the pg_use_reserved_connections role when only the new reserve is left. Match on the code, not the message.
A connection pooler changes the arithmetic, not the bug
PgBouncer in transaction mode makes idle client connections cheap, so duplicate pools become waste rather than an outage. The duplication is still there, and the pooler brings its own constraints: postgres.js needs prepare: false unless the pooler supports prepared statements, and a LISTEN connection has to bypass it. Fix the module first; add the pooler when the instance count needs it.
Conclusion
A Next.js server is several bundles sharing one process, and module scope is per bundle while globalThis is per process. Anything that must exist once per process, a database pool, a LISTEN client, a job scheduler, belongs on the global object, created lazily behind a check. Pair that with a boot-time comparison of what the process will open against what the server allows, including the reserve and one extra process for deploys, and the connection budget stops being something you re-derive by hand after an outage.
We build and run Next.js applications on managed PostgreSQL for clients; if your deployment is hitting limits like this one, get in touch.
Resources
- Next.js: instrumentation — the
register()hook used for the boot check - Next.js: proxy — the Node-runtime replacement for middleware
- Next.js: keeping server-only code out of the client — the
server-onlypackage - PostgreSQL: connection settings —
max_connections,superuser_reserved_connections,reserved_connections - postgres.js — pool options,
application_name,prepare - u11d: Postgres Row-Level Security in Next.js with Drizzle — the two-pool setup (admin and RLS-scoped) this app runs
FAQ
Why does my Next.js app open more database connections than my pool's max?
A Next.js production build compiles server code into separate bundles for route handlers, pages with server components and actions, the proxy, and the instrumentation hook. A database module imported by several of them is compiled into each, and each compiled copy has its own module scope, so a module-level singleton such as let pool = null becomes one pool per copy. Store the client on globalThis, which all copies in the process share, so only one pool is created.
How do I fix "remaining connection slots are reserved" (SQLSTATE 53300) in a Next.js app?
The error means PostgreSQL has no free connection slots for ordinary roles. In a Next.js app the usual cause is several copies of the database module each opening a pool. Create the client lazily and keep it on globalThis under a project-specific key, then size every pool's max so that all pools times the instance count plus one extra process for rolling deploys fits within max_connections minus the reserved connections.
Is the Next.js multiple-pool problem only in development with hot reloading?
No. Hot reloading in next dev re-evaluates modules and is the best-known reason for duplicate clients, but a production next build also compiles the module once per server entry kind. In a test on Next.js 16.4 with Turbopack, one next start process created four pools from one module: for the instrumentation hook, the proxy, route handlers, and server components. A webpack build created three.
How many database connections can a Next.js app open on a managed PostgreSQL plan?
As many as max_connections minus the reserved connections, which small managed plans often set in the low tens; a 25-connection plan with a reserve of 3 leaves 22 for the application. Every pool in every app process counts against that number, and a rolling deploy briefly runs one extra process. For example, pools of 5 and 3 plus one LISTEN connection per process is 9 slots, 18 during a deploy, which fits only if the module creates its pools once per process.
How do I check at startup that my database pools fit the connection limit?
In register() in instrumentation.ts, query current_setting('max_connections'), current_setting('superuser_reserved_connections') and, on PostgreSQL 16 and later, current_setting('reserved_connections'), subtract both reserves, and compare the result with the sum of every pool's max multiplied by the instance count plus one. Log an error when it does not fit. Reading reserved_connections instead of superuser_reserved_connections returns 0 on PostgreSQL 16+ and overstates the budget by the superuser reserve.