PgBouncer Production Guide: Connection Pooling for Django, FastAPI, Node.js, and Java

Backend•

It's 2:00 AM on a Thursday. Your monitoring dashboard lights up red. The API is returning 500 errors across the board. You SSH into the server, check the logs, and there it is — the one PostgreSQL error message that has ruined more weekends than any syntax bug ever could:

FATAL: sorry, too many clients already

Your app didn't crash because of a bug. It crashed because too many things tried to talk to your database at the same time, and PostgreSQL said "I can't handle this many conversations."

PgBouncer fixes this problem. And by the end of this guide, you'll understand exactly why it's needed, how it works, and how to wire it up to Django, FastAPI, Node.js, or Java Spring Boot — with copy-paste configs that work out of the box.

So grab a coffee (or tea, I don't judge), and let's make sure this error never wakes you up again.

What you'll learn:

  • What connection pooling is, explained with a simple analogy anyone can follow.
  • Why PostgreSQL crashes under too many connections, and what PgBouncer does about it.
  • The difference between session, transaction, and statement pooling — in plain English.
  • How to install and configure PgBouncer step by step.
  • Copy-paste connection configs for Django, FastAPI, Node.js, and Java Spring Boot.
  • The common traps that break your app the first time you use PgBouncer — and how to dodge every one of them.
  • How to monitor PgBouncer and perform zero-downtime maintenance.

Set Your Variables

Enter your database and PgBouncer details below. Every code block in this article updates instantly to reflect your values, making every config ready to copy and paste directly into your project.

Interactive Variables

Enter your values below — every code block in this article updates instantly.


1. What Is PgBouncer? (The Restaurant Analogy)

Before we touch any code, let's understand the problem PgBouncer solves — with a simple analogy.

Imagine a restaurant with 10 chefs

Your PostgreSQL database is the kitchen. The chefs inside are the database connections — the actual workers that cook (execute) your SQL queries.

Without PgBouncer, your restaurant has a terrible policy: every single customer who walks through the front door gets their own personal chef. If 10 customers arrive, 10 chefs are assigned. So far, so good.

But here's the problem: most of the time, those chefs are just standing around doing nothing. The customer is browsing the menu, chewing their food, scrolling their phone, or chatting with friends. The chef is idle, but no one else can use them.

Without PgBouncer: One Chef Per Customer

Customer 1  ───>  Chef 1  (Cooking: 2 seconds)
Customer 2  ───>  Chef 2  (Idle: Customer is reading the menu...)
Customer 3  ───>  Chef 3  (Idle: Customer is on the phone...)
Customer 4  ───>  Chef 4  (Idle: Customer is chewing...)
...
Customer 200 ───>  ??? (No chefs left! Kitchen explodes!)

Now imagine it's Friday night. 200 customers flood in. You'd need 200 chefs, each with their own counter space, ingredients, and stove burner. The kitchen runs out of space, chefs bump into each other, and the whole restaurant grinds to a halt.

That's exactly what happens to PostgreSQL. Each "chef" is an operating system process that costs 5–10 MB of RAM. At 200 connections, your database server is spending more energy juggling chefs than actually cooking food.

PgBouncer is the smart host at the front door

Now you hire a sharp, efficient host who stands at the entrance. This host is PgBouncer.

300 customers can sit in the dining room (your application workers), and they all feel like they have an open line to the kitchen. But the host knows there are only 25 chefs, and most orders take just a few seconds to cook.

When Customer #1 needs their query cooked (SELECT * FROM users), the host instantly assigns an available chef. The chef executes the query in 2 milliseconds. The moment the food is served (the SQL transaction finishes), the host immediately hands that same chef to Customer #2. While Customer #1 is busy in their Python/Node/Java code processing the data, the chef is already cooking for someone else.

With PgBouncer: Smart Host Sharing 25 Chefs

300 App Workers                    PgBouncer                    PostgreSQL
(Customers at tables)             (The Host)                   (The Kitchen)

[ Django Workers   ] ──┐
[ FastAPI Workers  ] ──┤
[ Node.js Workers  ] ──┼──> [ PgBouncer (:$PGBOUNCER_PORT) ] ──> [ 25 Chefs ]
[ Java Service     ] ──┘       (Routes orders smartly)         (:$POSTGRES_PORT)

300 application connections become just $DEFAULT_POOL_SIZE real PostgreSQL connections. The database is calm. Memory usage is flat. And your applications don't notice the difference — they just connect to PgBouncer on port $PGBOUNCER_PORT instead of PostgreSQL on port $POSTGRES_PORT. That's the only change.

How lightweight is PgBouncer? Each connection in PgBouncer uses about 2 KB of memory. Compare that to PostgreSQL's 5–10 MB per connection — that's roughly a 2,500× to 5,000× reduction. A single PgBouncer instance can handle 10,000 client connections on a modest server.


2. Why Can't PostgreSQL Handle This on Its Own?

This is a fair question. If the problem is too many connections, why not just increase PostgreSQL's max_connections setting to 1,000?

The short answer: PostgreSQL wasn't built for that

Unlike MySQL (which uses threads), PostgreSQL creates a brand-new operating system process for every single connection. Each process gets its own chunk of RAM, its own CPU scheduling slot, and its own entry in the kernel's process table.

Here's what that looks like when your application scales:

ScenarioTotal connectionsRAM used (by connections alone)What happens
Small app, 1 server20~100–200 MBFine
Medium app, 3 servers60~300–600 MBStill okay
Growing app, 10 servers200~1–2 GBPerformance starts degrading
Scaled app, 30+ servers600+~3–6 GBLock contention, CPU thrashing, random timeouts

The official PostgreSQL documentation warns that performance degrades sharply beyond 200–300 connections. It's not just about RAM — the CPU spends more and more time switching between processes instead of actually running your queries. It's like having 300 chefs in a kitchen built for 25: they spend all their time bumping into each other instead of cooking.

Key insight: In a typical web application, a database connection is actively executing a query less than 5% of the time. The other 95%, it's sitting idle — consuming memory, holding a slot, doing absolutely nothing. PgBouncer reclaims that wasted 95%.


3. How PgBouncer Actually Works

PgBouncer sits between your application and PostgreSQL like a middleman. Your app connects to PgBouncer (thinking it's the database), and PgBouncer manages a small pool of real PostgreSQL connections behind the scenes.

┌──────────────────────────────────────────────────────────────────┐
│                     The Big Picture                              │
│                                                                  │
│  Your App ────connects to────> PgBouncer ────connects to────> PostgreSQL
│  (Port $PGBOUNCER_PORT)                        (Port $POSTGRES_PORT)
│                                                                  │
│  Your app thinks it's talking directly to the database.          │
│  PgBouncer handles the sharing behind the scenes.                │
└──────────────────────────────────────────────────────────────────┘

The only change you make is updating your database connection string: instead of pointing to PostgreSQL's port ($POSTGRES_PORT), you point to PgBouncer's port ($PGBOUNCER_PORT). That's it. No code changes. No new libraries. No query rewrites.


4. Pooling Modes: How PgBouncer Shares Connections

PgBouncer has three different strategies for sharing database connections. This is controlled by a single setting called pool_mode. Think of it as telling the restaurant host when to reassign a chef to a different customer.

The Three Modes (Simple Explanation)

ModeRestaurant AnalogyIn Database TermsBest For
SessionA chef stays with one customer from the moment they sit down until they leave.A real database connection is assigned when the app connects and released when it disconnects.Legacy apps that need persistent session features.
Transaction ⭐A chef walks over only to cook one course (appetizer, main, dessert), then moves to the next table.A real connection is assigned only during a SQL transaction (BEGIN → COMMIT), then immediately freed for the next client.95% of web apps. This is what you want.
StatementA chef cooks a single plate, drops it off, and walks away instantly. No multi-course meals allowed.A real connection is released after every single SQL statement. Multi-statement transactions are forbidden.Very simple, read-heavy workloads.

Transaction mode gives you the best of both worlds: your app feels like it has a dedicated connection, but PgBouncer is constantly recycling real connections behind the scenes. A backend that finishes a 2-millisecond SELECT is instantly available for the next client.

The important trade-off to understand: In transaction mode, the real PostgreSQL connection your app uses for Query #1 is probably not the same connection it gets for Query #2. They might be totally different database processes. This means certain PostgreSQL features that depend on "staying on the same connection" can break. We'll cover exactly what breaks and how to fix each one in Section 6 (The 5 Production Traps).


5. Step-by-Step: Installing and Configuring PgBouncer

Install PgBouncer

On Ubuntu/Debian:

sudo apt update
sudo apt install pgbouncer -y

Verify it installed correctly:

pgbouncer --version

Configure PgBouncer

The main configuration file lives at /etc/pgbouncer/pgbouncer.ini. Open it:

sudo nano /etc/pgbouncer/pgbouncer.ini

Here's a production-ready config. Every setting is commented so you know exactly what it does:

;; /etc/pgbouncer/pgbouncer.ini

;; ═══════════════════════════════════════════════════
;; SECTION 1: Which databases does PgBouncer manage?
;; ═══════════════════════════════════════════════════
[databases]
;; When your app connects asking for "$DB_NAME",
;; PgBouncer forwards the query to PostgreSQL at $POSTGRES_HOST:$POSTGRES_PORT
$DB_NAME = host=$POSTGRES_HOST port=$POSTGRES_PORT dbname=$DB_NAME

;; ═══════════════════════════════════════════════════
;; SECTION 2: PgBouncer's own settings
;; ═══════════════════════════════════════════════════
[pgbouncer]

;; --- Where PgBouncer listens for incoming connections ---
listen_addr = $PGBOUNCER_HOST
listen_port = $PGBOUNCER_PORT

;; --- How clients authenticate ---
;; md5 is widely compatible; scram-sha-256 is stronger (needs PgBouncer 1.14+)
auth_type = md5
auth_file = /etc/pgbouncer/userlist.txt

;; --- The pooling strategy (see Section 4 above) ---
pool_mode = $POOL_MODE

;; --- Connection limits ---

;; How many TOTAL app connections can PgBouncer accept?
;; Think of this as "how many customers can sit in the dining room"
max_client_conn = $MAX_CLIENT_CONN

;; How many REAL PostgreSQL connections does PgBouncer maintain?
;; Think of this as "how many chefs are in the kitchen"
;; This is per user/database pair
default_pool_size = $DEFAULT_POOL_SIZE

;; Keep at least this many real connections warm (avoids startup delay)
min_pool_size = 5

;; Emergency extra connections if the pool is temporarily full
reserve_pool_size = 5
reserve_pool_timeout = 5

;; --- Connection hygiene (VERY IMPORTANT) ---

;; After each transaction, reset the connection to a clean state.
;; Without this, settings from one app can leak to another app.
;; This is the single most important line in this file.
server_reset_query = DISCARD ALL

;; Quick health check: "is this connection still alive?"
server_check_query = SELECT 1
server_check_delay = 30

;; --- Timeouts ---

;; How long an app waits for a database connection (seconds)
query_wait_timeout = 120

;; Close idle real connections after 10 minutes
server_idle_timeout = 600

;; --- Logging ---
log_connections = 0
log_disconnections = 0
log_pooler_errors = 1
stats_period = 60

;; --- Admin access ---
admin_users = $DB_USER

The single most important line: server_reset_query = DISCARD ALL. Here's why: in transaction mode, PgBouncer hands the same real database connection to different apps one after another. If App A ran SET timezone TO 'Asia/Kathmandu', that setting would silently carry over to App B, C, and D — causing bizarre, unreproducible bugs. DISCARD ALL wipes the slate clean between every use.

Set Up Authentication

PgBouncer needs to know your database users' credentials. The simplest way is a password file:

sudo nano /etc/pgbouncer/userlist.txt
"$DB_USER" "md5_hashed_password_here"

To generate the MD5 hash, run this inside psql (PostgreSQL's command-line tool):

SELECT 'md5' || md5('$DB_PASSWORD' || '$DB_USER');

Copy the output (it looks like md5abc123def456...) and paste it as the password in userlist.txt.

A Better Way: Dynamic Password Lookup (No Flat File)

Maintaining a password file on every server gets annoying fast. A better approach is to let PgBouncer ask PostgreSQL directly: "Hey, is this password correct?" Add this to your pgbouncer.ini:

;; Dynamic authentication — PgBouncer queries PostgreSQL for passwords
auth_type = md5
auth_user = pgbouncer_auth_user
auth_query = SELECT usename, passwd FROM pg_shadow WHERE usename=$1

Then create the lookup user in PostgreSQL:

CREATE ROLE pgbouncer_auth_user LOGIN PASSWORD 'auth_lookup_password';
GRANT SELECT ON pg_shadow TO pgbouncer_auth_user;

You still need a minimal userlist.txt with just this one user:

"pgbouncer_auth_user" "md5_hash_of_auth_lookup_password"

Now PgBouncer uses pgbouncer_auth_user to look up everyone else's passwords automatically. No more syncing files across servers.

Start PgBouncer

sudo systemctl enable pgbouncer
sudo systemctl start pgbouncer

# Verify it's listening on the right port
sudo ss -tlnp | grep $PGBOUNCER_PORT

That's it — PgBouncer is running. Now let's connect your application to it.


6. Connecting Your Application (The Fun Part)

This is where most tutorials end and most production bugs begin. Every framework has specific quirks when working with PgBouncer. Here are battle-tested configs for each one.

The core idea is always the same: change your database port from $POSTGRES_PORT to $PGBOUNCER_PORT, and disable any features that depend on "staying on the same database connection."

A. Django

Django is the most straightforward. Update your settings.py:

# settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '$DB_NAME',
        'USER': '$DB_USER',
        'PASSWORD': '$DB_PASSWORD',
        'HOST': '$PGBOUNCER_HOST',       # Point to PgBouncer
        'PORT': '$PGBOUNCER_PORT',       # PgBouncer port, NOT $POSTGRES_PORT
        'CONN_MAX_AGE': 0,               # Don't hold connections between requests
        'DISABLE_SERVER_SIDE_CURSORS': True,  # Required for PgBouncer
    },
}

Two settings that matter — here's why:

DISABLE_SERVER_SIDE_CURSORS = True — When Django processes large querysets with .iterator(), it normally creates a "cursor" object inside PostgreSQL. That cursor lives on a specific database process. In transaction mode, PgBouncer might hand your next query to a different process that knows nothing about that cursor. Result: cursor "..." does not exist. Setting this to True tells Django to fetch results to the app's memory instead, which works perfectly with PgBouncer.

CONN_MAX_AGE = 0 — This tells Django to close its database connection after every request. With PgBouncer, this is fine because PgBouncer manages the real persistent connections to PostgreSQL. Django just borrows one briefly. If you have extremely high traffic (thousands of requests/second), you can set this to 600 to save TCP handshake time — PgBouncer handles it either way.

Migrations: The One Exception

Database migrations (python manage.py migrate) create and alter tables. These operations need to stay on a single, stable connection — which is exactly what transaction mode doesn't guarantee. The fix is simple: set up a second database entry that connects directly to PostgreSQL:

# settings.py — Add a direct connection for migrations

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '$DB_NAME',
        'USER': '$DB_USER',
        'PASSWORD': '$DB_PASSWORD',
        'HOST': '$PGBOUNCER_HOST',
        'PORT': '$PGBOUNCER_PORT',
        'CONN_MAX_AGE': 0,
        'DISABLE_SERVER_SIDE_CURSORS': True,
    },
    'direct': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': '$DB_NAME',
        'USER': '$DB_USER',
        'PASSWORD': '$DB_PASSWORD',
        'HOST': '$POSTGRES_HOST',        # Directly to PostgreSQL
        'PORT': '$POSTGRES_PORT',        # PostgreSQL's port, not PgBouncer's
    },
}

Then run migrations like this:

# Normal app traffic goes through PgBouncer (port $PGBOUNCER_PORT) automatically.
# Migrations go directly to PostgreSQL (port $POSTGRES_PORT):
python manage.py migrate --database=direct

B. FastAPI (Python Async)

FastAPI typically uses asyncpg (a fast async PostgreSQL driver) with SQLAlchemy. Two things will break if you don't handle them:

  1. asyncpg caches prepared statements — it remembers frequently-used queries to speed them up. But those cached statements live on a specific database process. With PgBouncer swapping processes between transactions, the cache points to processes that have no idea about those statements. Boom: prepared statement "..." does not exist.

  2. Double pooling — SQLAlchemy has its own built-in connection pool. If you put that on top of PgBouncer's pool, you get two layers of pooling fighting each other: SQLAlchemy holds connections to PgBouncer "open" for reuse, while PgBouncer might close the underlying PostgreSQL connection for being idle. This causes random timeouts and stale connections.

Here's the config that handles both:

# database.py — FastAPI + SQLAlchemy async + PgBouncer

from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.pool import NullPool

DATABASE_URL = (
    "postgresql+asyncpg://$DB_USER:$DB_PASSWORD"
    "@$PGBOUNCER_HOST:$PGBOUNCER_PORT/$DB_NAME"
)

engine = create_async_engine(
    DATABASE_URL,

    # NullPool = "Don't pool connections inside SQLAlchemy."
    # Let PgBouncer handle ALL the pooling. Two pools = trouble.
    poolclass=NullPool,

    connect_args={
        # Disable asyncpg's prepared statement cache.
        # Without this, you'll get:
        #   ERROR: prepared statement "..." does not exist
        "statement_cache_size": 0,
        "prepared_statement_cache_size": 0,
    },
)

async_session = async_sessionmaker(engine, expire_on_commit=False)


# Dependency for FastAPI routes
async def get_db():
    async with async_session() as session:
        try:
            yield session
        finally:
            await session.close()

Using it in a route:

# routes.py

from fastapi import FastAPI, Depends
from sqlalchemy import text
from database import get_db

app = FastAPI()

@app.get("/users/{user_id}")
async def get_user(user_id: int, db=Depends(get_db)):
    result = await db.execute(
        text("SELECT id, name, email FROM users WHERE id = :id"),
        {"id": user_id},
    )
    user = result.mappings().first()
    return user

In plain English: NullPool says "don't keep any spare connections lying around inside SQLAlchemy — just open one when needed and close it when done." This is safe because PgBouncer is already keeping spare connections to PostgreSQL. You only need one layer of pooling, not two.


C. Node.js

The pg library (node-postgres) is the most popular PostgreSQL driver for Node.js. By default, it uses something called the "extended query protocol," which creates hidden prepared statements behind the scenes. In PgBouncer's transaction mode, this breaks because those prepared statements are tied to a specific database process — and PgBouncer keeps swapping processes.

// db.js — Node.js + node-postgres + PgBouncer

const { Pool } = require('pg');

const pool = new Pool({
  host: '$PGBOUNCER_HOST',
  port: $PGBOUNCER_PORT,          // PgBouncer port
  user: '$DB_USER',
  password: '$DB_PASSWORD',
  database: '$DB_NAME',

  // Keep this small — PgBouncer handles the heavy pooling
  max: 10,

  // How long to wait for a connection (milliseconds)
  connectionTimeoutMillis: 5000,

  // Release idle connections after 30 seconds
  idleTimeoutMillis: 30000,

  // Query timeout (milliseconds)
  statement_timeout: 30000,
});

module.exports = { pool };

Using it in an Express route:

// routes/users.js

const { pool } = require('../db');

app.get('/users/:id', async (req, res) => {
  const { rows } = await pool.query(
    'SELECT id, name, email FROM users WHERE id = $1',
    [req.params.id]
  );
  res.json(rows[0]);
});

If you use Prisma (Node.js / TypeScript ORM)

Prisma has built-in PgBouncer support. You just need two database URLs: one that goes through PgBouncer (for your app) and one that goes directly to PostgreSQL (for migrations):

# .env

# App queries go through PgBouncer — the ?pgbouncer=true flag
# automatically disables prepared statements
DATABASE_URL="postgresql://$DB_USER:$DB_PASSWORD@$PGBOUNCER_HOST:$PGBOUNCER_PORT/$DB_NAME?pgbouncer=true"

# Migrations go directly to PostgreSQL (bypassing PgBouncer)
DIRECT_URL="postgresql://$DB_USER:$DB_PASSWORD@$POSTGRES_HOST:$POSTGRES_PORT/$DB_NAME"
// schema.prisma

datasource db {
  provider  = "postgresql"
  url       = env("DATABASE_URL")
  directUrl = env("DIRECT_URL")
}

The ?pgbouncer=true flag tells Prisma to handle everything automatically — no extra config needed.


D. Java / Spring Boot

Spring Boot uses HikariCP as its default connection pool. Just like SQLAlchemy in Python, this means you now have two pools: HikariCP inside your Java app, and PgBouncer in front of PostgreSQL. The strategy: keep HikariCP small and disable the JDBC driver's automatic prepared statement promotion.

# application.properties

# Point to PgBouncer, NOT directly to PostgreSQL
# The ?prepareThreshold=0 disables automatic prepared statement caching
spring.datasource.url=jdbc:postgresql://$PGBOUNCER_HOST:$PGBOUNCER_PORT/$DB_NAME?prepareThreshold=0
spring.datasource.username=$DB_USER
spring.datasource.password=$DB_PASSWORD

# Keep HikariCP's local pool small — PgBouncer handles the global pooling
spring.datasource.hikari.maximum-pool-size=10
spring.datasource.hikari.minimum-idle=2
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.max-lifetime=600000
spring.datasource.hikari.connection-timeout=5000

What is ?prepareThreshold=0? The PostgreSQL JDBC driver is clever: after you run the same query 5 times, it automatically converts it into a "prepared statement" (a pre-compiled query plan stored on the database server for speed). The problem? That prepared statement lives on one specific database process. If PgBouncer hands your next query to a different process, it has no idea that statement exists. Setting prepareThreshold=0 tells the driver: "Never do that. Always send the full query text."

If you prefer YAML:

# application.yml

spring:
  datasource:
    url: jdbc:postgresql://$PGBOUNCER_HOST:$PGBOUNCER_PORT/$DB_NAME?prepareThreshold=0
    username: $DB_USER
    password: $DB_PASSWORD
    hikari:
      maximum-pool-size: 10
      minimum-idle: 2
      idle-timeout: 30000
      max-lifetime: 600000
      connection-timeout: 5000

Migrations (Flyway / Liquibase)

Same pattern as every other framework — migrations go directly to PostgreSQL:

# Flyway connects directly — bypasses PgBouncer
spring.flyway.url=jdbc:postgresql://$POSTGRES_HOST:$POSTGRES_PORT/$DB_NAME
spring.flyway.user=$DB_USER
spring.flyway.password=$DB_PASSWORD

7. The 5 Traps That Break Everyone Once

You've got PgBouncer installed, your app is connected, and everything works in development. Then you deploy to production and something weird happens. These are the five traps that catch every team exactly once. After reading this section, they won't catch you.

Trap 1: The Prepared Statement Error

What you see:

ERROR: prepared statement "..." already exists
ERROR: prepared statement "..." does not exist

Why it happens (simple version): A "prepared statement" is like a recipe card that your app gives to a specific chef (database process). The chef memorizes it for speed. But with PgBouncer in transaction mode, the next query might go to a different chef who has never seen that recipe card. Either the new chef says "I don't know that recipe" or the original chef says "I already have a recipe with that name."

How to fix it (per framework):

  • Django: Usually not affected — Django's default driver doesn't use named prepared statements.
  • FastAPI (asyncpg): Set statement_cache_size=0 (we did this in our config above).
  • Node.js: Avoid named prepared statements, or use Prisma's ?pgbouncer=true flag.
  • Java (JDBC): Add ?prepareThreshold=0 to the connection URL (we did this too).
  • PgBouncer 1.21+: You can also set max_prepared_statements = 1000 in pgbouncer.ini to let PgBouncer manage this transparently.

Trap 2: Settings From One App Leaking to Another

What you see: Queries return data from the wrong schema, timestamps are in the wrong timezone, or one user's settings mysteriously affect another user.

Why it happens: Imagine App A runs SET timezone TO 'Asia/Kathmandu' to show times in Nepal's timezone. The transaction ends. PgBouncer hands that same database connection (with Kathmandu timezone still set) to App B, which expected UTC. App B now shows all timestamps in the wrong timezone — and has no idea why.

How to fix it: The server_reset_query = DISCARD ALL setting in pgbouncer.ini wipes all these settings clean between every use. That's why we included it in our config above, and why it's the most important line in the file. If you need per-user defaults, set them permanently in PostgreSQL:

-- These settings apply automatically, no matter which connection is assigned
ALTER ROLE $DB_USER SET search_path TO public, my_schema;
ALTER ROLE $DB_USER SET timezone TO 'UTC';

Trap 3: Migrations That Hang or Crash

What you see: python manage.py migrate hangs forever, or migrations fail with lock errors.

Why it happens: Migrations create and alter tables — operations that need to stay on one stable database connection from start to finish. In transaction mode, PgBouncer might route different parts of a migration to different database processes. One process acquires a lock, another process tries to use it and fails because it's on a completely different connection.

How to fix it: Always run migrations directly against PostgreSQL, bypassing PgBouncer entirely:

  • Django: python manage.py migrate --database=direct
  • Prisma: Uses directUrl automatically (we configured this above)
  • Java (Flyway/Liquibase): Use a separate spring.flyway.url pointing to port $POSTGRES_PORT
  • Node.js (Knex/TypeORM): Set MIGRATION_DATABASE_URL pointing to port $POSTGRES_PORT

Trap 4: Real-Time Features (LISTEN/NOTIFY) Don't Work

What you see: Your real-time notification system (LISTEN/NOTIFY) stops receiving events, or distributed locks (pg_advisory_lock) don't actually prevent concurrent access.

Why it happens: These features are tied to a specific database connection for their entire lifetime. LISTEN says "notify me on this connection when something happens." But in transaction mode, PgBouncer swaps connections between transactions, so the notification arrives on Connection A while your app is now talking to Connection B.

How to fix it: Create a separate database entry in pgbouncer.ini that uses session mode (one connection per client) specifically for real-time features:

[databases]
;; Normal app traffic: transaction pooling (fast, shared)
$DB_NAME = host=$POSTGRES_HOST port=$POSTGRES_PORT dbname=$DB_NAME pool_mode=$POOL_MODE

;; Real-time listener: session pooling (dedicated connection)
${DB_NAME}_realtime = host=$POSTGRES_HOST port=$POSTGRES_PORT dbname=$DB_NAME pool_mode=session

Your app uses $DB_NAME for normal queries and ${DB_NAME}_realtime for LISTEN/NOTIFY.

Trap 5: Random, Unreproducible Bugs

What you see: Bizarre bugs that happen randomly and disappear when you try to reproduce them. One user sees another user's temporary table data. A setting changes for no apparent reason.

Why it happens: If server_reset_query = DISCARD ALL is missing or commented out, PgBouncer returns connections to the pool without cleaning them. The next app that gets that connection inherits whatever mess the previous app left behind.

How to fix it: Never remove server_reset_query = DISCARD ALL from your config. The tiny overhead (one extra database round-trip per transaction) is absolutely worth it to eliminate this entire category of ghost bugs.


8. Monitoring PgBouncer

PgBouncer has a built-in admin console. You connect to it with psql just like you would a regular database, but instead of querying tables, you run special SHOW commands to see what's happening inside the pool.

Connect to the Admin Console

psql -h $PGBOUNCER_HOST -p $PGBOUNCER_PORT -U $DB_USER pgbouncer

The Commands You'll Use Most

See Pool Utilization

SHOW POOLS;
 database  |   user   | cl_active | cl_waiting | sv_active | sv_idle | pool_mode
-----------+----------+-----------+------------+-----------+---------+------------
 $DB_NAME  | $DB_USER |        12 |          0 |         3 |      22 | transaction

Here's what those columns mean:

ColumnWhat It MeansWhat to Watch For
cl_activeApp connections currently running a queryNormal traffic indicator
cl_waitingApp connections waiting for a database connection⚠️ If this is consistently > 0, increase default_pool_size
sv_activeReal PostgreSQL connections currently in useShows actual database load
sv_idleReal PostgreSQL connections sitting in the pool, readyAvailable capacity

See Throughput Stats

SHOW STATS;

Shows total queries processed, bytes sent/received, and average query duration per database.

See All Connected Clients

SHOW CLIENTS;

See All Backend Connections

SHOW SERVERS;

Zero-Downtime Maintenance

Need to restart PostgreSQL for a patch or vacuum? PgBouncer can hold all incoming traffic while you do it:

-- Reload PgBouncer's config without dropping any connections
RELOAD;

-- Pause: waits for active transactions to finish, then queues everything
PAUSE $DB_NAME;

-- Do your PostgreSQL maintenance here...

-- Resume: releases the queue, everything flows again
RESUME $DB_NAME;

Your applications don't see a single error. They just experience a brief pause.


9. How Big Should the Pool Be?

A common mistake is setting default_pool_size too high, thinking more connections = more performance. It's actually the opposite.

The Starting Formula

default_pool_size = (2 × CPU cores of your database server) + 1
Database ServerCPU CoresRecommended default_pool_size
Small cloud instance2 vCPUs5
Medium cloud instance4 vCPUs9–10
Large cloud instance8 vCPUs17–20
Dedicated server16 cores30–35

Why smaller is often faster: With fewer concurrent database processes, PostgreSQL spends less time on context switching and lock contention, and more time actually executing queries. It's like a kitchen: 10 focused chefs cook faster than 100 chefs tripping over each other.

Start small. Then watch cl_waiting in SHOW POOLS. If apps are consistently waiting for connections, bump the pool size up by 5 and test again.

Set max_client_conn high (1,000–10,000). This is how many app connections PgBouncer accepts — it queues them efficiently in memory, so there's no cost.


10. Production Checklist

Before going live with PgBouncer, run through this list:

  • PgBouncer config: pool_mode = transaction set
  • PgBouncer config: server_reset_query = DISCARD ALL set (non-negotiable)
  • PgBouncer config: default_pool_size tuned with the formula above
  • PgBouncer config: max_client_conn high enough for all your app instances
  • PgBouncer config: Authentication set up (auth_query preferred over flat file)
  • Django: DISABLE_SERVER_SIDE_CURSORS = True and CONN_MAX_AGE = 0
  • FastAPI: statement_cache_size = 0 and poolclass = NullPool
  • Node.js: Prepared statements disabled (or Prisma ?pgbouncer=true)
  • Java: ?prepareThreshold=0 in the JDBC URL
  • All frameworks: Migrations run directly against PostgreSQL (port $POSTGRES_PORT), not through PgBouncer (port $PGBOUNCER_PORT)
  • Monitoring: SHOW POOLS confirms cl_waiting = 0 under normal load
  • System: PgBouncer enabled as a service (systemctl enable pgbouncer)

That's PgBouncer from zero to production. One lightweight proxy, a few lines of framework-specific config, and your PostgreSQL instance goes from drowning in hundreds of forked processes to calmly serving a handful of real connections while thousands of application workers share the pool.

The pattern is always the same, regardless of language: point your app at port $PGBOUNCER_PORT instead of $POSTGRES_PORT, disable whatever prepared statement or session feature your driver uses by default, and run migrations directly against PostgreSQL. The database does less work. The application doesn't notice the difference. And your 2 AM self will thank you.

Applaud this article if you found it useful (up to 50 times)

Discussion

0

Leave a comment

Got a question or feedback? Join the conversation below.