Skip to content

Why Supabase & Neon Freeze at 100 Concurrent Users

Fix Supabase and Neon connection exhaustion, Linux process-per-connection RAM spikes, and 504 gateway timeouts using transaction pooling on port 6543.

Why Supabase & Neon Freeze at 100 Concurrent Users

When scaling serverless applications on PostgreSQL, configuring Supabase connection pooling and max connections correctly is the difference between seamless traffic handling and total system failure. Most developers experience connection starvation not during slow synthetic load tests, but right after a sudden traffic surge. In staging and local development, query response times hover under five milliseconds, and the database CPU appears completely idle. Once several hundred concurrent users hit the signup flow, serverless function runtimes jump from 30ms to several thousand milliseconds, eventually dropping client requests with 504 Gateway Timeouts.

The underlying failure is rarely a slow query or an underpowered database instance. Instead, it is the structural mismatch between the process-per-connection architecture of PostgreSQL and the ephemeral scaling mechanics of modern serverless infrastructure. When unpooled serverless functions spawn individual TCP connections, PostgreSQL rapidly hits its connection ceiling, triggering FATAL: remaining connection slots are reserved for non-replication superuser connections (SQLSTATE 53300) and grinding the data layer to a halt.


Quick Production Triage Checklist

If your application is actively timing out or rejecting incoming client connections, run through these four immediate remediation steps:

  1. Switch Serverless Endpoints from Port 5432 to Port 6543: Direct connections to db.[project-ref].supabase.co:5432 exhaust connection limits within dozens of concurrent lambdas. Route application traffic through the Supavisor transaction pooler on port 6543 (aws-0-[region].pooler.supabase.com:6543) or the -pooler endpoint on Neon.
  2. Disable Driver-Side Prepared Statement Caching: Transaction poolers swap underlying PostgreSQL processes between queries. Configure your ORM or driver to disable statement preparation (such as adding ?pgbouncer=true in Prisma, setting { prepare: false } in postgres.js or Drizzle, or setting statement_cache_size=0 in asyncpg).
  3. Route Database Migrations Exclusively to Direct Ports: Migration tools (Prisma Migrate, Flyway, Rails ActiveRecord) require session-level advisory locks that fail in transaction pooling mode. Always supply a direct connection URL (directUrl) for migration commands.
  4. Inspect Active Connection Counts in PostgreSQL: Run SELECT count(*), state FROM pg_stat_activity GROUP BY state; from a direct maintenance session to identify whether connections are actively running queries or idling inside open client sockets.

FATAL: remaining connection slots are reserved for non-replication superuser connections (SQLSTATE 53300)

PostgreSQL returns SQLSTATE 53300 when the total number of active client connections reaches the configured max_connections threshold minus superuser_reserved_connections (typically set to 3). At this point, PostgreSQL rejects all non-superuser incoming TCP handshakes to preserve dedicated connection slots for emergency administrative access.

Illustrative PostgreSQL backend connection failure log:
FATAL: remaining connection slots are reserved for non-replication superuser connections (SQLSTATE 53300)
FATAL: sorry, too many clients already (SQLSTATE 53300)

In managed environments like Supabase or Neon, small compute tiers (such as Micro and Small instances) set max_connections between 60 and 100 connections. Managed platform processes (storage managers, real-time replication listeners, auth microservices, and metrics collectors) consume 20 to 30 of these available slots out of the box.

As a result, your web application may only have 40 to 60 direct connection slots available before PostgreSQL begins dropping incoming requests. When a burst of 100 concurrent users triggers serverless functions, the platform spins up 100 isolated function instances. Each instance initiates an independent TCP handshake, instantly consuming the remaining connection slots and locking out subsequent requests.


The Architectural Conflict: Process-per-Connection vs Serverless Autoscaling

PostgreSQL relies on a process-per-connection concurrency model developed for long-running Unix servers, whereas serverless platforms deploy stateless, ephemeral execution containers that multiply on demand.

                                  UNPOOLED DIRECT ARCHITECTURE (PORT 5432)
                                  
  ┌─────────────────────────┐     TCP Connect     ┌────────────────────────────────────────────────────────┐
  │ 150 Serverless Lambdas  │ ──────────────────> │ PostgreSQL Database Engine                             │
  │ (Each holds 1 TCP conn) │                     │                                                        │
  └─────────────────────────┘                     │  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐  │
                                                  │  │ Backend PID1 │  │ Backend PID2 │  │ Backend PID3 │  │
                                                  │  │  (8MB RAM)   │  │  (8MB RAM)   │  │  (8MB RAM)   │  │
                                                  │  └──────────────┘  └──────────────┘  └──────────────┘  │
                                                  │         ... (Exhausts max_connections at 60)           │
                                                  └────────────────────────────────────────────────────────┘
                                                                           │
                                                                           ▼
                                                                  [ 53300 Connection Refusal ]
                                                                  [ Linux Context Thrashing  ]

                                  TRANSACTION POOLED ARCHITECTURE (PORT 6543)
                                  
  ┌─────────────────────────┐     Lightweight     ┌─────────────────────┐    15 Persistent   ┌───────────────────────┐
  │ 2,500 Serverless Lambdas│ ──────────────────> │ Supavisor/PgBouncer │ ─────────────────> │ PostgreSQL Core       │
  │ (Ephemeral HTTP Conns)  │     Client Sockets  │ (Transaction Mode)  │    DB Connections  │ (15 Worker Processes) │
  └─────────────────────────┘                     └─────────────────────┘                    └───────────────────────┘
                                                             │
                                                             ▼
                                                  [ Sub-5ms Client Reuse ]
                                                  [ Stable Memory & CPU  ]

The Cost of a PostgreSQL Backend Process

Unlike modern thread-based databases, PostgreSQL does not handle new connections by spawning lightweight OS threads. When an application client connects to PostgreSQL:

  1. The central postmaster process calls fork() to spawn an independent Linux process.
  2. The operating system allocates private memory for the process, including work_mem, local execution buffers, and per-process metadata (averaging 5MB to 10MB per backend).
  3. The process establishes separate SSL/TLS handshakes and validates client role credentials.
  4. When hundreds of processes run concurrently, the Linux kernel spends a substantial percentage of its CPU cycles executing context switches, descheduling processes, and coordinating shared memory latches rather than executing SQL queries.

In contrast, traditional backend runtimes (such as persistent Go services or Node.js instances) maintain a single, long-lived internal connection pool. That pool holds 10 to 20 persistent sockets and coordinates thousands of HTTP requests across those connections. When architectures migrate to serverless runtimes (Next.js on Vercel, AWS Lambda, or Cloudflare Workers), every incoming HTTP request potentially spawns a new execution container that creates an uncoordinated, direct TCP socket.


Direct Connection vs Connection Pooling: Benchmark Comparison

Understanding the performance characteristics of direct connections versus connection pooler modes reveals why transaction pooling is necessary for serverless workloads:

Operational MetricDirect Connection (Port 5432)Session Pooling ModeTransaction Pooling Mode (Port 6543)
Max Concurrent Clients60 - 100 (Hard Instance Ceiling)60 - 100 (Tied to Backend Sockets)10,000+ Multiplexed Sockets
Memory Footprint per Client5MB - 10MB (OS Process Fork)5MB - 10MB (OS Process Fork)< 50KB (Lightweight Pooler Socket)
Connection Handshake Latency60ms - 140ms (TCP + TLS + Auth)60ms - 140ms on Cold BootSub-5ms (Pre-warmed Backend Reuse)
Prepared Statement ProtocolSupported (Per-Process Cache)Supported (1:1 Bound Connection)Requires Configuration or Driver Workarounds
Session Advisory LocksSupported (pg_advisory_lock)SupportedNot Supported (pg_advisory_xact_lock only)
Temporary TablesSupported (PRESERVE ROWS)SupportedOnly ON COMMIT DROP Supported
PostgreSQL CPU at 250 Users100% (Kernel Context Thrashing)100% (Kernel Context Thrashing)10% - 18% (Direct Query Execution)
Throughput Under SurgeFails at ~80 req/secFails at ~80 req/sec3,500+ req/sec Sustained

In session pooling mode, the pooler assigns an entire PostgreSQL backend to the client for the duration of the client socket. While this maintains complete compatibility with session variables and prepared statements, it offers zero scalability benefits for serverless environments. Only transaction pooling mode, which releases the backend connection back into the pool the instant a SQL transaction finishes, allows serverless applications to scale safely.


ERROR: prepared statement does not exist (SQLSTATE 26000)

When developers first switch their connection strings from port 5432 to port 6543, their application often crashes immediately with a new error:

Illustrative PostgreSQL backend statement cache failure log:
ERROR: prepared statement "s0" does not exist (SQLSTATE 26000)

This error is a direct consequence of transaction pooling mechanics. In the PostgreSQL extended query protocol, preparing a query involves two distinct steps:

  1. The client sends a Parse message containing the SQL string and names it (for example, s0). The PostgreSQL backend process compiles the query, computes an execution plan, and stores it in its private process memory.
  2. The client later sends a Bind and Execute message referencing s0.

In transaction pooling mode, client query 1 runs on PostgreSQL backend process PID 101, which creates s0. Client query 2 runs half a second later; because backend PID 101 is now busy serving another request, the pooler routes query 2 to PostgreSQL backend process PID 102. Backend PID 102 has never seen statement s0, and immediately throws SQLSTATE 26000.

Counterpart: ERROR: prepared statement already exists (SQLSTATE 42P05)

The inverse failure mode occurs when multiple clients share a backend process without internal statement isolation:

Illustrative PostgreSQL backend statement naming collision log:
ERROR: prepared statement "s0" already exists (SQLSTATE 42P05)

If Client A creates a prepared statement named s0 on backend PID 101, and Client B is subsequently connected to PID 101 and also attempts to prepare a statement named s0, PostgreSQL rejects it with SQLSTATE 42P05.

Modern connection poolers address this in two ways:

  • PgBouncer 1.21+ transparently intercepts protocol-level prepared statements, renames them with internal unique prefixes (PGBOUNCER_<id>), and handles execution routing across backends.
  • Client-Side Driver Configuration: Configuring drivers to use unnamed prepared statements or simple query protocols bypasses named statement caches altogether.

Driver and ORM Configuration Guide for Transaction Pooling

To eliminate SQLSTATE 26000 and SQLSTATE 42P05 errors, every database client running against transaction poolers must be configured properly:

1. Prisma ORM (v6 and v7)

Prisma maintains an internal query engine that relies on prepared statements. In Prisma v6, add ?pgbouncer=true to your pooled database URL to force Prisma to execute queries without protocol-level named statements, and supply a direct connection for migrations:

// schema.prisma (Prisma v6)
datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")   // Transaction pooled: aws-0-[region].pooler.supabase.com:6543
  directUrl = env("DIRECT_URL")     // Direct session: db.[project-ref].supabase.co:5432
}

In Prisma v7, migration configuration moves to prisma.config.ts, while the application client consumes the pooled adapter:

// prisma.config.ts (Prisma v7)
import "dotenv/config";
import { defineConfig } from "@prisma/config";

export default defineConfig({
  datasource: {
    url: process.env.DIRECT_URL, // Used exclusively by Prisma CLI for migrations
  },
});
// src/lib/db.ts - Runtime Client using Driver Adapter
import { Pool } from "pg";
import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "@prisma/client";

// Pool points to the pooled URL on port 6543
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const adapter = new PrismaPg(pool);

export const prisma = new PrismaClient({ adapter });

2. Drizzle ORM and postgres.js

When using postgres.js with Drizzle, disable prepared statements explicitly via the prepare configuration option:

// src/lib/drizzle.ts
import { drizzle } from "drizzle-orm/postgres-js";
import postgres from "postgres";

const connectionString = process.env.DATABASE_URL!; // Port 6543

// Setting prepare: false forces unnamed execution, preventing 26000 errors
const client = postgres(connectionString, { 
  prepare: false,
  max: 10,
  idle_timeout: 20,
});

export const db = drizzle(client);

3. Node.js pg (node-postgres)

When running raw parameterized queries with pg, do not assign a name property to your query configuration. Omission of the name property instructs pg to send an unnamed prepared statement, which transaction poolers handle seamlessly without backend collisions:

// ❌ WRONG: Named prepared statements cause SQLSTATE 26000 in transaction mode
await client.query({
  name: 'fetch-user-by-id',
  text: 'SELECT * FROM users WHERE id = $1',
  values: [userId],
});

// ✅ CORRECT: Unnamed statements execute safely across multiplexed backends
await client.query({
  text: 'SELECT * FROM users WHERE id = $1',
  values: [userId],
});

4. Python asyncpg

By default, asyncpg caches up to 100 prepared statements per connection. When connecting to transaction poolers, set statement_cache_size=0:

import asyncpg

# Configure pool with disabled driver-side prepared statement cache
pool = await asyncpg.create_pool(
    dsn=os.environ["DATABASE_URL"], # Port 6543
    statement_cache_size=0,
    min_size=2,
    max_size=10,
)

5. Go pgx/v5

In Go, configure pgxpool to use simple protocol execution or exec mode rather than statement caching:

config, err := pgxpool.ParseConfig(os.Getenv("DATABASE_URL"))
if err != nil {
    log.Fatal(err)
}

// Disable automatic prepared statement caching for transaction poolers
config.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeExec

Managed Provider Differences: Supabase vs Neon vs AWS RDS Proxy

Not all managed connection poolers behave identically. Using PgBouncer-specific parameters on an incompatible proxy causes silent configuration failures:

Supabase (Supavisor)

  • Direct Port: db.[project-ref].supabase.co:5432 (allocates full PostgreSQL process per connection).
  • Pooler Port: aws-0-[region].pooler.supabase.com:6543 (dedicated pooling infrastructure).
  • Architecture: Supabase previously deployed PgBouncer, but has migrated infrastructure to Supavisor, an open-source connection pooler built in Elixir.
  • Key Caveats: Supavisor supports protocol-level prepared statements in transaction mode, but ORMs like Prisma still require ?pgbouncer=true to adjust internal query generation. Supavisor does not read pgbouncer.ini directives.

Neon (PgBouncer)

  • Direct Connection: ep-[endpoint-id].region.aws.neon.tech:5432.
  • Pooled Connection: ep-[endpoint-id]-pooler.region.aws.neon.tech:5432 (note: port remains 5432, but routes through the -pooler virtual host).
  • Architecture: Neon runs managed PgBouncer instances in front of serverless compute nodes.
  • Key Caveats: Protocol-level prepared statements are supported in transaction mode on modern versions, but text PREPARE and DEALLOCATE statements are rejected.

AWS RDS Proxy

  • Architecture: AWS RDS Proxy operates as a fully managed reverse proxy rather than a classic transaction pooler.
  • Pinning Behavior: RDS Proxy does not return SQLSTATE 26000. Instead, if your application executes named prepared statements, creates temporary tables, or calls SET search_path, RDS Proxy pins the client socket to the physical database connection, disabling multiplexing until the client disconnects. If multiple lambdas trigger pinning, the proxy exhausts physical connections just as quickly as a direct port.

Step-by-Step Connection Pool Sizing Formula and Configuration

When self-hosting PgBouncer or configuring managed pooler limits, sizing pools requires balancing CPU concurrency against disk I/O latency.

                           PGBOUNCER SIZING & QUEUE ARCHITECTURE
                           
  Client Connections
  ┌────────────────────────────────────────────────────────────────────────┐
  │ 800 Incoming Client Sockets (default_pool_size = 9)                    │
  └────────────────────────────────────────────────────────────────────────┘
                                     │
             ┌───────────────────────┴───────────────────────┐
             │                                               │
             ▼                                               ▼
  [ Under Normal Load ]                           [ Under Traffic Surge ]
  9 Active Backend Connections                    3 Reserve Connections Activated
  (Instant multiplexing)                          (after reserve_pool_timeout = 5.0s)
                                                             │
                                                             ▼
                                                  Max DB Limit Reached (12)
                                                  Queue excess clients up to
                                                  query_wait_timeout = 15.0s

1. The Core Sizing Formula

A common operational error is setting database pool sizes to 100 or 200 connections. PostgreSQL performs optimally when the number of actively running queries matches physical CPU capacity:

Active Pool Size ≈ (Physical CPU Cores × 2) + Effective Spindle Count

For example, on a database VM with 4 vCPUs (2 physical CPU cores) and SSD storage (effective spindle count = 1), the baseline active pool size is:

Baseline Pool Size = (2 × 2) + 1 = 5 to 9 connections

Adding more concurrent worker processes beyond this threshold forces the CPU into cache misses and context-switch overhead, decreasing overall transaction throughput.

2. PgBouncer Production Configuration Template

Here is a verified pgbouncer.ini configuration for production workloads operating in transaction mode:

; pgbouncer.ini - Production Hardened Transaction Pooling
[databases]
app_db = host=127.0.0.1 port=5432 dbname=production_app

[pgbouncer]
listen_addr = 0.0.0.0
listen_port = 6543
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt

; Pool Configuration
pool_mode = transaction
max_client_conn = 10000

; Normal operational ceiling: 9 connections, bursting to 12
default_pool_size = 9
min_pool_size = 3
reserve_pool_size = 3
reserve_pool_timeout = 5.0
max_db_connections = 12

; Timeouts and Queue Ceilings
server_idle_timeout = 600.0
server_connect_timeout = 15.0
server_login_retry = 15.0
query_timeout = 30.0
query_wait_timeout = 15.0
client_idle_timeout = 0

; Tracked Parameter Synchronization (PG 14+)
track_extra_parameters = TimeZone, DateStyle, standard_conforming_strings, application_name

Important: The reserve_pool_size setting only activates after client requests have waited in the queue for longer than reserve_pool_timeout (5.0 seconds). If all 12 backend connections remain busy and client wait times exceed query_wait_timeout (15.0 seconds), PgBouncer aborts the waiting client socket to prevent queue backlog cascading.


Feature Matrix in Transaction Mode: Unsupported Primitives

Because transaction pooling disassociates client sockets from underlying PostgreSQL processes between transactions, several stateful SQL primitives behave differently or fail entirely:

Unsupported SQL Primitives in Transaction Mode:
❌ LISTEN / NOTIFY (Persistent PubSub requires dedicated session sockets)
❌ Session Advisory Locks (pg_advisory_lock does not release across pool backends)
❌ Temporary Tables with PRESERVE ROWS (State vanishes when backend reallocates)
❌ Session-Level SET Variables (e.g. SET TIME ZONE affects subsequent tenants)
  1. LISTEN and NOTIFY: PostgreSQL Realtime listeners require a continuous, stateful socket to receive events. LISTEN commands are unsupported in transaction pooling mode. Always connect real-time event listeners through a dedicated direct connection.
  2. Advisory Locks: Calls to pg_advisory_lock() bind the lock to the physical PostgreSQL backend process. If a client executes a query, gets disconnected by the pooler, and later attempts to release the lock on a different backend, the lock remains orphaned on the original process, deadlocking subsequent transactions. Use transaction-level advisory locks (pg_advisory_xact_lock()), which release automatically when the enclosing transaction commits or rolls back.
  3. Temporary Tables: Standard temporary tables (CREATE TEMP TABLE my_temp ...) persist until the backend process terminates. In transaction mode, your next query may land on a different backend where my_temp does not exist. If you must use temporary tables, declare them with ON COMMIT DROP:
    CREATE TEMP TABLE staging_records ON COMMIT DROP AS 
    SELECT id, payload FROM incoming_events WHERE processed = false;
  4. Relational Foreign Key Indexing: In high-concurrency environments, unindexed foreign keys cause PostgreSQL to acquire share locks on referenced tables during updates. Read our complete guide to Zero-Downtime PostgreSQL Migrations and Lock Elimination to avoid locking production tables during high-traffic intervals. Furthermore, multi-tenant row-level security policies can drastically amplify query latency if queries lack optimized InitPlan evaluation; see our audit of PostgreSQL Row-Level Security (RLS) Pitfalls.

Verifying Pooler Status via Administrative Consoles

When troubleshooting pool contention, do not guess connection allocation. Connect directly to the pooler’s administrative console:

# Connect to the administrative console (requires user in admin_users and auth_file)
psql -p 6543 -U pgbouncer_admin -d pgbouncer

Inspect active backend servers and client queues:

-- Illustrative PgBouncer administrative console session (columns trimmed for readability)
SHOW POOLS;
/*
 database |   user   | cl_active | cl_waiting | sv_active | sv_idle | sv_used | maxwait
----------+----------+-----------+------------+-----------+---------+---------+---------
 app_db   | app_user |        45 |          0 |         8 |       1 |       0 |       0
*/

SHOW STATS;
/*
 database | total_xact_count | total_query_count | total_client_parse_count | total_bind_count
----------+------------------+-------------------+--------------------------+------------------
 app_db   |          1840291 |           4120932 |                   240182 |           240182
*/

If cl_waiting is greater than zero and maxwait is climbing, your application’s concurrency demands have exceeded your active pool capacity, or individual slow queries are holding backend connections open for extended durations. You can test your frontend and API endpoints for search engine readiness and payload efficiency using our Free GEO Checker & AI Readiness Scanner or review developer utilities in Diagnostic Tools.


Summary Runbook

Failure SymptomImmediate Root CauseResolution
SQLSTATE 53300 (too many clients)Ephemeral serverless containers exhausting direct PostgreSQL max_connections.Switch client endpoints to pooler port 6543 in transaction mode.
SQLSTATE 26000 (statement does not exist)Driver named prepared statements executing across different backend processes.Set prepare: false (Drizzle), ?pgbouncer=true (Prisma), or statement_cache_size=0 (asyncpg).
SQLSTATE 42P05 (statement already exists)Multiple clients preparing identical named statements on shared backends.Upgrade to PgBouncer 1.21+ or configure drivers to use unnamed queries.
Database Migrations HangMigration tools attempting to acquire session-level advisory locks via pooler.Route migration commands strictly through direct port 5432 (directUrl).
High CPU under low query volumePostgreSQL forking processes and thrashing context switches.Cap pool size to (Physical Cores * 2) + Spindle Count baseline.

If your production backend is struggling with connection spikes, database locks, or unexpected latency cliffs, our team provides comprehensive architecture diagnostics. Review our 48-Hour Codebase Audit or collaborate directly with senior architects during an Architecture Hardening Sprint to stabilize your data tier. You can also contact our engineering desk to discuss your deployment requirements.

Written By

Marcus Vance

Principal Systems Architect

Systems engineer focusing on distributed backends, database concurrency, and application security. Specializes in high-throughput PostgreSQL concurrency, serverless connection pooling, and infrastructure hardening.

Practice: Vexn • Focus: Deep Engineering, Infrastructure & Security
Frequently Asked Questions
Why does PostgreSQL return SQLSTATE 53300 (remaining connection slots are reserved)?
PostgreSQL assigns a dedicated Linux backend process to every open client connection. When total incoming connections exceed max_connections minus superuser_reserved_connections, PostgreSQL terminates new connection attempts with SQLSTATE 53300 to protect admin maintenance channels.
What is the difference between direct port 5432 and pooler port 6543 in Supabase?
Port 5432 establishes a direct, 1:1 stateful TCP connection to PostgreSQL, exhausting memory and socket limits under minimal serverless traffic. Port 6543 routes through Supavisor in transaction pooling mode, multiplexing thousands of ephemeral client requests across a small pool of persistent backend connections.
Why do ORMs throw 'prepared statement does not exist' (SQLSTATE 26000) behind connection poolers?
In transaction pooling mode, subsequent queries within the same client session are routed across different backend PostgreSQL processes. If an ORM caches a prepared statement name on backend A and tries to execute it on backend B, PostgreSQL returns SQLSTATE 26000 because statement caches are local to each backend process.
Why do database migrations fail when run through transaction poolers?
Migration frameworks like Prisma Migrate, Rails ActiveRecord, and Flyway use session-level advisory locks (pg_advisory_lock) to prevent concurrent migrations. Transaction poolers swap connections after each transaction, causing session-level locks to fail, hang indefinitely, or trigger errors.
Need an Architectural Audit?

Have our team inspect your AI-generated codebase.

48-hour turnaround with direct pull requests fixing security and scale bottlenecks.

Request Audit