Configuring PgBouncer as a Connection Pooler for PostgreSQL with Docker Compose

Docker tutorial - IT technology blog
Docker tutorial - IT technology blog

The Problem: The Dreaded “FATAL: remaining connection slots are reserved”

Whenever a flash sale or major marketing campaign kicks off, a familiar nightmare unfolds. Dozens of microservices and Celery workers scale out simultaneously, fighting for database connections. Within minutes, Slack alerts blow up. PostgreSQL throws a fatal error: FATAL: remaining connection slots are reserved for non-replication superuser connections. Database CPU hits 100%, RAM is exhausted, and API requests hang indefinitely.

Why does it collapse so quickly? Unlike MySQL, which uses threads, PostgreSQL relies on a process-based architecture. For every new incoming client connection, Linux must fork a dedicated backend process.

Each process consumes at least 5MB to 10MB of RAM at idle, and can easily surge to 30MB–50MB when executing complex queries. Add TLS handshakes and nonstop context switching across hundreds of processes, and PostgreSQL soon burns out managing processes rather than executing queries once connection counts pass 300 to 500.

In a 30-microservice architecture I once optimized, letting services connect directly to the database drove active connections past 600, eating up a massive 12GB of RAM. Once we placed PgBouncer in front, the database only needed to maintain 25 actual backend connections. Memory usage dropped immediately to 2.5GB and stayed rock solid throughout peak traffic.

Core Concept: How Does PgBouncer Work?

PgBouncer is a specialized, lightweight connection pooler written in C. Instead of letting hundreds of workers connect directly and chaotically to Postgres, all clients talk strictly to PgBouncer. PgBouncer acts as a reverse proxy: it maintains a small pool of actual connections to the database and dynamically multiplexes them to client applications.

3 Pooling Modes You Must Understand

  • Session Pooling: PgBouncer assigns a server connection to a client as soon as the client authenticates. This connection is only released back to the pool when the client completely disconnects. This is the safest mode and offers 100% compatibility with all Postgres features, but pooling efficiency is low if applications hold connections open for long periods.
  • Transaction Pooling (Recommended for Web/API): PgBouncer borrows a physical connection only for the duration of a transaction, returning it to the pool immediately upon a COMMIT or ROLLBACK. With this approach, just 20 real database connections can easily serve up to 2,000 API clients. Note: While prepared statements were historically unsupported in this mode, PgBouncer v1.21+ handles them seamlessly. However, session-level constructs like LISTEN/NOTIFY or temporary SET timezone commands are not supported.
  • Statement Pooling: Connections are returned immediately after every single SQL statement. This mode prohibits multi-statement transactions and can easily break application logic, making it rarely suitable for real-world production environments.

Hands-On Guide: Running PgBouncer and PostgreSQL with Docker Compose

Here is a step-by-step setup to spin up PostgreSQL 16 alongside PgBouncer v1.22 using Docker Compose, ready for testing.

Step 1: Set Up Directory Structure

mkdir pgbouncer-demo && cd pgbouncer-demo
mkdir pgbouncer
touch docker-compose.yml pgbouncer/pgbouncer.ini pgbouncer/userlist.txt

Step 2: Configure pgbouncer.ini

Open pgbouncer/pgbouncer.ini and paste the following configuration:

[databases]
app_db = host=postgres port=5432 dbname=app_db auth_user=postgres

[pgbouncer]
logfile = /tmp/pgbouncer.log
pidfile = /tmp/pgbouncer.pid
listen_addr = 0.0.0.0
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
admin_users = postgres
stats_users = postgres
pool_mode = transaction
max_client_conn = 1000
default_pool_size = 20
min_pool_size = 5
reserve_pool_size = 5
reserve_pool_timeout = 5
max_prepared_statements = 100

Key configuration highlights:

  • max_client_conn = 1000: Upper limit allowing up to 1,000 concurrent client connections to PgBouncer.
  • default_pool_size = 20: Limits open backend connections to PostgreSQL to 20 per user/database pair.
  • pool_mode = transaction: Reuses connections immediately after each transaction completes.
  • max_prepared_statements = 100: Enables prepared statement caching on PgBouncer (crucial when using ORMs like Prisma or Hibernate).

Step 3: Create Authentication Credentials (userlist.txt)

PgBouncer requires an authentication file to verify client credentials before granting pool access. Add user entries into pgbouncer/userlist.txt:

"postgres" "postgres_secret_pass"
"app_user" "app_secret_pass"

Step 4: Configure docker-compose.yml

The Compose file connects both services via an internal bridge network. A healthcheck ensures PostgreSQL is fully initialized before PgBouncer attempts to connect:

version: '3.8'

services:
  postgres:
    image: postgres:16-alpine
    container_name: postgres_db
    environment:
      POSTGRES_DB: app_db
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: postgres_secret_pass
    volumes:
      - pgdata:/var/lib/postgresql/data
    networks:
      - backend_net
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres -d app_db"]
      interval: 5s
      timeout: 5s
      retries: 5

  pgbouncer:
    image: edoburu/pgbouncer:v1.22.0
    container_name: pgbouncer_pool
    depends_on:
      postgres:
        condition: service_healthy
    ports:
      - "6432:6432"
    volumes:
      - ./pgbouncer/pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini:ro
      - ./pgbouncer/userlist.txt:/etc/pgbouncer/userlist.txt:ro
    networks:
      - backend_net
    restart: unless-stopped

volumes:
  pgdata:

networks:
  backend_net:
    driver: bridge

Step 5: Launch and Verify

Start the container cluster with the standard command:

docker compose up -d

Verify application connectivity by pointing psql to port 6432 instead of the standard PostgreSQL port 5432:

psql -h localhost -p 6432 -U postgres -d app_db

A successful login confirms the pooler is up and running. Now connect to PgBouncer’s virtual administrative console to inspect live pool metrics:

psql -h localhost -p 6432 -U postgres -d pgbouncer

Run these commands to monitor traffic and connection state:

-- Check the status of connection pools
SHOW POOLS;

-- View details of currently connected clients
SHOW CLIENTS;

-- Check actual open connections to PostgreSQL
SHOW SERVERS;

Summary

Don’t jump straight to upgrading CPU or RAM when your database hits connection bottlenecks. Placing PgBouncer in front of PostgreSQL is straightforward and targets the fundamental bottleneck of Postgres’s process-based design. Keeping backend connections modest (dozens instead of hundreds) frees up CPU resources for actual query processing, empowering your infrastructure to handle significantly higher workloads without additional hardware costs.

Share: