EthioDeploy
DocsPricingDomainsBlogToolsChangelog

Blog/Fix deploy errors

Postgres "too many connections" after deploy: how to fix it

BS
Brook SolomonPublished November 17, 2026
Share on XShare on LinkedIn
53300

THE SHORT ANSWER

Postgres refuses new connections with "FATAL: sorry, too many clients already" (SQLSTATE 53300, too_many_connections) once every slot under max_connections is taken, and max_connections defaults to 100. After a deploy the usual cause is arithmetic: each process of your app opens its own pool (10 for node-postgres and Prisma 7, 15 for SQLAlchemy), you run several processes, and for a short time the old and the new copy of the app are both connected. Count connections in pg_stat_activity, make copies × processes × pool max fit under the limit with room to spare, release clients you check out, set idle_in_transaction_session_timeout, and put PgBouncer in front when the numbers can't fit.

What does "too many clients already" mean?

Postgres has a fixed number of connection slots, set by max_connections. The PostgreSQL 16 docs say the default “is typically 100 connections”, and the setting “can only be set at server start”. When every slot is in use, the next connection gets:

FATAL:  sorry, too many clients already

Two more messages come from the same limit. Postgres 16 keeps a few slots back, and a role that isn't allowed to use them sees one of these instead:

FATAL:  remaining connection slots are reserved for roles with the SUPERUSER attribute
FATAL:  remaining connection slots are reserved for roles with privileges of the "pg_use_reserved_connections" role

All three carry SQLSTATE 53300, condition name too_many_connections, in class 53 “Insufficient Resources”. Drivers surface that code in their own way: Prisma reports P2037, “Too many database connections opened”; other drivers pass the Postgres message through.

The reserved slots work like this in Postgres 16:

  • superuser_reserved_connections, default 3: once free slots drop to 3, only superusers can connect.
  • reserved_connections, new in 16, default 0: slots above those for roles with privileges of pg_use_reserved_connections.

So with the defaults, an ordinary role gets 97 connections and sees the “reserved for ... SUPERUSER” message at the 98th. A superuser gets all 100 and then “sorry, too many clients already”.

Quick checklist

What you seeLikely causeFix
Errors only during or right after a deployOld and new copies of the app both hold a full poolSize pools so two copies fit under the limit
Errors after raising workers or adding a serviceEvery process has its own poolDo the math: copies × processes × pool max
Count climbs over hours, never dropsClients checked out and never releasedRelease in finally, or use pool.query
Many rows in idle in transactionTransactions opened and left hangingFix the code path; set idle_in_transaction_session_timeout
Next.js dev server runs out locallyHot reload creates a new Prisma Client each timeKeep one client on globalThis
The math can't fit under the limitMore clients than the server should holdPut PgBouncer in front

How do you see who is using the connections?

Connect with psql (you may need a reserved slot, see above) and start with the limit and the total:

SHOW max_connections;

SELECT count(*) FROM pg_stat_activity
WHERE backend_type = 'client backend';

pg_stat_activity has one row per server process. Filtering on backend_type leaves out the background processes like the checkpointer and autovacuum. Then group by who is connected and what they're doing:

SELECT application_name, client_addr, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2, 3
ORDER BY 4 DESC;

client_addr is the IP address of the client, so with containers each copy of the app shows up as its own address. That is how you spot an old copy that is still connected next to the new one. The state column tells you what the connections are doing:

  • active: running a query right now.
  • idle: waiting for a command. Normal for a pool, which keeps connections open.
  • idle in transaction: inside a transaction but not running anything. A few are normal; a steady pile means a leak.

application_name is empty unless the client sets it, so name each service. libpq accepts it as a URL parameter (?application_name=web), node-postgres keeps that parameter from the connection string and also takes an application_name option on the pool or the PGAPPNAME variable.

How many connections does your app actually open?

Every pool is per process. Multiply it out:

connections = copies of the app × processes per copy × pool max
            + anything else (workers, cron jobs, psql, GUI clients)

The pool max depends on the library, and the defaults are higher than people expect:

LibraryDefault per poolSetting
node-postgres (pg)10max
Prisma 7 with @prisma/adapter-pg10 (the pg default)max on PrismaPg
Prisma 6physical CPUs × 2 + 1?connection_limit= in the URL
SQLAlchemy QueuePool5 + 10 overflow = 15pool_size, max_overflow
DjangoOne per threadCONN_MAX_AGE, or OPTIONS["pool"] on 5.1+

The process count is the one that sneaks up on Python apps. Gunicorn's workers setting is “the number of worker processes for handling requests”, it defaults to WEB_CONCURRENCY or 1, and the docs suggest 2 to 4 per CPU core. SQLAlchemy's docs say pooled connections “are not shared to a forked process”, so each worker builds its own pool. Four workers with the default engine can open 60 connections. With --threads, Django holds one connection per thread: its docs say the database “must support at least as many simultaneous connections as you have worker threads”.

Now the deploy. A zero-downtime deploy starts the new copy and waits for it to pass a health check before stopping the old one. For that window you have two copies, each with a full set of pools. The Gunicorn app above needs up to 120 connections during the switch, against a limit of 100. The old copy goes away seconds later, which is why the error shows up in deploy logs and then seems to fix itself.

Pick numbers that fit with room left over. A rough budget for a 100-slot server: keep two copies of everything under about 80, which leaves space for migrations, a cron job and you in psql. For the Gunicorn example, 4 workers with pool_size=5, max_overflow=5 is 40 per copy and 80 during a deploy.

How do you size the pool in Node.js and Prisma?

Create one pool per process, at module level, and set max on purpose. node-postgres closes idle clients after idleTimeoutMillis (10 seconds by default), so a quiet app gives connections back on its own:

import { Pool } from "pg";

export const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
  max: 5,
  idleTimeoutMillis: 10_000,
  connectionTimeoutMillis: 5_000, // default 0 waits forever
  application_name: "web",
});

With Prisma 7 the same options go on the adapter, because “connection pooling defaults (and configuration) now come from the driver itself”. In Next.js, keep a single client across hot reloads. This is the pattern from Prisma's Next.js page, with the adapter added:

import { PrismaPg } from "@prisma/adapter-pg";
import { PrismaClient } from "../prisma/generated/client";

const globalForPrisma = global as unknown as { prisma: PrismaClient };

export const prisma =
  globalForPrisma.prisma ||
  new PrismaClient({
    adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL, max: 5 }),
  });

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

Without it, Prisma's docs warn that hot reloading “can lead to multiple instances of Prisma Client being created”, each with its own adapter and pool. In production the module loads once, so the global only matters in development. On Prisma 6, put the limit in the URL instead: ?connection_limit=5. Pool timeouts show up as P2024, not as a Postgres error; for unreachable-database errors see Prisma P1001: Can't reach database server.

How do you size the pool in Django and SQLAlchemy?

For SQLAlchemy, set the pool on the engine and remember it applies per worker process:

engine = create_engine(
    os.environ["DATABASE_URL"],
    pool_size=5,
    max_overflow=5,
    pool_pre_ping=True,
)

pool_pre_ping doesn't change the count; it sends a test query (usually SELECT 1) each time a connection is checked out. If you use Gunicorn's --preload, the engine may be created before the fork. SQLAlchemy's docs recommend calling engine.dispose(close=False) in the child so it never touches the parent's connections.

Django's default CONN_MAX_AGE is 0, which closes the connection at the end of each request. A positive number keeps one connection per thread for that many seconds, and None keeps it forever. Django 5.1 added a real pool for psycopg 3:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        # ...
        "OPTIONS": {
            "pool": True,  # or a dict passed to psycopg_pool.ConnectionPool
        },
    },
}

It needs psycopg[pool] and is ignored with psycopg2. It is also a pool per process, so the Gunicorn multiplication still applies.

What if the count keeps growing?

If connections climb over hours and stay up, something checks out connections and doesn't give them back. In node-postgres, every pool.connect() needs a release(). The docs say an unreleased client stays out of the pool, and once all of them are out, new pool.connect calls time out, or hang forever if connectionTimeoutMillis is 0:

const client = await pool.connect();
try {
  await client.query("BEGIN");
  // ...
  await client.query("COMMIT");
} catch (err) {
  await client.query("ROLLBACK");
  throw err;
} finally {
  client.release();
}

For single queries, pool.query() checks out and releases for you (but not for transactions, which need one client). A pool leak by itself stops at the pool's max; the database only runs out when something keeps creating new pools, like a new Pool() or new PrismaClient() inside a request handler.

Connections stuck in idle in transaction are a different leak: the code opened a transaction and is waiting on something else, or crashed between BEGIN and COMMIT. Find them by age:

SELECT pid, application_name, client_addr, now() - state_change AS idle_for, query
FROM pg_stat_activity
WHERE state = 'idle in transaction'
ORDER BY idle_for DESC;

query shows the last statement, which usually points at the code path. To free slots now, SELECT pg_terminate_backend(pid) ends a session. To stop it recurring, set idle_in_transaction_session_timeout; the default of 0 means never. ALTER ROLE ... SET makes it the default for every new session that role logs in with:

ALTER ROLE app_user SET idle_in_transaction_session_timeout = '60s';

When should you add PgBouncer?

Raising max_connections is possible but it doesn't scale well. Postgres “uses one process per connection”, and its own docs say that “it may be better to reduce max_connections and instead make use of external connection-pooling software”.

PgBouncer sits between your app and Postgres. Its max_client_conn defaults to 100 clients and default_pool_size to 20 server connections per user/database pair, so many app connections share a few real ones. What gets shared depends on pool_mode:

  • session (default): a server connection belongs to a client until it disconnects. Supports every Postgres feature, but saves connections only when clients connect and leave often.
  • transaction: a server connection is lent out only for the length of a transaction. This is the mode that lets many app connections share a few server connections.

Transaction mode has costs. PgBouncer's feature table marks SET/RESET, LISTEN, WITH HOLD cursors, SQL PREPARE and session-level advisory locks as not supported, and protocol-level prepared statements need max_prepared_statements set above 0. Django's docs add that server-side cursors break and suggest DISABLE_SERVER_SIDE_CURSORS.

What happens on EthioDeploy?

A Postgres addon runs the stock postgres:16 image without extra server flags, so max_connections is the default 100. The app gets:

postgres://ethiodeploy:<password>@<addon-host>:5432/ethiodeploy

The ethiodeploy role is the image's POSTGRES_USER, which the official image creates as a superuser. That means the 3 superuser-reserved slots aren't held back from your app: it can use all 100 and then gets “sorry, too many clients already”. It also means there is no spare slot left for you to log in and look, so keep your own budget below 100.

Three things on the platform add to the count:

  • Deploys are blue-green. The old container keeps serving until the new one passes its health check and traffic moves over, then the old one is stopped. For that window both copies hold their pools, so size pools for two copies.
  • Branch deployments share the database. Each branch deployment joins the addon's network and gets the same DATABASE_URL, so every running branch adds its own pools to the same 100 slots.
  • External access is capped per IP. Connections from your own computer through the Addons tab are limited to 20 at a time per source IP, which keeps a GUI client from eating the app's slots.

Connections cost memory as well as slots, because each one is a separate server process inside the addon container. Postgres addons get 256 MB and 0.25 CPU on Free, 512 MB and 0.5 CPU on Pro, and 1 GB and 1 CPU on Business. A small pool is the better default on the smaller plans.

EthioDeploy doesn't run a PgBouncer for you. Lower the pool sizes first: for a Node app, max: 5 leaves room for production, a deploy overlap and a few branches. Framework specifics are in the Next.js, Express, Django and FastAPI deploy guides.

Questions

Every connection slot under max_connections is in use, so Postgres refused the new one. The default max_connections is typically 100. The error has SQLSTATE 53300, too_many_connections.

A zero-downtime deploy runs the new copy of the app next to the old one until the new one is healthy. For that window both copies hold their connection pools, so the total can be twice the normal count. Size pools so two copies fit under the limit.

Prisma 7 with @prisma/adapter-pg uses node-postgres's pool, which defaults to max 10 per client. Prisma 6 defaults to the number of physical CPUs times 2, plus 1, set with connection_limit in the URL. Each PrismaClient you create has its own pool, so create one per process.

Only after you've counted where the connections come from. Postgres uses one process per connection, and its docs suggest lowering max_connections and using an external pooler such as PgBouncer when you need many clients.

The server has only its superuser-reserved slots left (3 by default) and your role isn't a superuser. It is the same problem as too many clients already, just hit a few connections earlier.

Query pg_stat_activity for state = 'idle in transaction' and sort by now() - state_change. The query column shows the last statement each one ran. Set idle_in_transaction_session_timeout so Postgres ends them automatically.

Sources

Checked on November 17, 2026:

  • PostgreSQL 16: Connection settings
  • PostgreSQL 16: Error codes
  • PostgreSQL 16: The cumulative statistics system (pg_stat_activity)
  • PostgreSQL 16: Client connection defaults
  • PostgreSQL 16: ALTER ROLE
  • PostgreSQL 16: System administration functions
  • PostgreSQL 16: Managing kernel resources
  • PostgreSQL 16: libpq connection strings
  • PostgreSQL 16 source: proc.c
  • PostgreSQL 16 source: postinit.c
  • Docker Hub: postgres official image
  • node-postgres: Pool
  • pg-connection-string README
  • Prisma: Connection pool (v7)
  • Prisma: Connection pool (v6)
  • Prisma: Error reference (v7)
  • Prisma: Next.js troubleshooting (v7)
  • SQLAlchemy 2.0: Connection pooling
  • Django 5.2: Databases
  • Gunicorn: Settings
  • PgBouncer: Configuration
  • PgBouncer: Features

Push a repo. Get a URL.

  • Database addons
  • Branch deployments
  • Deploy a Next.js app
  • Deploy an Express app
  • Deploy a Django app
  • Deploy a FastAPI app
Start free

Join the EthioDeploy Telegram

Release notes as they ship, plus deploy help from the team and other developers.

Join on Telegram
BS
WRITTEN BYBrook SolomonFounder, EthioDeploy

Brook Solomon founded EthioDeploy and builds its deploy pipeline, build servers and AI coding agent. The posts here come from errors seen in real deploys on the platform.

All posts by Brook →
On this page
  • What does "too many clients already" mean?
  • Quick checklist
  • How do you see who is using the connections?
  • How many connections does your app actually open?
  • How do you size the pool in Node.js and Prisma?
  • How do you size the pool in Django and SQLAlchemy?
  • What if the count keeps growing?
  • When should you add PgBouncer?
  • What happens on EthioDeploy?
  • Questions
  • Sources
0% read

Keep reading

  • NEXT_PUBLIC_*

    Fix deploy errorsNov 17, 2026

    NEXT_PUBLIC_ env variables undefined in production: causes and fixes

    A NEXT_PUBLIC_ variable is undefined in production when it wasn't set while next build ran. Next.js replaces every process.env.NEXT_PUBLIC_ reference with a fixed value during the build, so a variable added to the server afterwards changes nothing until you build again. The other usual causes are reading it dynamically (process.env[name] or a copy of process.env), a name without the NEXT_PUBLIC_ prefix in a Client Component, and one Docker image promoted across environments. For values that must change without a rebuild, read them on the server at request time and pass them down.

  • Invalid HTTP_HOST header

    Fix deploy errorsNov 15, 2026

    Django DisallowedHost and CSRF errors behind a proxy

    DisallowedHost means the request's Host header isn't in ALLOWED_HOSTS, so Django answers 400; add your production domain to the list. The CSRF 403 "Origin checking failed - https://... does not match any trusted origins" usually means Django thinks the request came over plain HTTP: the proxy ended HTTPS and forwarded it as HTTP, so Django expects an http:// origin and the browser sent https://. Set SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") when your proxy sets that header. Since Django 4.0, entries in CSRF_TRUSTED_ORIGINS must include the scheme, such as https://example.com.

  • npm error code ERESOLVE

    Fix deploy errorsNov 15, 2026

    npm ERESOLVE peer dependency error on deploy

    ERESOLVE means a package's peerDependencies range doesn't accept the version your project already uses, and npm 7 and later refuse to build that tree. It often passes locally because your package-lock.json was made with --legacy-peer-deps, your ~/.npmrc sets legacy-peer-deps=true, or your local npm is older, while the build server runs a clean npm ci without any of that. Fix it by upgrading the package to a version whose peer range fits, by forcing the version with overrides in package.json, or, as a last resort, by committing legacy-peer-deps=true in a project .npmrc so every install, local and on deploy, resolves the same way.

EthioDeploy

Agentic first development and deployment, started in Ethiopia, built for developers everywhere.

Telegram community
Product
PricingAI coding agentAgent mode docsDomainsCLIFree backend hostingHosting in EthiopiaChangelog
Deploy guides
Next.jsNode.jsPythonSvelteKitTanStack StartAstroNuxtReact RouterHonoStrapiDjangoFastAPIFlaskStreamlitExpressNestJSLaravelRailsGoTelegram botDiscord botLovableBoltReplitv0Google AI StudioBase44Firebase StudioClaude Code & Cursor
Compare
vs Herokuvs Vercelvs Rendervs Railwayvs Fly.iovs Netlifyvs KoyebHeroku alternativesVercel alternativesNetlify alternativesRender alternativesRailway alternativesFly.io alternativesReplit alternativesPythonAnywhere alternativesDigitalOcean App Platform alternativesGlitch alternatives
Resources
DocsBlogFree toolsAboutSupportContactllms.txt
© 2026 EthioDeployPay by card in USD or bank transfer in ETBTermsPrivacy