PostgreSQL Too Many Connections: Docker PgBouncer Test

21 min readBy Yun Sanghun (M. Yun)

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 = 500 on a memory-constrained server. Every PostgreSQL connection forks a dedicated backend OS process that can allocate multiple work_mem (4 MB default) sort buffers and work_mem × hash_mem_multiplier (8 MB default) hash tables when queries are active. Instead, keep PostgreSQL port 5432 internal to your Docker bridge network and place PgBouncer in front of it on port 6432 with pool_mode = transaction and default_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 just 81.5 MiB on PostgreSQL and 3.297 MiB on 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:

PostgreSQL 16.6 container with max_connections=5 rejecting the sixth concurrent psql client with FATAL sorry too many clients already
Reproducing hard connection exhaustion on postgres:16-alpine (gfl-pg) with max_connections=5: launching six concurrent psql -U postgres -tAc "select pg_sleep for 5s" workers saturates all five backend slots and rejects the sixth client with FATAL: sorry, too many clients already on both stdout and docker logs.

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:

Side-by-side shell scripts reproducing max_connections=5 exhaustion as superuser versus non-superuser role app hitting superuser_reserved_connections=3
Exact shell scripts used to reproduce both connection limit errors on postgres:16-alpine (max_connections=5): repro_max5_too_many_clients.sh (left) exhausts all five slots as the postgres superuser, while /lab/pg_reserved.sh (right) tests non-superuser role app against superuser_reserved_connections=3.

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:

Terminal output of /lab/pg_reserved.sh showing app|2 and postgres|1 while the third connection as role app fails with FATAL remaining connection slots are reserved for roles with the SUPERUSER attribute
Running /lab/pg_reserved.sh on PostgreSQL 16.6 with max_connections=5 and superuser_reserved_connections=3: non-superuser role app is capped at two concurrent sessions (app|2) and fails on the third attempt with FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute, while the postgres superuser (postgres|1) can still log in.

What this means in practice:

  • Non-superuser application roles hit the wall earlier than max_connections: Because app is not a superuser (rolsuper = false), it could only open 2 sessions (app|2 in the output above, which equals max_connections minus superuser_reserved_connections and reserved_connections). The third app connection failed immediately, even though only two of the five total server slots were occupied by app and 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, where reserved_connections also exists, the server prints FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute (as seen in the postgres:16-alpine log above).
  • Running your application as postgres destroys your emergency recovery path: If your application connects as a superuser (for example, using the default postgres user in a Docker Compose file), it will consume the reserved slots too and fail later with FATAL: sorry, too many clients already, leaving zero slots for you to log in and recover the database.
Split terminal comparison contrasting non-superuser role app capped at 2 of 5 slots versus superuser role postgres consuming all 5 of 5 slots and locking out DBA login
Contrasting non-superuser versus superuser application connections on max_connections=5 (superuser_reserved_connections=3): connecting as role app hits the reserved-slot wall on the 3rd connection but preserves 3 slots for emergency admin access (left), whereas connecting as superuser postgres consumes all 5 slots and locks out administrative recovery until clients disconnect (right).

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):

Matplotlib two-panel chart showing PostgreSQL connection slot partitioning for max_connections=5 and max_connections=100 across non-superuser, superuser, and PgBouncer pools
PostgreSQL connection slot partitioning for max_connections=5 (left) and default max_connections=100 (right): superuser_reserved_connections=3 caps ordinary application roles at 2 slots (on max=5) or 97 slots (on max=100), whereas routing 110 clients through a 20-connection PgBouncer transaction pool uses only 20 backend slots and leaves 80 slots free with zero client rejections.

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:

Raw benchmark output from a 2 GiB PostgreSQL 17.2 container comparing 110 direct clients, 110 clients through PgBouncer 1.23.1, and 450 sleeping clients at max_connections=500
Selected raw log output from our 2 GiB memory-capped PostgreSQL 17.2 container runs: 110 direct clients resulted in 100 succeeded and 10 failed (54.78 MiB RAM); routing the same 110 clients through PgBouncer 1.23.1 (pool_mode=transaction, default_pool_size=20) resulted in 110 succeeded and 0 failed (cl_active=20, cl_waiting=90, sv_active=20, 81.5 MiB + 3.297 MiB RAM); and 450 sleeping clients at max_connections=500 consumed 739.5 MiB across 451 backends with OOMKilled=false.

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 count pg_stat_activity from outside failed with the same error because all 100 slots were already full. After the burst finished, container memory usage on gfl-pg was 54.78 MiB / 2 GiB.
  • Run B: Through PgBouncer (110 clients at once): Using PgBouncer 1.23.1 from Alpine's package configured with pool_mode = transaction, default_pool_size = 20, and max_client_conn = 200, all 110 clients succeeded and 0 failed. At 5 seconds into the burst, SHOW POOLS reported cl_active = 20, cl_waiting = 90, and sv_active = 20, while PostgreSQL had only 21 client backends (the 20 pooled server connections plus the probe query itself). Ninety waiting clients received NOTICE: No server connection available in postgres backend, client being queued and completed as earlier 15-second queries finished, taking 90 seconds total (5.5 waves × 15s). Memory usage was 81.5 MiB / 2 GiB for PostgreSQL and 3.297 MiB for PgBouncer.
Live PgBouncer SHOW POOLS and PostgreSQL pg_stat_activity telemetry dashboard showing cl_active=20, cl_waiting=90, sv_active=20, and 84.8 MiB combined RAM
Live PgBouncer and PostgreSQL pool telemetry web inspector connected to port 6432 and port 5432 during the 110-client burst: SHOW POOLS reports cl_active=20, cl_waiting=90, and sv_active=20 in transaction mode while PostgreSQL maintains just 21 backend processes at 81.5 MiB RSS alongside PgBouncer at 3.297 MiB.
  • Run C: max_connections=500 in a fresh 2 GB container (450 sleeping clients): Before launching clients, the idle PostgreSQL 17.2 container used 46.65 MiB / 2 GiB. With 450 clients connected at once and running SELECT pg_sleep for 40s, PostgreSQL reached 451 client backends at 20 seconds, and container memory usage climbed to 739.5 MiB / 2 GiB (cpu=0.03%) with OOMKilled=false and running=true. These clients were sleeping, not working. I did not test busy queries, a large work_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:

Editor view of postgresql.conf connection and work_mem parameters alongside the 2 GiB container benchmark script run_2gb_110_450_bench.sh
Inspecting postgresql.conf memory parameters (left) alongside our 2 GiB container benchmark script run_2gb_110_450_bench.sh (right): while 450 sleeping backends at max_connections=500 consume 739.5 MiB without triggering OOMKilled, each active sort operation can allocate up to work_mem (4 MB) and each hash operation up to work_mem × hash_mem_multiplier (8 MB) 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:

Split terminal diagnostic comparing Alpine Linux pgbouncer -u pgbouncer startup failure id unknown user pgbouncer against clean startup with pgbouncer -u nobody on port 6432
Reproducing and fixing the Alpine Linux PgBouncer startup failure from our first benchmark run: Alpine's pgbouncer package does not create a pgbouncer system user (id: unknown user pgbouncer), causing -u pgbouncer to exit immediately (left), whereas passing pgbouncer -u nobody drops privileges cleanly and binds port 6432 (right).

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:

Matplotlib two-panel chart comparing measured container RAM across 110 direct, 110 PgBouncer, and 450 sleeping clients alongside active work_mem OOM scaling
Measured container RAM and client failure counts across our 2 GiB Docker runs (left) and active query memory scaling against the 2,048 MiB container ceiling (right): PgBouncer serves all 110 clients in 84.8 MiB total (81.5 MiB PostgreSQL + 3.297 MiB PgBouncer) with zero rejections, whereas 450 sleeping backends at max_connections=500 consume 739.5 MiB before allocating a single 4 MB work_mem sort or 8 MB hash table.

Three architectural factors explain why direct PostgreSQL connections carry this footprint:

  1. The postmaster forks 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 port 5432, the supervisor process forks a separate postgres backend process with its own private address space, catalog caches, and lock-table state.
  2. work_mem and hash_mem_multiplier apply per operation, per backend: While shared_buffers is allocated once for the entire PostgreSQL instance, work_mem (default 4 MB) limits each individual sort or merge node, and work_mem × hash_mem_multiplier (default 2.0, so 8 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 allocate 1,200 MB of private memory.
  3. 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:

Architectural comparison card contrasting PostgreSQL process-per-connection backend memory against PgBouncer single-process event loop
Comparing PostgreSQL's process-per-connection architecture against PgBouncer's event-driven connection multiplexer: while 451 sleeping PostgreSQL backend processes consume 739.5 MiB of RAM (plus up to 4 MB per sort and 8 MB per hash table when active), PgBouncer manages 110 concurrent client sockets inside a single 3.297 MiB daemon process.

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.

Architecture comparison of 400 direct PostgreSQL backend processes causing FATAL 53300 and OOM versus PgBouncer transaction-mode multiplexing onto 25 warm PostgreSQL backends
Connection Multiplexing Topology: Routing 400 concurrent application sockets through PgBouncer (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:

Terminal capture showing 10 concurrent psql clients completing select pg_sleep for 2s with client 1..10 ok through PgBouncer on a max_connections=5 PostgreSQL container
Routing ten concurrent psql clients (select pg_sleep for 2s) through PgBouncer (transaction mode, default_pool_size=3) against the same max_connections=5 PostgreSQL container: instead of failing on the 6th client, PgBouncer queues excess clients in cl_waiting and multiplexes all 10 queries across 3 backend server connections (client 1..10 ok).

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:

n8n v1.76.1 Postgres credential inspector configured to connect via pgbouncer_pool on port 6432 as non-superuser gearflow with live SHOW POOLS verification
Connecting n8nio/n8n:1.76.1 on Docker Desktop to PostgreSQL through PgBouncer on port 6432 (Host: pgbouncer_pool, Port: 6432, Database: production_db, User: gearflow): application workers open connections against the lightweight PgBouncer proxy while PostgreSQL backend usage stays capped at DEFAULT_POOL_SIZE.

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:

Side-by-side configuration editor showing docker-compose.yml with postgres and edoburu/pgbouncer alongside /etc/pgbouncer/pgbouncer.ini with transaction pooling and max_prepared_statements=100
Side-by-side production configuration: docker-compose.yml (left) keeps PostgreSQL port 5432 internal on the Docker bridge and exposes edoburu/pgbouncer on port 6432 (MAX_CLIENT_CONN=200, DEFAULT_POOL_SIZE=12), while /etc/pgbouncer/pgbouncer.ini (right) shows the equivalent native settings used in our Alpine PgBouncer 1.23.1 container including admin_users and 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 = transaction breaks all prepared statements unless you disable them in your client (such as appending ?pgbouncer=true in Prisma). Starting in PgBouncer 1.21.0 (including 1.23.1 tested here), PgBouncer can track and rewrite protocol-level prepared statements (PostgreSQL Extended Query Protocol Parse/Bind messages) in transaction mode when you set max_prepared_statements above 0 (for example, max_prepared_statements = 100). SQL-level PREPARE name AS ... / EXECUTE statements remain unsupported in transaction mode.

Split comparison showing prepared statement collision errors 42P05 and 26000 when max_prepared_statements=0 versus transparent protocol statement tracking with max_prepared_statements=100 on PgBouncer 1.23.1
Testing prepared statement behavior under pool_mode = transaction on PgBouncer 1.23.1: with max_prepared_statements = 0 or SQL-level PREPARE (left), reusing a pooled backend across clients triggers prepared statement collision errors (42P05 / 26000), whereas setting max_prepared_statements = 100 (right) enables PgBouncer 1.21+ protocol-level statement rewriting across shared server connections.

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:

Matplotlib two-panel chart showing the 90-second 110-client wave drain timeline on PgBouncer alongside pooling mode concurrency comparison
Queue drain timeline across the 90-second 110-client PgBouncer run (left) and pooling mode concurrency comparison (right): with default_pool_size=20 and 15-second queries, PgBouncer processes 20 active clients per wave while draining cl_waiting from 90 down to 0 in six waves (5 × 20 + 1 × 10 = 110 clients in 90s) without opening more than 20 PostgreSQL server connections.

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:

Four-tier Docker bridge connection-multiplexing and superuser slot reservation architecture diagram showing 200 clients routing through PgBouncer port 6432 to 12-20 PostgreSQL backends
End-to-end Docker bridge connection-multiplexing architecture: up to 200 application connections terminate at PgBouncer on port 6432 (3.297 MiB RSS, transaction mode, max_prepared_statements=100) and share 12 to 20 persistent server connections to PostgreSQL on internal port 5432, leaving 77 normal slots unallocated and 3 superuser_reserved_connections free for emergency administration.

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:

Actionable six-point production verification and operational checklist card for PostgreSQL and PgBouncer in Docker
Six-point production verification checklist for PostgreSQL and PgBouncer in Docker: exact CLI inspection commands and pass criteria covering reserved superuser slots, non-superuser application roles, internal port 5432 isolation, Alpine daemon privileges, SHOW POOLS transaction multiplexing, and max_prepared_statements = 100.

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), preserving superuser_reserved_connections = 3 for emergency DBA login.
  • ✓ 2. Internal Bridge Isolation Active: PostgreSQL uses expose: ["5432"] while PgBouncer listens on 6432 with pool_mode = transaction and default_pool_size = 12..20.
  • ✓ 3. Prepared Statements & Pool Queue Verified: SHOW CONFIG; confirms max_prepared_statements = 100 and SHOW POOLS; confirms sv_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.

100% Client-Side Utilities · Printable A4 Runbook

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.

Paired Prefilled Calculators & Vector PDF Checklist

Yun Sanghun (M. Yun) · Linux, Docker & AI Infrastructure Engineer