Your API does not need hundreds of simultaneous database queries to run out of connections. It can happen because every serverless instance creates its own local connection pool, and the pool's default size is larger than the workload needs. When instances scale horizontally, those small pools multiply.

The fix is not simply to increase the database connection limit. You need to understand two separate layers: the pool inside your application process and the pooler in front of PostgreSQL. They solve related problems, but they do not share the same limits.

The two pools people accidentally treat as one

An application-side pool lives inside your Node.js process. It reuses a few client connections so each request does not open a brand-new TCP connection. The server-side pooler sits between application clients and PostgreSQL. It can share a smaller number of actual database connections across many client connections.

In a long-running server, one application pool can serve many requests for the lifetime of that process. In a serverless platform, separate warm instances may each load the same database module and create their own pool. Module-scope reuse helps within one warm instance; it does not create one global pool across every instance.

A useful capacity estimate

Potential application-to-pooler clients are roughly the number of warm instances multiplied by the local pool maximum. For example, 40 warm instances with a pool maximum of 10 could create up to 400 client connections. This is an illustrative upper bound, not a traffic benchmark or a promise that every slot will be opened.

The pooler then has its own limits: how many clients it accepts and how many backend connections it may open to PostgreSQL. Those are different numbers. A pooler can reduce backend connection pressure, but it cannot make client limits, query capacity or database resources infinite.

Choose the connection mode before changing code

Supabase offers different connection paths for different workloads. Pick based on where the code runs and whether it needs a persistent PostgreSQL session.

WorkloadRecommended pathWhy
Browser or mobile clientSupabase Data API and client libraries with Row Level SecurityNo raw PostgreSQL connection string or database password belongs in the client.
Serverless functions or edge functionsShared pooler, transaction modeDesigned for many short-lived connections; use the transaction-pooler URI from the dashboard.
Long-running backend on IPv6Direct connection with a small application poolPersistent sessions without pooler overhead.
Long-running backend on an IPv4-only networkShared pooler, session modeKeeps session behavior while providing an IPv4-reachable endpoint.
Migrations, pg_dump, backup and replication toolsDirect connectionThese workflows often need a single persistent session or native PostgreSQL behavior.
High-load application on an eligible planDedicated pooler, transaction modeRuns alongside the database and can reduce pooler network latency; check its feature limits.

The shared pooler is available across Supabase plans and is IPv4-only. The dedicated pooler is available on the Pro Plan and above, runs in transaction mode, and supports prepared statements on PgBouncer 1.21 and later. Direct connections are normally IPv6 unless the project has the IPv4 add-on. These details can change, so use the current Supabase connection guide rather than copying a connection string from an old tutorial.

To get the correct URI, open the project dashboard, choose Connect, select the connection method and copy the generated string. Do not guess the pooler hostname or edit the username by hand: shared-pooler usernames differ from direct-connection usernames.

Set up a small Node.js pool per warm instance

For a serverless function using Supabase's shared transaction pooler, start with one client connection in the application-side pool. Create the pool once at module scope, not inside the request handler. Supabase specifically recommends a pool size of one for this pattern; raise it only after measuring that concurrent work inside one instance is waiting for a connection.

Example using pg (node-postgres):

import pg from "pg";

const { Pool } = pg;

const ssl = process.env.DATABASE_CA_CERT
  ? {
      ca: process.env.DATABASE_CA_CERT,
      rejectUnauthorized: true
    }
  : { rejectUnauthorized: true };

export const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 1,
  idleTimeoutMillis: 10_000,
  connectionTimeoutMillis: 5_000,
  ssl
});

pool.on("error", (error) => {
  console.error("Unexpected idle PostgreSQL client error", error);
});
  • DATABASE_URL should be the transaction-pooler URI copied from the Supabase dashboard and stored as a server-side environment variable.
  • max: 1 caps this process's local pool. It is not a project-wide connection cap.
  • connectionTimeoutMillis gives a request a finite wait instead of letting it wait indefinitely for a new client.
  • idleTimeoutMillis allows unused local clients to be closed after a period of inactivity.
  • ssl keeps certificate verification enabled. If Node does not trust the database certificate chain by default, store the root CA PEM from the dashboard in DATABASE_CA_CERT. Do not disable certificate checks just to make a connection succeed.

Keep the database password and full connection string on the server. If a browser app needs user data, use the Supabase client library and enforce access with Row Level Security policies. A public client key is not a substitute for authorization, and a service-role key must never be shipped to a browser.

Use parameterized queries without named prepared statements

The shared transaction pooler does not support prepared statements in transaction mode. With node-postgres, do not set the name property on a query configuration object. You can still use parameterized queries; parameterization and a named server-side prepared statement are not the same thing.

const result = await pool.query(
  "SELECT id, title FROM tasks WHERE id = $1",
  [taskId]
);

return result.rows[0] ?? null;

This keeps the value separate from the SQL text and avoids manually concatenating user input into a query. For other libraries, use the documented switch: Prisma uses pgbouncer=true, while Drizzle with Postgres.js uses prepare: false. Check the driver-specific guidance before assuming the setting is identical.

Keep each transaction on one checked-out client

pool.query() is convenient for a single independent statement because the pool checks out and returns a client for you. A multi-statement transaction must use one checked-out client from BEGIN through COMMIT or ROLLBACK.

export async function createOrder(order) {
  const client = await pool.connect();

  try {
    await client.query("BEGIN");

    const inserted = await client.query(
      "INSERT INTO orders (customer_id, total) VALUES ($1, $2) RETURNING id",
      [order.customerId, order.total]
    );

    await client.query(
      "INSERT INTO order_events (order_id, event_type) VALUES ($1, $2)",
      [inserted.rows[0].id, "created"]
    );

    await client.query("COMMIT");
    return inserted.rows[0];
  } catch (error) {
    await client.query("ROLLBACK").catch(() => {});
    throw error;
  } finally {
    client.release();
  }
}

The finally block matters. If a checked-out client is not released, the local pool can become exhausted even when PostgreSQL itself has free connections. Avoid calling pool.end() after every serverless request; that destroys the reusable pool and makes the next invocation reconnect.

Know what transaction pooling changes

Transaction mode assigns a backend connection for a transaction, then returns it to the shared pool when the transaction ends. The next transaction from the same application client may use a different PostgreSQL backend session. Code that assumes the same session survives between transactions can therefore break.

Do not rely on session-level state across separate transactions. Common trouble spots include:

  • Session-level SET or RESET values. Use SET LOCAL inside the transaction that needs the setting.
  • LISTEN subscriptions, which need a persistent session.
  • Session-level advisory locks.
  • Temporary tables or cursors that must survive beyond the transaction that created them.
  • Named prepared statements on the shared transaction pooler.

If your application genuinely needs a persistent session, use direct connection or session mode for that part of the workload. Do not force every connection through transaction mode just because the application also has serverless endpoints.

One driver-specific trap

Supabase's current Postgres.js quickstart warns that Postgres.js pipelines queries by default, while the shared transaction pooler does not support query pipelining. The guide documents a risk of hanging queries or mismatched results and says there is no working option to disable pipelining directly. Do not assume that max: 1 and prepare: false remove that incompatibility. Review the current driver guide before choosing Postgres.js for this connection mode.

Find out which connection limit you are hitting

Before raising a pool size, inspect actual connections. Supabase's dashboard exposes database and pooler connection charts, but those reports are not real-time. For a current database-side snapshot, query pg_stat_activity:

SELECT
  usename,
  application_name,
  state,
  count(*) AS connections
FROM pg_stat_activity
GROUP BY usename, application_name, state
ORDER BY connections DESC;

Use application_name to separate your web API, workers, migrations and other clients. If you see many idle sessions from one application, check whether each request is creating a new pool or whether checked-out clients are not being released. If the pooler itself is rejecting clients, inspect the pooler's client-connection limit and the compute size. If PostgreSQL is at its backend connection limit, inspect direct connections, pooler backend pools and Supabase services that also use database connections.

Supabase's pool-size setting applies per database role, not as one universal total for every role in the project. Multiple roles can therefore create separate pools. Leave headroom for Auth, Storage, PostgREST and other platform services instead of allocating every available connection to your application.

Three fixes that usually make the problem worse

Creating a pool inside every request

This throws away reuse. Put the pool in a module that the serverless runtime can reuse between warm invocations. The runtime may still create many instances, so combine this with a small local pool and a server-side pooler.

Increasing every pool to 20 or 50

A larger local pool multiplies across instances. Start small, measure pool wait time and query latency, and increase only when you can show that the local pool is the bottleneck. The PostgreSQL max_connections setting is not a free performance switch: PostgreSQL allocates resources based partly on that value, and it is configured at server start.

Retrying every failed query immediately

Retries can amplify a saturated database. First distinguish a connection timeout, a pooler client-limit error, a backend connection-limit error and a query that is simply slow. Apply bounded retries with backoff only to operations that are safe to retry, and avoid blindly repeating a transaction after the client has lost the connection because the commit outcome may be unknown.

A production checklist

  • Does each runtime use the connection mode designed for its workload?
  • Is the connection string copied from the dashboard and stored only in server-side secrets?
  • Is the local pool created at module scope and sized conservatively?
  • Are connection and query waits bounded with sensible timeouts?
  • Are checked-out clients always released in a finally block?
  • Are named prepared statements and session-dependent features compatible with the selected pooler mode?
  • Can you distinguish pooler client limits from PostgreSQL backend connection limits?
  • Do your monitoring queries identify the application, role and connection state?
  • Have you tested cold starts, warm reuse, concurrent requests and a database restart?

Pool for the way your code actually runs

Connection exhaustion is often a mismatch between a persistent database session and a runtime that creates many short-lived instances. For Supabase serverless functions, start with the shared transaction pooler and one local client per warm instance. Keep the pool at module scope, disable named prepared statements for that mode, avoid session-dependent features, and watch both pooler and database-side limits.

For long-running backends, migrations and tools that need session behavior, choose direct or session connections instead. The right connection mode is more important than an arbitrarily large pool.

For related backend work, read our guides to safer PostgreSQL schema migrations, PostgreSQL indexes and query performance, and reliable webhook processing. If you are planning a database-backed product, explore our software development services and SaaS solutions.

Sources and further reading

  1. Supabase: Connect to your database — connection modes, transaction pooler configuration, serverless client settings, SSL and driver limitations.
  2. Supabase: Connection pooling and limits — application-side versus server-side pools, client and backend limits, and monitoring.
  3. Supabase: Connection management — pool-size configuration and inspecting live sessions with pg_stat_activity.
  4. Supabase: Postgres.js quickstart — documented transaction-pooler query-pipelining caveat.
  5. Supabase: Disabling prepared statements — driver-specific configuration for transaction mode.
  6. PostgreSQL: Connections and Authentication — the meaning and resource implications of max_connections.
  7. node-postgres: Pool API and SSL configuration — pool defaults, timeouts, pool events and certificate validation.
  8. PgBouncer: Feature compatibility by pooling mode — the PostgreSQL session features affected by transaction pooling.