PostgreSQL refuses new clients with a "too many connections" error (SQLSTATE 53300) once every allowed slot is active, or earlier for ordinary application roles because superuser slots are held back. On this page I reproduce both failure modes in Docker on Windows 11, measure a 110-client burst and a 450-client idle run inside a 2 GiB memory-capped container, and configure PgBouncer transaction pooling in front of PostgreSQL resource limits so bursts queue cleanly instead of crashing.
Short Answer (Quick Fix): Do not blindly raise
max_connections = 500on a memory-constrained server. Every PostgreSQL connection forks a dedicated backend OS process that can allocate multiplework_mem(4 MBdefault) sort buffers andwork_mem × hash_mem_multiplier(8 MBdefault) hash tables when queries are active. Instead, keep PostgreSQL port5432internal to your Docker bridge network and place PgBouncer in front of it on port6432withpool_mode = transactionanddefault_pool_size = 12..20. In my 2 GiB container test with 110 concurrent clients, direct connections resulted in 100 succeeded and 10 failed (FATAL: sorry, too many clients already), whereas routing the same 110 clients through PgBouncer resulted in 110 succeeded and 0 failed using just81.5 MiBon PostgreSQL and3.297 MiBon PgBouncer.
Tested on: Windows 11 Pro 23H2 | WSL 2 Kernel 6.6.87.2-microsoft-standard-WSL2 | Official Docker Engine 27.3.1 (Compose v2.29.7, desktop-linux) | postgres:16-alpine (PostgreSQL 16.6) & postgres:17-alpine (PostgreSQL 17.2) | edoburu/pgbouncer & Alpine pgbouncer 1.23.1 | Execution Date: 2025-01-30 ~ 2025-01-31
What I Tested: max_connections=5 and 100, With and Without PgBouncer
To isolate the exact mechanics of connection exhaustion before scaling up to a 2 GiB container benchmark, I started a postgres:16-alpine test container named gfl-pg on Docker Desktop for Windows 11 with max_connections=5, verified the active limit via SHOW max_connections, and launched six concurrent psql clients at once:

In this first test on 2025-01-30, docker exec gfl-pg psql -U postgres -tAc "show max_connections" returned 5. When the shell loop fired six background workers running psql -U postgres -tAc "select pg_sleep for 5s" simultaneously, the first five processes claimed all five backend slots in pg_stat_activity. The sixth client immediately failed on the Unix domain socket with psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: FATAL: sorry, too many clients already, and docker logs gfl-pg 2>&1 | tail -1 recorded the matching server-side rejection under SQLSTATE 53300 (too_many_connections).
Notice an important detail about why we saw FATAL: sorry, too many clients already on the sixth client instead of an earlier error on the third client: every worker in that one-liner connected as -U postgres, which is a database superuser. Because superuser connections are permitted to dip into PostgreSQL's reserved administrative slots, those sessions consumed all five total slots on the server. To make both failure modes reproducible from a clean container state, I saved the exact hard-limit burst and the non-superuser reserved-slot check as standalone shell scripts inside the test container:

Why the Error Can Mention Superuser Slots
PostgreSQL does not hand out every slot in max_connections to ordinary application users. Per the PostgreSQL connection settings documentation, superuser_reserved_connections defaults to 3, and PostgreSQL 16+ also provides reserved_connections (default 0) for roles granted pg_use_reserved_connections. Those final slots stay reserved so you can still connect with psql -U postgres to query pg_stat_activity or run pg_terminate_backend() when a client spike exhausts normal slots.
# Check reserved-slot settings on the same max_connections=5 server:
docker exec gfl-pg psql -U postgres -tAc "show superuser_reserved_connections"
# 3
docker exec gfl-pg psql -U postgres -tAc "show reserved_connections"
# 0
On a server configured with max_connections=5 and superuser_reserved_connections=3, an ordinary login role without the SUPERUSER attribute is only allowed to use 5 - 3 = 2 concurrent slots. On 2025-01-30, I created a non-superuser role named app inside gfl-pg and ran /lab/pg_reserved.sh to open three concurrent sessions with it while a superuser probe checked active backends:

What this means in practice:
- Non-superuser application roles hit the wall earlier than
max_connections: Becauseappis not a superuser (rolsuper = false), it could only open2sessions (app|2in the output above, which equalsmax_connectionsminussuperuser_reserved_connectionsandreserved_connections). The thirdappconnection failed immediately, even though only two of the five total server slots were occupied byappand a superuser session (postgres|1) could still connect right alongside it. - The error message wording depends on your PostgreSQL version: Older PostgreSQL releases print
FATAL: remaining connection slots are reserved for non-replication superuser connections. In PostgreSQL 16 and 17, wherereserved_connectionsalso exists, the server printsFATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute(as seen in thepostgres:16-alpinelog above). - Running your application as
postgresdestroys your emergency recovery path: If your application connects as a superuser (for example, using the defaultpostgresuser in a Docker Compose file), it will consume the reserved slots too and fail later withFATAL: sorry, too many clients already, leaving zero slots for you to log in and recover the database.

Scaling that exact arithmetic from our max_connections=5 lab container to a standard PostgreSQL container where max_connections defaults to 100 explains why production services often fail at 98 concurrent connections rather than 101. With max_connections = 100, superuser_reserved_connections = 3, and reserved_connections = 0, an application connecting with a non-superuser role such as app or gearflow can open at most 97 concurrent backend sessions before the 98th connection is rejected with SQLSTATE 53300.
Conversely, if an application connects as the postgres superuser against max_connections = 100, it will use all 100 slots and reject the 101st client. When we place PgBouncer in front of PostgreSQL in transaction mode with default_pool_size = 20 (or default_pool_size = 3 on the max_connections = 5 container), PostgreSQL backend consumption is capped at the pool size, leaving the remaining normal slots and all three superuser slots untouched (you can model exact shared_buffers, per-backend RSS, and default_pool_size ceilings for your own container RAM in our PostgreSQL & PgBouncer Memory Pool Calculator):

Measured: 110 Clients in a 2 GB Container, With and Without PgBouncer
To test how default connection limits and connection pooling behave inside a fixed memory envelope, on 2025-01-31 I ran postgres:17-alpine (PostgreSQL 17.2) on Docker Desktop in a container capped at 2 GiB of RAM and swap (--memory=2g --memory-swap=2g, verified inside the container as memory limit bytes=2147483648). For the 110-client tests, PostgreSQL used its default connection settings: max_connections = 100, superuser_reserved_connections = 3, and reserved_connections = 0.
In both 110-client runs, a separate client container launched 110 concurrent psql processes at the same time, with each client executing SELECT pg_sleep for 15s to hold its transaction open for 15 seconds. I then ran a third test in a fresh 2 GiB container with max_connections = 500 and 450 concurrent sleeping clients (SELECT pg_sleep for 40s) to measure the raw memory footprint of idle backend processes before any sort or hash operations occur. Selected lines from the raw benchmark log are shown below:

Here is what happened across the first two 110-client runs in that 2 GiB container:
- Run A: Straight to PostgreSQL (110 clients at once): Exactly 100 succeeded and 10 failed. Each of the 10 rejected clients exited immediately with
psql: error: connection to server at "gfl-pg" ([REDACTED_IP]), port 5432 failed: FATAL: sorry, too many clients already. Even the 5-second mid-run probe that tried to countpg_stat_activityfrom outside failed with the same error because all 100 slots were already full. After the burst finished, container memory usage ongfl-pgwas54.78 MiB / 2 GiB. - Run B: Through PgBouncer (110 clients at once): Using
PgBouncer 1.23.1from Alpine's package configured withpool_mode = transaction,default_pool_size = 20, andmax_client_conn = 200, all 110 clients succeeded and 0 failed. At 5 seconds into the burst,SHOW POOLSreportedcl_active = 20,cl_waiting = 90, andsv_active = 20, while PostgreSQL had only21client backends (the 20 pooled server connections plus the probe query itself). Ninety waiting clients receivedNOTICE: No server connection available in postgres backend, client being queuedand completed as earlier 15-second queries finished, taking90 secondstotal (5.5 waves × 15s). Memory usage was81.5 MiB / 2 GiBfor PostgreSQL and3.297 MiBfor PgBouncer.

- Run C:
max_connections=500in a fresh 2 GB container (450 sleeping clients): Before launching clients, the idle PostgreSQL 17.2 container used46.65 MiB / 2 GiB. With 450 clients connected at once and runningSELECT pg_sleep for 40s, PostgreSQL reached451client backends at 20 seconds, and container memory usage climbed to739.5 MiB / 2 GiB(cpu=0.03%) withOOMKilled=falseandrunning=true. These clients were sleeping, not working. I did not test busy queries, a largework_mem, or a real 2 GB Linux VPS where the host kernel and system services share the same 2 GB of RAM.
The Naive Fix: Raising max_connections
When applications start throwing FATAL: sorry, too many clients already, the most common reflex is to open postgresql.conf (or pass a Docker command flag) and raise the connection limit:
# /var/lib/postgresql/data/postgresql.conf
# Naive change: raising the limit without a connection pooler
max_connections = 500
In my 2 GiB container test above, 450 idle backends running pg_sleep for 40s already pushed PostgreSQL memory from 46.65 MiB to 739.5 MiB without executing a single sort or hash join. According to the PostgreSQL documentation, each active sort or merge operation can allocate up to work_mem (4 MB by default), and hash-based operations can allocate up to work_mem × hash_mem_multiplier (2.0 by default, or 8 MB per hash table), with complex queries allocating several such buffers simultaneously per backend:

One practical failure from the lab is also worth calling out if you build your own PgBouncer container on Alpine Linux rather than using a prepackaged image. In my first attempt at the 2 GiB PgBouncer benchmark run, I installed Alpine's pgbouncer package (apk add --no-cache pgbouncer) and started the daemon with pgbouncer -u pgbouncer -d /etc/pgbouncer/pgbouncer.ini.
That container exited immediately with code 1 because Alpine's package did not create a system user named pgbouncer: running id pgbouncer inside the container returned id: unknown user pgbouncer, and PgBouncer aborted at startup with FATAL CannotFindUser: getpwnam("pgbouncer") failed. Because the container stopped right away, Docker's embedded DNS server removed the gfl-pgb hostname from the bridge network, and all 110 clients failed with psql: error: could not translate host name "gfl-pgb" to address: Name does not exist. Starting the daemon with pgbouncer -u nobody (using Alpine's built-in unprivileged nobody account) fixed the startup failure immediately:

Why PostgreSQL Connections Are Heavy
Comparing the measured memory numbers across all three 2 GiB container runs makes the cost of PostgreSQL's connection architecture concrete. Moving from 0 clients (46.65 MiB) to 450 sleeping clients (739.5 MiB across 451 backends) added 692.85 MiB of RAM (roughly 1.54 MiB per idle backend process) before a single real query ran. By contrast, handling 110 concurrent clients through PgBouncer required just 81.5 MiB on PostgreSQL (for 21 backends) plus 3.297 MiB on PgBouncer, or 84.8 MiB combined, nearly nine times less memory than 450 sleeping PostgreSQL backends.
When backends transition from sleeping to executing real queries that sort rows and build hash tables, memory usage scales with the number of active PostgreSQL backends rather than total client sockets. Even a single 4 MB sort buffer and a single 8 MB hash table (+12 MB per active backend) across 150 concurrent backends adds 1,800 MiB on top of the backend process footprint, crossing the 2,048 MiB container ceiling:

Three architectural factors explain why direct PostgreSQL connections carry this footprint:
- The
postmasterforks a dedicated OS process per connection: Unlike event-loop proxies or thread-per-request servers, PostgreSQL uses a process-per-connection model. Every time an application opens a TCP socket to port5432, the supervisor process forks a separatepostgresbackend process with its own private address space, catalog caches, and lock-table state. work_memandhash_mem_multiplierapply per operation, per backend: Whileshared_buffersis allocated once for the entire PostgreSQL instance,work_mem(default4 MB) limits each individual sort or merge node, andwork_mem × hash_mem_multiplier(default2.0, so8 MB) limits each hash table node. If 100 active backends each run a query containing one sort and one hash join, those operations alone can legally allocate1,200 MBof private memory.- Idle connections still hold backend processes and connection slots: Even when an application worker is waiting on external HTTP calls or sitting idle in a framework pool, its dedicated PostgreSQL backend process remains resident in memory and occupies one slot out of
max_connections.
PgBouncer, by contrast, keeps client sockets cheap. Its official documentation notes a footprint of roughly 2 kB per connection by default, and in our 110-client benchmark on Alpine Linux the entire pgbouncer container used just 3.297 MiB of RAM:

Putting PgBouncer in Front of PostgreSQL
Instead of allowing hundreds of application containers, serverless functions, or queue workers to open direct connections to PostgreSQL on port 5432, you place PgBouncer in front of the database on port 6432. In transaction pooling mode, PgBouncer accepts up to max_client_conn client connections (for example, 200), assigns a real PostgreSQL backend connection from default_pool_size only for the duration of a single transaction, and immediately returns that backend connection to the pool as soon as the transaction commits or rolls back.

pool_mode = transaction, max_prepared_statements = 200) collapses active PostgreSQL backend processes down to 25 warm workers inside memory-constrained Docker cgroups.To verify this on the exact same postgres:16-alpine server with max_connections=5 that rejected the 6th client in our first test, I started edoburu/pgbouncer in transaction mode with a pool size of 3 (default_pool_size=3) and connected 10 concurrent clients at once, each running SELECT pg_sleep for 2s:

All 10 clients printed ok (client 8 ok, client 9 ok, client 5 ok, client 2 ok, client 7 ok, client 1 ok, client 4 ok, client 10 ok, client 6 ok, client 3 ok) against a PostgreSQL server whose hard max_connections limit was still 5. Look at the completion order: because default_pool_size was set to 3, the first three clients to finish the TCP handshake acquired the three server connections and ran their 2-second sleep while the other seven clients waited in PgBouncer's queue (cl_waiting = 7). As each 2-second transaction finished, PgBouncer immediately handed those same three PostgreSQL backends to the next waiting clients until all 10 succeeded.
This exact pattern applies when self-hosting multi-worker applications such as n8n, Node.js microservices, or Python API workers in Docker. By pointing the application's PostgreSQL credential at Host: pgbouncer_pool and Port: 6432 using a non-superuser role (gearflow), webhook bursts never exhaust PostgreSQL backend slots:

Step 1: Create the Integrated Docker Compose Stack
Below is a production-ready docker-compose.yml pattern that pairs postgres:16-alpine with edoburu/pgbouncer:latest on an isolated Docker bridge network. Notice that PostgreSQL uses expose: ["5432"] rather than ports: ["5432:5432"] so that only containers on the internal network can reach port 5432, forcing all host and application traffic through PgBouncer on port 6432:
services:
postgres:
image: postgres:16-alpine
container_name: postgres_db
restart: unless-stopped
environment:
POSTGRES_USER: gearflow
POSTGRES_PASSWORD: ${DB_PASSWORD}
POSTGRES_DB: production_db
expose:
- "5432"
volumes:
- pg_data:/var/lib/postgresql/data
networks:
- backend_net
pgbouncer:
image: edoburu/pgbouncer:latest
container_name: pgbouncer_pool
restart: unless-stopped
environment:
DATABASE_URL: "postgres://gearflow:${DB_PASSWORD}@postgres:5432/production_db"
POOL_MODE: transaction
MAX_CLIENT_CONN: 200
DEFAULT_POOL_SIZE: 12
MIN_POOL_SIZE: 2
RESERVE_POOL_SIZE: 3
ADMIN_USERS: postgres,gearflow
ports:
- "127.0.0.1:6432:6432"
depends_on:
- postgres
networks:
- backend_net
volumes:
pg_data:
networks:
backend_net:
driver: bridge
If you prefer using Alpine's native pgbouncer package (as in our 2 GiB benchmark run with PgBouncer 1.23.1) instead of environment-variable wrappers, map the equivalent settings directly in /etc/pgbouncer/pgbouncer.ini and include max_prepared_statements = 100:

Step 2: Understanding Pool Modes
PgBouncer supports three pooling modes that determine when a PostgreSQL server connection can be reassigned to another client:
| Pool Mode | When Server Connection Is Released | Best Use Case & Caveats |
|---|---|---|
Transaction (pool_mode = transaction) |
As soon as the transaction ends (COMMIT / ROLLBACK or single statement). |
Recommended default for web apps & workers. Session-scoped features (SET, advisory locks, SQL PREPARE) cannot cross transactions. |
Session (pool_mode = session) |
Only when the client disconnects from PgBouncer. | Supports all session state, but idle connected clients still pin a PostgreSQL backend until they disconnect. |
Statement (pool_mode = statement) |
After every single SQL statement. | Rejects multi-statement transactions (BEGIN ... COMMIT); rarely suitable for general applications. |
Prisma & ORM Prepared Statement Note (PgBouncer 1.21.0+): Older guides state that
pool_mode = transactionbreaks all prepared statements unless you disable them in your client (such as appending?pgbouncer=truein Prisma). Starting in PgBouncer 1.21.0 (including1.23.1tested here), PgBouncer can track and rewrite protocol-level prepared statements (PostgreSQL Extended Query ProtocolParse/Bindmessages) in transaction mode when you setmax_prepared_statementsabove0(for example,max_prepared_statements = 100). SQL-levelPREPARE name AS .../EXECUTEstatements remain unsupported in transaction mode.

Step 3: Verify the Pool in Action
Once your user is listed under admin_users or stats_users in pgbouncer.ini (or ADMIN_USERS in edoburu/pgbouncer), you can connect to PgBouncer's special virtual database named pgbouncer on port 6432 and inspect live connection multiplexing with SHOW POOLS;:
docker exec -it pgbouncer_pool psql -U gearflow -p 6432 -d pgbouncer -c "SHOW POOLS;"
In the SHOW POOLS; output from our 110-client 2 GiB container benchmark (IMG_06 and IMG_07), the key columns tell the whole story at a glance: cl_active (20) is the number of client connections currently linked to a server connection; cl_waiting (90) is the number of clients queued waiting for a server connection in transaction mode; and sv_active (20) is the number of active backend connections opened to PostgreSQL. Because default_pool_size was 20 and each client ran SELECT pg_sleep for 15s, PgBouncer drained those 110 clients in five waves of 20 (75 seconds) plus a sixth wave for the final 10 clients (15 seconds), totaling exactly 90 seconds with zero connection failures:

Putting all four pieces together, network port isolation (expose: ["5432"]), non-superuser application roles (rolsuper = false), transaction-mode pooling (default_pool_size = 12..20), and protocol prepared statement tracking (max_prepared_statements = 100), creates a predictable capacity boundary inside Docker. Even if 200 application workers connect to port 6432 simultaneously during an inbound webhook or API traffic spike, PgBouncer opens at most DEFAULT_POOL_SIZE + RESERVE_POOL_SIZE (12 + 3 = 15, or 20 + 3 = 23) backend connections to PostgreSQL on internal port 5432.
On a default max_connections = 100 instance with superuser_reserved_connections = 3, that architecture leaves more than 74 normal connection slots completely unallocated, preventing concurrent per-backend work_mem sort buffers and hash_mem_multiplier hash tables from cascading into a Linux cgroup OOM kill (Exit Code 137), while keeping slots 98..100 strictly reserved for emergency psql -U postgres database administration and live recovery:

Before closing out a production deployment or incident review, run the six verification commands in the operational checklist card below to confirm your slot headroom, role privileges, internal port isolation, daemon user, active pool state, and protocol prepared statement cache:

Last reviewed: 2025-01-31. Reproduced on Docker Desktop (Windows 11 Pro 23H2, Official Docker Engine 27.3.1, Compose v2.29.7): the hard connection limit and PgBouncer pooling with max_connections=5 (2025-01-30, postgres:16-alpine 16.6, edoburu/pgbouncer); reserved superuser slots (2025-01-30, PostgreSQL 16.6); and on 2025-01-31, in a container capped at 2 GiB with PostgreSQL 17.2, 110 clients against max_connections=100 (10 rejected), the same 110 clients through PgBouncer 1.23.1 from Alpine's package (all 110 succeeded), and 450 sleeping clients at max_connections=500 (739.5 MiB RSS, no OOM kill). Not tested: a real 2 GB Linux VPS where the OS kernel shares the 2 GB budget, busy multi-sort queries at max_connections=500, and third-party ORM client libraries beyond protocol-level prepared statement verification.
Quick Pre-Flight Verification Checklist
- ✓ 1. Non-Superuser Role Enforced: Application connects as
gearflow/app(rolsuper = false), preservingsuperuser_reserved_connections = 3for emergency DBA login. - ✓ 2. Internal Bridge Isolation Active: PostgreSQL uses
expose: ["5432"]while PgBouncer listens on6432withpool_mode = transactionanddefault_pool_size = 12..20. - ✓ 3. Prepared Statements & Pool Queue Verified:
SHOW CONFIG;confirmsmax_prepared_statements = 100andSHOW POOLS;confirmssv_active <= default_pool_size.
PgBouncer Transaction Pooling & PostgreSQL Slot Limits Q&A
Why do ordinary database users hit too many connections at 97 slots when max_connections is 100?
PostgreSQL reserves superuser_reserved_connections=3 by default so a DBA can still log in during connection exhaustion. Non-superuser application roles can only occupy the remaining 97 slots before failing with SQLSTATE 53300.
How much RAM does PgBouncer save compared to raising PostgreSQL max_connections to 500?
In our 2 GiB Docker container test on PostgreSQL 17.2, 450 idle client backends consumed 739.5 MiB of RAM before running a single query. Routing 110 concurrent clients through a 20-backend PgBouncer 1.23.1 transaction pool queued bursts with zero errors at just 84.8 MiB combined RAM.
Why do prepared statements break under PgBouncer transaction pooling unless configured?
Transaction pooling reassigns server backends between transactions, so session-scoped prepared statements vanish on the next query unless you run PgBouncer 1.21+ with max_prepared_statements set (for example 200) or disable client statement caching.
Run Prefilled Sizing Math & Download the 1-Page Runbook
Size PostgreSQL 17 shared_buffers + PgBouncer transaction pools and generate a pg_isready systemd watchdog unit.