# Supabase Max Client Connections Fix: Supavisor, Prisma & Edge

> Canonical URL: https://stackquota.com/guides/supabase-max-client-connections-pgbouncer-serverless-fix/
> Checked: 2026-12-04 · Published: 2026-12-04

Fix FATAL: MaxClientsInSessionMode and 42P05 prepared statement errors on Vercel and Workers using Supavisor port 6543 with Prisma and Drizzle.

## Why does serverless traffic trigger FATAL: MaxClientsInSessionMode on Supabase?

**Quick answer:** Serverless platforms (Vercel Functions, AWS Lambda, Cloudflare Workers) spin up isolated execution environments per concurrent request and hold idle TCP sockets open between invocations; connecting them to Supavisor **Session Mode (`port 5432`)** pins `1:1` backend Postgres connections until the pool ceiling (`15–60` slots on Micro) snaps shut with `FATAL: MaxClientsInSessionMode: max clients reached`.

Traditional Node.js or Go servers run `2–4` long-lived containers with an in-memory connection pool of `10` sockets each. Serverless breaks that contract completely. When a Next.js App Router deployment on Vercel receives a burst of `80` concurrent SSR page loads, AWS Lambda spins up `80` separate microVMs. If each microVM instantiates Prisma with its default connection pool (`num_cpus * 2 + 1`, typically `5` connections) against `aws-0-us-east-1.pooler.supabase.com:5432`, your app suddenly demands `400` persistent session slots from a database configured for `60` total Postgres processes.

Even worse, Supabase reserves internal backend connections for PostgREST (`authenticator`), Realtime, GoTrue Auth, Storage, and `pg_cron`. When you copy the IPv4-compatible **Session Mode** string (`port 5432` on `*.pooler.supabase.com`) from the Supabase Dashboard instead of the **Transaction Mode** string (`port 6543`), Supavisor restricts Session Mode clients to your configured `pool_size` so serverless bursts cannot starve PostgREST or Auth. Once warm Lambda containers hold all `pool_size` slots idle waiting for the next HTTP request, every new visitor hits a `500 Internal Server Error` with:

```text
FATAL: MaxClientsInSessionMode: max clients reached - in Session mode max clients are limited to pool_size
```

Unlike [runaway Firestore listener bills](/guides/firestore-unexpected-read-spike-snapshot-listener-loop/) where traffic succeeds while charging thousands of dollars, Postgres connection exhaustion causes immediate production downtime, often while database CPU sits below `8%`.

## Supavisor port 5432 vs port 6543: which mode should your runtime use?

**Quick answer:** Use **Supavisor Transaction Mode (`port 6543`)** for all stateless serverless functions, edge workers, and autoscaling API routes, and restrict **Session Mode / Direct (`port 5432`)** strictly to CLI schema migrations (`prisma migrate`, `drizzle-kit`), `pg_dump`, and stateful long-lived workers that require advisory locks or `LISTEN/NOTIFY`.

Supabase exposes three distinct Postgres connection paths. Picking the wrong hostname or port is the root cause of both connection exhaustion and prepared-statement crashes:

| Connection Endpoint | Hostname & Port Pattern | IPv4 / IPv6 | Prepared Statements & Session Locks | Ideal Production Workload |
| :--- | :--- | :--- | :--- | :--- |
| **Supavisor Transaction Mode** | `aws-0-[region].pooler.supabase.com:6543` | IPv4 + IPv6 | Disabled unless client opts out (`?pgbouncer=true` / `prepare: false`) | Vercel Functions, AWS Lambda, Cloudflare Workers, Next.js SSR |
| **Supavisor Session Mode** | `aws-0-[region].pooler.supabase.com:5432` | IPv4 + IPv6 | Supported (holds backend slot until client `DISCONNECT`) | IPv4-only CI runners, `prisma migrate`, stateful background daemons |
| **Direct Database Host** | `db.[project-ref].supabase.co:5432` | IPv6 default (IPv4 `$4/mo` add-on) | Full native Postgres session features | IPv6 VPS clusters, `pg_dump` / `pg_restore`, logical replication |

Notice two critical details when switching to Supavisor (`*.pooler.supabase.com`):

1. **Tenant-qualified username:** Direct connections authenticate as `postgres`, whereas Supavisor requires your project reference appended to the username: `postgres.[project-ref]` (for example, `postgres.qwerasdfzxcvtyui`). Using bare `postgres` against the pooler returns `FATAL: Tenant or user not found`.
2. **Transaction lifecycle:** On `port 6543`, Supavisor lends a physical Postgres backend connection to your serverless function *only for the millisecond duration of a single SQL statement or `BEGIN ... COMMIT` block*. The moment the transaction finishes, that backend slot returns to the shared pool to serve another Lambda, even while your Node.js container stays warm for `5 minutes`.

## How do you fix Prisma 42P05 prepared statement errors on port 6543?

**Quick answer:** Split your Prisma configuration into two environment variables: point `DATABASE_URL` to Supavisor **port `6543`** with `?pgbouncer=true&connection_limit=1` for runtime queries, and point `DIRECT_URL` to **port `5432`** so `prisma migrate deploy` can acquire schema advisory locks cleanly.

If you simply change `:5432` to `:6543` in a Prisma project without updating query string flags, production immediately throws intermittent Postgres protocol errors under load:

```text
ConnectorError: Error querying the database: db error: ERROR: prepared statement "s0" already exists (SQLSTATE 42P05)
ConnectorError: Error querying the database: db error: ERROR: prepared statement "s1" does not exist (SQLSTATE 26000)
```

Prisma's Rust query engine prepares named statements (`s0`, `s1`, `s2`) on each connection to skip repeated SQL parsing. Under Supavisor Transaction Mode, Lambda A prepares `s0` on backend connection `#4`; milliseconds later, Lambda B gets assigned backend connection `#4` and tries to prepare its own `s0`, triggering `42P05` (`already exists`), or tries to execute `s1` on connection `#7` where it was never registered (`26000`).

Additionally, leaving Prisma's default `connection_limit` (`5+` sockets per Lambda) wastes Supavisor client slots because a single-threaded serverless request rarely executes more than `1` transaction concurrently unless you fire wide `Promise.all()` batches.

Apply the battle-tested dual-URL setup in `prisma/schema.prisma`, `.env`, and a global singleton client:

```prisma
// prisma/schema.prisma
datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL") // Runtime: Supavisor Transaction Mode (port 6543)
  directUrl = env("DIRECT_URL")   // CLI Migrations: Session Mode or Direct (port 5432)
}

generator client {
  provider = "prisma-client-js"
}
```

```ini
# .env (Production Vercel / Lambda environment variables)
# 1. Runtime pooled URL: port 6543 + pgbouncer=true + connection_limit=1 + pool_timeout=15
DATABASE_URL="postgresql://postgres.qwerasdfzxcv:STRONG_PASS@aws-0-us-east-1.pooler.supabase.com:6543/postgres?pgbouncer=true&connection_limit=1&pool_timeout=15"

# 2. Migration URL: port 5432 via Supavisor Session Mode (works on IPv4 GitHub Actions / Vercel build)
DIRECT_URL="postgresql://postgres.qwerasdfzxcv:STRONG_PASS@aws-0-us-east-1.pooler.supabase.com:5432/postgres"
```

```typescript
// src/lib/prisma.ts — Prevent Next.js hot-reload and warm-container client leaks
import { PrismaClient } from "@prisma/client";

const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };

export const prisma =
  globalForPrisma.prisma ??
  new PrismaClient({
    log: process.env.NODE_ENV === "development" ? ["warn", "error"] : ["error"],
  });

if (process.env.NODE_ENV !== "production") {
  globalForPrisma.prisma = prisma;
}
```

Why `connection_limit=1`? With `150` concurrent Vercel Function instances, `connection_limit=1` caps your peak Supavisor client footprint to `150` connections (safely inside the `200`-client ceiling of Supabase's baseline Micro compute instance) while Supavisor multiplexes those `150` lambdas onto just `15` physical Postgres connections. (If a specific API route runs heavy `Promise.all([prisma.a.findMany(), prisma.b.findMany()])` fan-outs, set `connection_limit=2` only after upgrading compute to Small.)

## How do you configure Drizzle ORM and Cloudflare Workers without leaking sockets?

**Quick answer:** Pass `{ prepare: false, max: 1 }` to `postgres-js` when instantiating Drizzle against Supavisor port `6543` on Node serverless runtimes, and instantiate (then close or bind via Hyperdrive) connections *inside* each `fetch()` handler on Cloudflare Workers so isolates never share dead TCP sockets across requests.

Drizzle ORM paired with `postgres` (`postgres-js`) enables automatic statement preparation (`prepare: true`) out of the box, triggering the exact same `42P05` collision on Supavisor port `6543` unless explicitly disabled.

For **Vercel, AWS Lambda, and Node.js serverless**, disable `prepare`, cap `max` to `1` per isolate, and set `idle_timeout: 20` so warm idle containers release Supavisor client slots cleanly:

```typescript
// src/db/index.ts — Node Serverless (Vercel / AWS Lambda)
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";
import * as schema from "./schema";

const globalForDb = globalThis as unknown as { sqlClient?: ReturnType<typeof postgres> };

const sqlClient =
  globalForDb.sqlClient ??
  postgres(process.env.DATABASE_URL!, {
    prepare: false,   // Mandatory for Supavisor Transaction Mode (port 6543)
    max: 1,           // 1 socket per serverless microVM
    idle_timeout: 20, // Release idle Supavisor slot after 20s
    connect_timeout: 10,
  });

if (process.env.NODE_ENV !== "production") {
  globalForDb.sqlClient = sqlClient;
}

export const db = drizzle(sqlClient, { schema });
```

Point `drizzle.config.ts` at `process.env.DIRECT_URL!` (`port 5432`) so `npx drizzle-kit migrate` runs DDL statements outside Transaction Mode.

For **Cloudflare Workers**, V8 isolates enforce an additional rule: **you cannot reuse an open TCP socket created in Request A inside Request B**. Declaring a global `postgres()` client at module top-level causes `"Cannot perform I/O on behalf of a different request"` errors or hung sockets. Either attach **Cloudflare Hyperdrive** (which pools connections globally at Cloudflare's edge) or scope the client to each request and flush it inside `ctx.waitUntil()`:

```typescript
// worker/index.ts — Cloudflare Workers per-request lifecycle without Hyperdrive
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

export default {
  async fetch(req: Request, env: { DATABASE_URL: string }, ctx: ExecutionContext) {
    const sql = postgres(env.DATABASE_URL, { prepare: false, max: 1 });
    const db = drizzle(sql);

    try {
      const rows = await db.execute("SELECT now() AS server_time");
      return Response.json(rows);
    } finally {
      // Close socket asynchronously after returning HTTP response
      ctx.waitUntil(sql.end({ timeout: 2 }));
    }
  },
};
```

If your edge workload performs pure key-value or read-heavy relational lookups on Cloudflare Workers, also evaluate edge-native SQLite tradeoffs in our [Cloudflare D1 rows-read optimization guide](/guides/cloudflare-d1-rows-read-spike-unindexed-query-fix/).

## When should you upgrade Supabase Compute vs tune pool size?

**Quick answer:** Stay on Micro (`$0` net extra on Supabase Pro) until your concurrent Supavisor Transaction Mode clients regularly exceed `160` (`80%` of the `200`-client cap) or Postgres RAM cache hit ratios drop below `98%`; beyond that, upgrading to **Small (`+$5/mo` net)** doubles Supavisor capacity to `400` clients and bumps direct connections from `60` to `90`.

Every Supabase Pro subscription (`$25/month` base, including `100,000` MAU, `8 GB` database disk, and `250 GB` egress) includes a **`$10/month` compute credit**. That credit covers one **Micro** compute instance completely, meaning upgrading to **Small** (`$15/month` list price) adds just **`$5/month`** to your invoice.

Compare December 2026 Supabase compute connection ceilings alongside Neon Launch (`$19/month` base with `300` compute hours and built-in PgBouncer up to `10,000` pooled connections):

| Instance Tier | RAM & CPU | Gross Compute Price | Net Cost on Supabase Pro (`$25/mo` Base) | Direct PG `max_connections` | Supavisor Max Client Connections |
| :--- | :--- | :--- | :--- | :--- | :--- |
| **Supabase Free (Nano)** | Up to `0.5 GB` (Shared) | `$0/mo` | `$0/mo` total | `60` | `200` |
| **Supabase Micro** | `1 GB` RAM (Shared CPU) | `$10/mo` | **`$25/mo` total** (`+$0` net) | `60` | `200` |
| **Supabase Small** | `2 GB` RAM (Shared CPU) | `$15/mo` | **`$30/mo` total** (`+$5` net) | `90` | `400` |
| **Supabase Medium** | `4 GB` RAM (Shared CPU) | `$60/mo` | **`$75/mo` total** (`+$50` net) | `120` | `600` |
| **Supabase Large** | `8 GB` RAM (Dedicated CPU) | `$110/mo` | **`$125/mo` total** (`+$100` net) | `160` | `800` |
| **Neon Launch (Pooled)** | Autoscaling `0.25–4 CU` | Included (`300` hrs) | **`$19/mo` base** (`$0.16/hr` extra) | `100–900+` (by CU) | Up to `10,000` (PgBouncer / HTTP) |

Model your full monthly stack, combining compute tiers, extra MAUs (`$0.00325/MAU` past `100k`), and [uncached egress overages (`$0.09/GB` past `250 GB`)](/guides/supabase-egress-overage-cached-storage-cdn-fix/), in our [Supabase vs Firebase vs Neon cost calculator](/calculators/supabase-vs-firebase-cost/).

## How do you audit active connections with pg_stat_activity in production?

**Quick answer:** Run a grouped `pg_stat_activity` query in the Supabase SQL Editor to break down live slots by `usename`, `application_name`, and `state`; if `idle in transaction` rows pile up, enforce a `15-second` `idle_in_transaction_session_timeout` at the role level so hung transactions cannot deadlock your pool.

Before spending money on a larger compute tier, verify *who* holds your connections right now in the Supabase SQL Editor:

```sql
SELECT
  usename AS db_role,
  COALESCE(NULLIF(application_name, ''), '<unnamed>') AS app,
  state,
  COUNT(*) AS open_connections,
  MAX(EXTRACT(EPOCH FROM (now() - state_change)))::int AS oldest_state_seconds
FROM pg_stat_activity
WHERE pid <> pg_backend_pid()
GROUP BY 1, 2, 3
ORDER BY open_connections DESC;
```

Interpret the output immediately:

- **Dozens of `postgres` rows in `idle` with `oldest_state_seconds > 120`:** One of your services or developer laptops is still connected via port `5432` instead of port `6543`. Rotate or audit `DATABASE_URL` across Vercel Preview and Production environments.
- **Rows stuck in `idle in transaction`:** Application code opened an interactive transaction (`prisma.$transaction(async (tx) => { ... })`) and awaited a slow third-party Stripe or LLM webhook *inside* the transaction block, holding a physical backend connection hostage on port `6543` for `10–30 seconds`. Move all external `fetch()` calls outside database transactions and set a hard safety timeout:

```sql
-- Automatically abort hung transactions holding Supavisor backend slots past 15s
ALTER ROLE postgres SET idle_in_transaction_session_timeout = '15s';
ALTER ROLE postgres SET statement_timeout = '10s';
```

Combining `port 6543`, `connection_limit=1`, prepared-statement opt-out, and `15s` transaction timeouts lets a `$25/month` Supabase Pro project absorb thousands of requests per minute without dropping a single connection.
