Skip to content

Connection Pooling ​

"Axiom: You want a small pool, saturated with threads waiting for connections." — "About Pool Sizing", HikariCP Wiki (GitHub)

Summary: A database connection is an expensive, scarce resource; pooling lends a small, fixed set of them to many callers, and the right number is far smaller than people expect. Focus: The cost of a PostgreSQL connection, pool sizing (formula, Little's law), Go database/sql and pgxpool knobs, pool exhaustion and leaks, PHP-FPM/Octane/Laravel pooled vs direct, PgBouncer modes and what breaks, other poolers, and fleet-wide budgets. Learning goal: Size every pool from a budget, predict what breaks behind a transaction pooler, and diagnose exhaustion from the numbers instead of raising the limit.

This page is the complete reference for connection pooling in front of PostgreSQL, with MySQL, SQL Server, Oracle, MongoDB and Redis compared where they differ. It covers the process model and why one connection costs real memory and snapshot work, max_connections and per-role limits, the sizing formula and Little's law, the Go pool (database/sql, pgxpool), the PHP side (PHP-FPM, persistent connections, Laravel Octane on Swoole/FrankenPHP/RoadRunner), Laravel 13 pooled and direct connections, PgBouncer's three modes and the exact features each breaks, server_reset_query, prepared statements behind a transaction pooler, the other poolers (pgcat, Odyssey, Supavisor, ProxySQL, RDS Proxy, Pgpool-II), read/write splitting, pooling across many services and replicas, serverless connection storms, health checks and monitoring. It does not re-teach neighbours: the PostgreSQL process model is in PostgreSQL & Database Fundamentals; row and advisory locks are in Locks & Concurrency; why a long open transaction hurts is in MVCC, VACUUM & Bloat; replica routing and lag are in Replication, Read Replicas & Failover; the transaction boundary itself is in ACID & Transactions.

Page map ​

If you are looking forGo to
The numbers to memoriseEverything in one minute
Why pools exist and the trade-offWhy connection pooling exists
What one PostgreSQL connection costsThe cost of a connection
max_connections, reserved slots, CONNECTION LIMITmax_connections and per-role limits
Pool size formula, HikariCP axiom, Little's lawPool sizing
SetMaxOpenConns, SetConnMaxLifetime, pgxpoolApplication pools in Go
Acquire timeouts, exhaustion symptoms, leaksExhaustion and leaks
PHP-FPM, persistent connections, OctanePHP: one connection per worker
pooled vs direct in Laravel 13Laravel 13 pooled and direct
Session, transaction, statement modePgBouncer pooling modes
What breaks in transaction modeWhat breaks
Prepared statements behind a poolerPrepared statements
pgcat, Odyssey, Supavisor, ProxySQL, RDS Proxy, Pgpool-IIThe other poolers
Read/write split, many services, serverlessTopologies
Monitoring and timeoutsMonitoring
Every PgBouncer knob and errorMechanics
Code for the classic problemsSolving the classic problems
Which setup for which workloadChoosing a setup
Monolith to distributedIn architecture
Reproduce exhaustion and the PgBouncer comparisonLab

Everything in one minute ​

The layers. Every layer in the path can pool; each multiplies or divides the connection count.

LayerExampleWhat a "connection" is thereWho pays
Application poolGo *sql.DB, pgxpool.Pool, HikariCP, PDOA socket plus a server backendEach process
External poolerPgBouncer, pgcat, Odyssey, Supavisor, RDS ProxyA cheap client socket in, a shared server connection outOne small service
DatabasePostgreSQL max_connectionsA forked backend processThe server (memory, snapshots)

The numbers.

RuleValueSource of the number
Starting active connections(core_count * 2) + effective_spindle_countPostgreSQL wiki, HikariCP wiki
Average connections in useL = λ × W (Little's law)Queueing theory
Fleet budgetinstances × MaxOpenConns summed over services must fit max_connections minus reservedArithmetic
PgBouncer client costabout 2 kB per connection by defaultPgBouncer features page
PostgreSQL default max_connections100PostgreSQL docs
Go database/sql defaultsMaxOpenConns unlimited, MaxIdleConns 2Go package docs
PgBouncer defaultsdefault_pool_size 20, max_client_conn 100, query_wait_timeout 120 sPgBouncer config

The three PgBouncer modes.

ModeServer connection returns to the poolBreaksTypical use
sessionWhen the client disconnectsNothingLegacy apps, LISTEN, long sessions
transactionWhen the transaction endsSET, LISTEN, PREPARE, session advisory locks, WITH HOLD cursors, PRESERVE ROWS temp tablesWeb apps with short transactions
statementAfter each statementEverything multi-statementPL/Proxy style autocommit only

The three things to do.

SituationDo this
Many small app instancesGive each instance a small pool (5 to 20) and put PgBouncer in transaction mode in front
Latency spikes under loadLook at wait counts first (Go WaitCount, PgBouncer cl_waiting), then at the slow query holding connections
Migrations, LISTEN, pg_dumpUse a direct (session) connection, not the transaction pool

Why connection pooling exists ​

Opening a connection means a TCP handshake, optional TLS, authentication, and on PostgreSQL a fork() of a new backend process. For a query that takes one millisecond, setup can cost many times more than the work. A pool pays that setup once and lends the open connection out again and again.

The deeper reason is the opposite one: the database cannot use unlimited concurrency. Past the point where CPU, disk and locks are saturated, extra concurrent queries do not finish sooner; they only wait on each other and use memory. A pool is a concurrency limiter as much as a cache of connections.

Few connections (small pool)Many connections (big pool)
Queries queue in the application, which is cheapQueries compete inside the database, which is expensive
Each query runs near full speedEach query slows down; total throughput eventually falls
Predictable memoryOne backend per connection, each with caches
Failure mode: callers wait, then time out (visible, bounded)Failure mode: too many clients, CPU saturation, lock pile-ups
Needs deadlines and short transactionsHides slow queries until the server falls over

The everyday picture. A bank with four tellers serves a hundred customers. Nobody owns a teller for the day; a teller serves one transaction and takes the next person. Doubling the tellers in a branch with four desks does not speed anything up; it only makes the room crowded. A transaction pooler works the same way. Asking a teller to keep your file open between visits (SET, LISTEN, session advisory locks) breaks the model, because your next visit may reach a different teller.

Three common misunderstandings, up front ​

  • "More connections means more throughput." Up to saturation, yes; beyond it, throughput flat-lines and then drops while latency grows. The PostgreSQL wiki says PostgreSQL "will usually complete the same 10,000 transactions faster by doing them 5, 10 or 20 at a time than by doing them 500 at a time".
  • "PgBouncer is transparent." Only in session mode. In transaction mode it is transparent to code that keeps no session state, and silently wrong for code that does.
  • "MaxOpenConns = 10 caps my database load." It caps one process. Ten replicas make 100. The budget is a fleet-wide sum.

The cost of a connection ​

What one PostgreSQL connection costs Must-know ​

In plain words: On PostgreSQL every client connection is its own operating-system process, and every process has to be created, kept in memory, and consulted whenever the server decides what each transaction may see.

Common misunderstanding: "An idle connection is free." An idle connection holds a whole backend process with its memory, and in older releases it made every other connection slower.

Definition: PostgreSQL implements a "process per user" model: a supervisor process (the postmaster) "spawns a new backend process every time a connection is requested", as the PostgreSQL documentation puts it. The cost has four parts:

PartWhat happensScale
Fork and startupfork() of the postmaster, backend initialisation, authentication (SCRAM, TLS handshake), loading catalog caches lazilyMilliseconds per connect, far more than a simple query
MemoryPrivate process memory: catalog and relation caches (CacheMemoryContext), plan caches, per-session buffers, plus work_mem for each sort or hash while runningCommonly several MB per backend at rest, much more under big queries; measure on your workload
Snapshot workEach transaction takes a snapshot of which transactions are in progress; this work grows with the number of connectionsThe GetSnapshotData() function dominated profiles with thousands of connections
ContentionSpinlocks, lightweight locks and the pg_locks tables, plus context switches between runnable processesShows up as wait_event_type LWLock and CPU in system time

The snapshot cost has a primary source. Andres Freund's analysis of connection scalability in PostgreSQL showed a single active connection slowing by more than 2x in the presence of 5000 mostly idle ones. The post says: "Obviously the bottleneck is entirely in the GetSnapshotData() function." The fix landed in PostgreSQL 14, so on older servers idle connections were costly and on current servers they are cheaper but still hold memory and a process slot.

     Client                      postmaster                      backend (new process)
1    TCP connect  ──────────────▶
2    startup packet, TLS, auth ─▶ fork()  ───────────────────────▶ init, load caches
3    ◀──────────────────────────────────────────────────────────  ReadyForQuery
4    query ... result ...                                          (about 1 ms of real work)
5    close  ──────────────────────────────────────────────────▶    process exits
     -- steps 1 to 3 cost more than step 4; a pool pays them once

Real scenario: A PHP-FPM site with no pooler opens a connection for every request: at 500 req/s the server forks 500 backends per second. A cron job fleet that starts 300 workers at the top of the minute exhausts max_connections for everybody. A Kubernetes rollout that starts 40 new pods, each with a pool of 20, briefly doubles the connection count.

What provides it (cost per product):

ProductConnection modelConsequence
PostgreSQLProcess per connectionPooler in front is standard practice; no built-in pooler
MySQL / InnoDBThread per connection (a thread pool exists in Enterprise and Percona builds)Cheaper than a process, still bounded by max_connections (default 151)
SQL ServerWorker threads multiplexed by the schedulerClient-side ADO.NET pool (Max Pool Size, default 100)
OracleDedicated server processes, or shared servers and DRCP (Database Resident Connection Pooling)DRCP is the built-in pooler
MongoDBDriver pool per client (maxPoolSize, default 100 in the drivers)A connection is a thread server-side; mongos adds its own pools
RedisSingle-threaded command loop, connection is a socket (maxclients, default 10000)Cheap connections; pooling mostly saves round trips
SQLiteIn-process, no serverA "pool" only limits file handles and writers
CockroachDB / SpannerNetwork-served SQL; connection counts still boundedDocumentation recommends a small multiple of vCPUs for pool size (check the current page for the exact number)

Fix / how to use it: Pool in the application, put a pooler in front when the fleet is large, and let queries wait in the pool rather than in the server. The rest of this page is that fix, layer by layer.

max_connections and per-role limits Must-know ​

In plain words: PostgreSQL has a hard ceiling on simultaneous connections, a few slots are kept for emergencies, and you can also cap a single role or database.

Common misunderstanding: "Raise max_connections to 1000 and the problem goes away." It raises the ceiling, the memory budget and the snapshot cost together, and it needs a restart.

Definition: max_connections "Determines the maximum number of concurrent connections to the database server", and PostgreSQL "sizes certain resources based directly on the value of max_connections". superuser_reserved_connections (default 3) keeps slots for superusers, and reserved_connections (PostgreSQL 16 and later, default 0) keeps slots for roles holding pg_use_reserved_connections. All of these need a server restart. CONNECTION LIMIT on a role or a database limits that role or database; superusers are never limited, and the documentation notes the limit "is only enforced approximately" when two sessions start at the same moment.

     Session A (app role, CONNECTION LIMIT 30)         Session B (monitoring, superuser)
1    30 sessions already open for role app
2    connect as app
3    FATAL:  too many connections for role "app"        -- SQLSTATE 53300
4                                                       connect OK  -- superusers bypass the limit
5    server at max_connections - superuser_reserved_connections (97 of 100):
6    connect as app
7    FATAL:  remaining connection slots are reserved for roles with the SUPERUSER attribute
8    server at max_connections (100 of 100), non-superuser:
9    FATAL:  sorry, too many clients already            -- SQLSTATE 53300

Real scenario: A reporting role with unbounded parallelism exhausts the server and takes the checkout API down with it; a per-role limit contains it. A rolling deploy briefly runs old and new pods, so the real peak is (old + new) × MaxOpenConns.

What prevents it (per engine):

EngineServer-wide capPer-user or per-database capError
PostgreSQLmax_connections (100)ALTER ROLE ... CONNECTION LIMIT n, ALTER DATABASE ... CONNECTION LIMIT n53300 too_many_connections
MySQLmax_connections (151)max_user_connections, CREATE USER ... WITH MAX_USER_CONNECTIONS1040 Too many connections, 1226 user limit
SQL Serveruser connections option (0 = up to 32767)Resource GovernorError 17809 (maximum user connections reached)
OraclePROCESSES, SESSIONSProfile SESSIONS_PER_USERORA-00018, ORA-02391
MongoDBnet.maxIncomingConnectionsPer-client driver maxPoolSizeConnection refused
RedismaxclientsNone built inERR max number of clients reached

Fix / how to use it:

sql
-- PostgreSQL: give each workload its own role and a ceiling
CREATE ROLE api   LOGIN PASSWORD '...' CONNECTION LIMIT 60;
CREATE ROLE batch LOGIN PASSWORD '...' CONNECTION LIMIT 10;
CREATE ROLE ops   LOGIN PASSWORD '...' CONNECTION LIMIT 5;
ALTER DATABASE shop CONNECTION LIMIT 90;

-- see the ceiling and who is using it
SHOW max_connections;
SELECT rolname, rolconnlimit FROM pg_roles WHERE rolconnlimit <> -1;
SELECT usename, count(*) FROM pg_stat_activity
WHERE backend_type = 'client backend' GROUP BY usename ORDER BY count(*) DESC;
go
// Go: make the per-process cap explicit, so the fleet sum can be computed
db.SetMaxOpenConns(10)
php
// Laravel: a role per workload is chosen in .env, one connection entry per role
// DB_USERNAME=api  (web)    DB_USERNAME=batch  (queue workers, separate env)

Pool sizing ​

The formula and the HikariCP axiom Must-know ​

In plain words: A small pool, kept busy, beats a large pool, mostly because the database can only do so many things at once.

Common misunderstanding: "My app has 200 threads, so it needs 200 connections." Threads can wait their turn; the database cannot do 200 things at once on 8 cores.

Definition: The PostgreSQL wiki, "Number Of Database Connections", states that "for optimal throughput the number of active connections should be somewhere near ((core_count * 2) + effective_spindle_count)", with core count excluding hyperthreads and spindle count zero when the working set is cached. The wiki adds that no analysis exists for SSDs, and the HikariCP wiki treats the number as a starting point to load test. HikariCP's own statement is the axiom at the top of this page. Its example of an Oracle demonstration reports a drop from about 100 ms to about 2 ms response time purely by shrinking the pool. For deadlock safety, with Tn threads that each hold at most Cm connections at once, a pool of Tn × (Cm - 1) + 1 cannot deadlock on connections.

     active connections ->        2     4     8    16    32    64   128
     throughput (tps)             ▂     ▅     █     █     ▇     ▅     ▃       <- the "knee", then decline
     latency (ms)                 2     2     3     6    14    38   110
     -- shape from the PostgreSQL wiki's description; your numbers differ, find your own knee

Real scenario: An 8-core database server behind 20 application instances each configured with MaxOpenConns = 50: 1000 possible connections against a knee near 16 to 20. Cutting each pool to 2 to 3 lowers latency and throughput stops collapsing under load.

What provides it:

SourceWhat it givesLimit
Formula (cores × 2) + spindlesA first guess for active connectionsStarting point, not a law
Load test with your queriesThe real kneeNeeds production-like data and concurrency
pg_stat_activity active count under peakWhat the workload really usesMeasured on today's workload
HikariCP deadlock boundMinimum for correctness with nested connection useNot a performance target

Fix / how to use it: Compute the database-side budget first (cores × 2 plus spindles, then round up to what tests show), divide it over every process that connects, and set each pool from that share.

Little's law applied Must-know ​

In plain words: The average number of connections busy at one moment equals how many requests arrive per second times how long each one holds a connection.

Common misunderstanding: "Request latency is what matters." The quantity is the hold time: from checkout to release. A handler that takes 200 ms but holds a connection for 5 ms needs a pool of 1, not 40.

Definition: Little's law says that the long-term average number of customers L in a stationary system equals the long-term average arrival rate λ times the average time W a customer spends in the system. Here the system is the pool: L = λ × W is the average number of connections in use.

     λ = 2000 requests/second that touch the database
     W = 5 ms average hold time (checkout to release)
     L = 2000 × 0.005 = 10 connections in use on average

     headroom for bursts and the tail:  pool = ceil(10 × 2) = 20
     if one query slows to W = 50 ms:   L = 2000 × 0.05 = 100   -> pool of 20 saturates, queue grows

This turns tuning advice into a calculation. It also shows why exhaustion is sudden: a ten-fold increase in hold time, from a lock wait or a missing index, needs a ten-fold bigger pool at the same traffic, so the pool saturates without any change in traffic. The reverse is the productive lever: halving the hold time (shorter transactions, no slow calls inside them, see ACID & Transactions) halves the pool the system needs.

Real scenario: A checkout service at 300 requests/second with a 12 ms hold needs 300 × 0.012 = 3.6 connections on average; a pool of 10 is generous. A nightly export that holds a connection for 20 minutes counts as 1/1200 requests per second times 1200 seconds = 1 connection for the whole night, which is why it belongs in its own small pool.

What provides it:

InputWhere to measure it
λApplication metrics: requests that open a transaction per second
WTime between Acquire and Release; DBStats.InUse sampled, or tracing spans around checkout
Tail of Wp99 of the hold time, not the mean
Server concurrencycount(*) FILTER (WHERE state = 'active') in pg_stat_activity

Fix / how to use it: The helper below holds the arithmetic (Little's law, headroom, the wiki formula, the deadlock bound and the fleet budget).

go
// Package sizing holds the arithmetic behind pool sizes. It is plain math so
// it can be copied into a capacity sheet or a unit test.
package sizing

import (
	"math"
	"time"
)

// LittlesLaw returns the average number of connections in use: L = lambda * W,
// where lambda is requests per second that need a connection and W is the
// average time one request holds it (checkout to release, not request time).
func LittlesLaw(requestsPerSecond float64, hold time.Duration) float64 {
	return requestsPerSecond * hold.Seconds()
}

// WithHeadroom turns the average from Little's law into a pool size. Headroom
// of 2 to 3 covers bursts and the tail of the hold-time distribution.
func WithHeadroom(avgInUse, headroom float64) int {
	return int(math.Ceil(avgInUse * headroom))
}

// FormulaStarting is the PostgreSQL wiki / HikariCP starting point for the
// number of active connections the database itself should run. coreCount
// excludes hyperthreads; spindles is 0 when the working set is cached.
func FormulaStarting(coreCount, spindles int) int {
	return coreCount*2 + spindles
}

// DeadlockFreeMin is the smallest pool that cannot deadlock on connections when
// each of threads holds up to maxHeld connections at once (HikariCP wiki):
// Tn * (Cm - 1) + 1.
func DeadlockFreeMin(threads, maxHeld int) int {
	return threads*(maxHeld-1) + 1
}

// #region budget-example

// Service is one deployable: how many instances, and each instance's pool cap.
type Service struct {
	Name      string
	Instances int
	MaxOpen   int
}

// Budget is the total server connections a fleet can ask for: instances times
// the per-process cap, summed over services.
func Budget(services []Service) int {
	total := 0
	for _, s := range services {
		total += s.Instances * s.MaxOpen
	}
	return total
}

// Fits reports whether the fleet fits in max_connections after reserving slots
// for superusers, replication, monitoring and migrations.
func Fits(services []Service, maxConnections, reserved int) bool {
	return Budget(services) <= maxConnections-reserved
}

// #endregion budget-example
php
// Laravel: the same arithmetic as a sanity check in a deploy script
$avgInUse = 300 * 0.012;              // lambda x W = 3.6
$poolPerProcess = (int) ceil($avgInUse * 2 / 4);  // 4 PHP-FPM hosts: about 2 each

Application pools in Go ​

database/sql pool knobs Must-know ​

In plain words: *sql.DB is not one connection; it is a pool with four settings that decide how many connections it opens, keeps and retires.

Common misunderstanding: "sql.Open connects." It only validates its arguments; the first query (or PingContext) dials. And "create a *sql.DB per request" defeats the pool completely (the before snippet).

Definition: The database/sql package documents that "DB is a database handle representing a pool of zero or more underlying connections. It's safe for concurrent use by multiple goroutines."

KnobDefaultEffectAdded in
SetMaxOpenConns(n)0 (unlimited)Hard cap on open connections; callers block when it is reachedGo 1.2
SetMaxIdleConns(n)2Connections kept open while idle; reduced to MaxOpenConns if that is lowerGo 1.1
SetConnMaxLifetime(d)0 (forever)Connections older than d are closed lazily before reuseGo 1.6
SetConnMaxIdleTime(d)0 (forever)Connections idle longer than d are closed lazilyGo 1.15
db.Stats()WaitCount, WaitDuration, InUse, Idle, MaxIdleClosed, MaxIdleTimeClosed, MaxLifetimeClosedGo 1.5
     goroutine 1..N                         *sql.DB                         PostgreSQL
1    db.QueryContext(ctx, ...)  ─────────▶  idle connection? yes → reuse
2    db.QueryContext(ctx, ...)  ─────────▶  idle? no; open < MaxOpenConns? yes → dial a new one
3    db.QueryContext(ctx, ...)  ─────────▶  open == MaxOpenConns → block on a request channel
4                                           (waits for a release OR ctx.Done())
5    rows.Close()               ─────────▶  connection returns: handed straight to a waiter
6    ctx deadline passes        ─────────▶  waiter gets context.DeadlineExceeded; WaitCount stays counted

Real scenario: A service sets SetMaxIdleConns(100) but leaves MaxOpenConns at 0, then a traffic spike opens 400 connections that stay idle for hours (no idle time set). SetConnMaxLifetime is also how a client notices a new primary after failover when the DNS name now points elsewhere.

What provides it: The pool is standard-library behaviour for every driver; pgx (via stdlib), lib/pq, go-sql-driver/mysql and others plug in below it.

Fix / how to use it: The shared pool with limits, deadline-bound handlers and a health endpoint:

go
// Package after holds the process-wide database pool and its limits.
package after

import (
	"context"
	"database/sql"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// Open returns the one *sql.DB for this process. Call it once in main and
// pass the result to every component that needs the database.
func Open(ctx context.Context, dsn string) (*sql.DB, error) {
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		return nil, err
	}

	// A hard cap per process. Across N instances the server (or PgBouncer,
	// behind its own pool_size) sees at most N * MaxOpenConns backends.
	db.SetMaxOpenConns(10)

	// Idle connections still hold a server backend, so keep only a few.
	db.SetMaxIdleConns(5)

	// Replace connections periodically and drop idle ones, so a changed
	// endpoint or a stuck backend is not reused forever.
	db.SetConnMaxLifetime(30 * time.Minute)
	db.SetConnMaxIdleTime(5 * time.Minute)

	pingCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
	defer cancel()
	if err := db.PingContext(pingCtx); err != nil {
		db.Close()
		return nil, err
	}
	return db, nil
}
go
package after

import (
	"context"
	"database/sql"
	"fmt"
	"net/http"
	"time"
)

// CountHandler uses the shared pool. The deadline covers the wait for a free
// connection as well as the query, so an exhausted pool fails fast with 503
// instead of holding the request open.
func CountHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
		defer cancel()

		var n int
		if err := db.QueryRowContext(ctx, "select count(*) from orders").Scan(&n); err != nil {
			http.Error(w, err.Error(), http.StatusServiceUnavailable)
			return
		}
		fmt.Fprintf(w, "%d\n", n)
	}
}
go
package after

import (
	"context"
	"database/sql"
	"encoding/json"
	"net/http"
	"time"
)

// HealthHandler pings the database and reports pool state from db.Stats().
// A rising WaitCount or WaitDuration means requests are queueing for a
// connection: the pool is too small, or queries are too slow.
func HealthHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx, cancel := context.WithTimeout(r.Context(), time.Second)
		defer cancel()

		status := http.StatusOK
		if err := db.PingContext(ctx); err != nil {
			status = http.StatusServiceUnavailable
		}

		s := db.Stats()
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(status)
		_ = json.NewEncoder(w).Encode(map[string]any{
			"ok":               status == http.StatusOK,
			"max_open":         s.MaxOpenConnections,
			"open":             s.OpenConnections,
			"in_use":           s.InUse,
			"idle":             s.Idle,
			"wait_count":       s.WaitCount,
			"wait_duration_ms": s.WaitDuration.Milliseconds(),
		})
	}
}
go
// Package main is the composition root: it opens the one pool and shares it.
package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"time"

	"academy/connection-pooling/after"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	db, err := after.Open(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	mux := http.NewServeMux()
	mux.Handle("GET /orders/count", after.CountHandler(db))
	mux.Handle("GET /healthz", after.HealthHandler(db))

	log.Fatal(http.ListenAndServe(":8080", mux))
}

The anti-pattern (a new *sql.DB per request, no limits, no Close) for contrast:

go
// Package before shows the anti-pattern: a new pool for every request, with
// no limits, no lifetime and no Close.
package before

import (
	"database/sql"
	"fmt"
	"net/http"

	_ "github.com/jackc/pgx/v5/stdlib"
)

// The DSN points straight at PostgreSQL: no pooler, and every request still
// builds its own pool.
const dsn = "postgres://app:secret@postgres:5432/shop?sslmode=disable"

func CountHandler(w http.ResponseWriter, r *http.Request) {
	// sql.Open does not dial. Each call creates a new *sql.DB with its own
	// pool, which is used for one query and never closed. The pool has no
	// MaxOpenConns, so under load every request can open its own connection,
	// and idle connections are kept with the default MaxIdleConns of 2 and no
	// lifetime limit.
	db, err := sql.Open("pgx", dsn)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	var n int
	if err := db.QueryRow("select count(*) from orders").Scan(&n); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "%d\n", n)
}

pgxpool Important ​

In plain words: If you use pgx directly instead of database/sql, pgxpool is its own pool with extra knobs and richer statistics.

Common misunderstanding: "pgxpool and database/sql have the same defaults." pgxpool's MaxConns defaults to the greater of 4 or runtime.NumCPU(), and it has a background health check that database/sql has no equivalent of.

Definition: pgxpool.Config exposes MaxConns, MinConns, MaxConnLifetime (default one hour), MaxConnLifetimeJitter, MaxConnIdleTime (default 30 minutes), HealthCheckPeriod (default one minute), plus hooks BeforeAcquire and AfterRelease that can veto a connection. Pool.Stat() reports AcquiredConns, IdleConns, TotalConns, EmptyAcquireCount (acquires that found no idle connection), EmptyAcquireWaitTime and CanceledAcquireCount.

Concerndatabase/sqlpgxpool
CapSetMaxOpenConns (0 = unlimited)MaxConns (default max(4, NumCPU))
Keep warmnoneMinConns
LifetimeSetConnMaxLifetimeMaxConnLifetime plus MaxConnLifetimeJitter
IdleSetConnMaxIdleTimeMaxConnIdleTime, HealthCheckPeriod
Veto reusedriver ResetSession / IsValidBeforeAcquire, AfterRelease
Wait metricsWaitCount, WaitDurationEmptyAcquireCount, EmptyAcquireWaitTime, CanceledAcquireCount
Prepared statementsdriver decidesdefault QueryExecModeCacheStatement: a prepared-statement cache per connection

The last row matters behind a pooler: the pgx source says its default mode "may be incompatible with proxies" such as PgBouncer and recommends QueryExecModeExec or QueryExecModeSimpleProtocol there (also settable in a DSN as default_query_exec_mode=simple_protocol).

Real scenario: Without jitter, all 40 pods reconnect at the 30-minute mark together after a restart wave; with MaxConnLifetimeJitter they spread out. AfterRelease returning false when TxStatus() != 'I' stops a connection left inside a transaction from being reused.

Fix / how to use it:

go
// Package pgxpoolsetup builds a pgxpool.Pool with every knob that matters.
package pgxpoolsetup

import (
	"context"
	"fmt"
	"time"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
)

// New returns a pool for one process. behindPooler is true when dsn points at
// PgBouncer in transaction mode (or another transaction-level pooler).
func New(ctx context.Context, dsn string, behindPooler bool) (*pgxpool.Pool, error) {
	cfg, err := pgxpool.ParseConfig(dsn)
	if err != nil {
		return nil, err
	}

	// The default is the greater of 4 or runtime.NumCPU(), which is rarely what
	// you want: size it from the budget, not from the machine running the app.
	cfg.MaxConns = 10
	cfg.MinConns = 2

	// Retire connections so failovers, DNS changes and server-side limits are
	// noticed. The jitter spreads the reconnects instead of one big wave.
	cfg.MaxConnLifetime = 30 * time.Minute
	cfg.MaxConnLifetimeJitter = 5 * time.Minute
	cfg.MaxConnIdleTime = 5 * time.Minute

	// The background health check closes idle or expired connections and keeps
	// MinConns filled.
	cfg.HealthCheckPeriod = time.Minute

	// Fail fast when a new connection cannot be built (server full, network).
	cfg.ConnConfig.ConnectTimeout = 5 * time.Second

	if behindPooler {
		// The default mode caches named prepared statements per connection,
		// which a transaction pooler cannot honour. The simple protocol sends
		// plain query text and works with any pooler.
		cfg.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
	}

	// AfterRelease runs when a connection goes back to the pool. Returning
	// false destroys it, which is how you refuse to reuse a connection that
	// was left inside a transaction.
	cfg.AfterRelease = func(c *pgx.Conn) bool {
		return c.PgConn().TxStatus() == 'I'
	}

	pool, err := pgxpool.NewWithConfig(ctx, cfg)
	if err != nil {
		return nil, err
	}
	return pool, nil
}

// QueryWithAcquireTimeout bounds the wait for a free connection and the query
// together. When the pool is full, Acquire blocks until a connection is
// released or ctx expires; the deadline is the acquisition timeout.
func QueryWithAcquireTimeout(ctx context.Context, pool *pgxpool.Pool) (int, error) {
	ctx, cancel := context.WithTimeout(ctx, 2*time.Second)
	defer cancel()

	var n int
	if err := pool.QueryRow(ctx, "select count(*) from orders").Scan(&n); err != nil {
		return 0, err
	}
	return n, nil
}

// Report prints the numbers worth graphing: a high EmptyAcquireCount means
// callers found no idle connection and had to wait or dial.
func Report(pool *pgxpool.Pool) string {
	s := pool.Stat()
	return fmt.Sprintf(
		"max=%d total=%d acquired=%d idle=%d acquires=%d empty_acquires=%d empty_wait=%s canceled=%d",
		s.MaxConns(), s.TotalConns(), s.AcquiredConns(), s.IdleConns(),
		s.AcquireCount(), s.EmptyAcquireCount(), s.EmptyAcquireWaitTime(), s.CanceledAcquireCount(),
	)
}

Exhaustion and leaks ​

Acquisition timeouts and pool exhaustion Must-know ​

In plain words: When every connection is checked out, new callers stand in line; the only thing that stops the line from growing forever is a deadline.

Common misunderstanding: "Pool exhaustion is a database problem." Usually the database is idle or lightly loaded; the connections are held by a few slow or stuck callers, and everybody else waits in the application.

Definition: Pool exhaustion is the state where in_use == max and new requests block. In Go, the database/sql wait ends on a release or ctx.Done(), so a request context with a deadline is the acquisition timeout; there is no separate setting. pgxpool.Acquire(ctx) behaves the same. PgBouncer has its own wait limit, query_wait_timeout (default 120 seconds), after which "the client is disconnected". HikariCP calls it connectionTimeout, and PDO has none (a request waits on the server).

healthyin_use 3 of 10one query slowsrow lock, no index,slow replicain_use 8 of 10pool fullin_use 10 of 10callers queueWaitCount riseslatency = wait + querydeadlines expire503 / context deadlineexceeded, retries addmore load (storm)DB CPU still lowMaxOpenConns (cap)timeTypical first signals: WaitCount and WaitDuration (Go), cl_waiting and maxwait (PgBouncer),state = idle in transaction and wait_event_type = Lock in pg_stat_activity.Fix the cause (the slow query or the open transaction), not only the pool size.
     time    event                                              in_use  waiting  p99
1    t0      normal traffic, queries 5 ms                        3/10      0      8 ms
2    t1      a deploy adds a lock; UPDATE blocks for 30 s        8/10      0     60 ms
3    t2      more requests hit the same row; all hold a conn     10/10     4    900 ms
4    t3      request deadlines (2 s) expire; clients retry       10/10    40    2 s timeouts
5    t4      retries double the arrival rate                      10/10   120    503s
6    t5      lock released; backlog drains over minutes          10/10    ...   recovering
     -- database CPU stayed low throughout; the pool, not the server, was the bottleneck

Symptoms you can recognise:

LayerSignalMeaning
Go database/sqlInUse == MaxOpenConnections, rising WaitCount and WaitDurationCallers queue for a connection
pgxpoolAcquiredConns == MaxConns, rising EmptyAcquireCount, CanceledAcquireCountSame, plus callers that gave up
PgBouncerSHOW POOLS: cl_waiting > 0, large maxwaitClients wait for a server connection
PostgreSQLpg_stat_activity: many idle in transaction or wait_event_type = 'Lock'The connections are held, not working
HTTP503 or timeouts with low database CPUPool wait counted inside request latency
LaravelSQLSTATE[08006] / too many clients already, queue jobs piling upWorkers each hold a backend

Real scenario: A reporting endpoint without an index runs for 40 seconds. Ten concurrent calls hold all ten connections, and the checkout API, which needs 5 ms, waits behind them. Latency is wait plus query.

Fix / how to use it: In order of preference: fix the slow query or open transaction (Little's law: hold time), put a deadline on every request including the wait for a connection, give slow background work its own small pool (the HikariCP wiki suggests separate pools for long and short transactions), then, last, raise the pool size if the database has spare capacity. QueryWithAcquireTimeout in the pgxpool snippet and CountHandler above show the deadline.

Leaked connections and idle in transaction Must-know ​

In plain words: A leak is a connection that was checked out and never given back; "idle in transaction" is a connection that was given a BEGIN and then nothing.

Common misunderstanding: "The garbage collector or the end of the function will release it." Go does not release a *sql.Rows or *sql.Tx automatically on return; PHP releases the PDO at the end of the request only under PHP-FPM, not in a worker or an Octane server.

Definition: A leak shows as InUse climbing and never falling back even at zero traffic. Idle in transaction is a pg_stat_activity.state meaning "The backend is in a transaction, but is not currently executing a query"; it keeps locks and, as the PostgreSQL docs explain for idle_in_transaction_session_timeout, prevents vacuuming away "recently-dead tuples" and so contributes to bloat (see MVCC, VACUUM & Bloat).

     goroutine                                   pool                                   PostgreSQL
1    rows, _ := db.Query(...)                    InUse 1/10
2    rows.Scan fails -> return err               (rows never closed)
3                                                InUse 1/10, never released              backend sits idle, unusable
4    ... repeated 10 times                       InUse 10/10                              10 backends held by nobody
5    next caller                                 blocks forever (no deadline)
     -- fix: defer rows.Close() immediately after the error check; check rows.Err()

Real scenario: A handler begins a transaction, calls a payment API for 8 seconds, then commits; at 50 req/s that is 50 × 8 = 400 connections in idle in transaction by Little's law. Another: defer tx.Rollback() is missing on an early return, so each failing request leaks one connection until the process restarts.

What provides the protection:

ProtectionWhereEffect
defer rows.Close(), defer tx.Rollback(), defer conn.Close()Go codeReleases on every path
idle_in_transaction_session_timeoutPostgreSQL (per role, database or server)Terminates sessions idle inside a transaction; default 0 (off)
idle_session_timeoutPostgreSQL 14 and laterTerminates plain idle sessions; less important, as the docs say
transaction_timeoutPostgreSQL 17 and laterBounds the total transaction duration
idle_transaction_timeoutPgBouncerDisconnects clients idle in transaction
statement_timeout, lock_timeoutPostgreSQLBounds the query itself and the lock wait
ConnMaxLifetime, AfterReleasePoolRetires or vetoes bad connections

Fix / how to use it:

sql
-- PostgreSQL: set per role so one workload cannot hold transactions open forever
ALTER ROLE api SET idle_in_transaction_session_timeout = '15s';
ALTER ROLE api SET statement_timeout = '5s';
ALTER ROLE api SET lock_timeout = '2s';

-- find the culprits now
SELECT pid, usename, application_name, now() - xact_start AS xact_age, state, left(query, 80)
FROM pg_stat_activity
WHERE state LIKE 'idle in transaction%' ORDER BY xact_start;
go
// Package before shows three ways a *sql.DB pool loses connections.
package before

import (
	"context"
	"database/sql"
)

// ListIDs forgets rows.Close on the early return. The connection stays checked
// out until the garbage collector never gets to it: InUse climbs by one for
// every failing call.
func ListIDs(ctx context.Context, db *sql.DB) ([]int, error) {
	rows, err := db.QueryContext(ctx, "select id from orders")
	if err != nil {
		return nil, err
	}

	var ids []int
	for rows.Next() {
		var id int
		if err := rows.Scan(&id); err != nil {
			return nil, err // leak: rows is not closed
		}
		ids = append(ids, id)
	}
	return ids, nil
}

// SlowTx holds a transaction, and so a connection, across a slow call and
// returns early without Rollback.
func SlowTx(ctx context.Context, db *sql.DB, call func() error) error {
	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	if err := call(); err != nil {
		return err // leak: tx is neither committed nor rolled back
	}
	return tx.Commit()
}

// Pinned takes a dedicated *sql.Conn and never gives it back.
func Pinned(ctx context.Context, db *sql.DB) error {
	conn, err := db.Conn(ctx)
	if err != nil {
		return err
	}
	_, err = conn.ExecContext(ctx, "select 1")
	return err // leak: conn.Close is never called
}
go
// Package after releases every connection on every path.
package after

import (
	"context"
	"database/sql"
)

// ListIDs closes rows with defer and checks rows.Err, which reports errors
// that ended the iteration.
func ListIDs(ctx context.Context, db *sql.DB) ([]int, error) {
	rows, err := db.QueryContext(ctx, "select id from orders")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var ids []int
	for rows.Next() {
		var id int
		if err := rows.Scan(&id); err != nil {
			return nil, err
		}
		ids = append(ids, id)
	}
	return ids, rows.Err()
}

// SlowTx does the slow call before BEGIN, so no connection is held while
// waiting, and defers Rollback, which is a no-op after Commit.
func SlowTx(ctx context.Context, db *sql.DB, call func() error) error {
	if err := call(); err != nil {
		return err
	}

	tx, err := db.BeginTx(ctx, nil)
	if err != nil {
		return err
	}
	defer tx.Rollback()

	if _, err := tx.ExecContext(ctx, "update orders set synced = true where synced = false"); err != nil {
		return err
	}
	return tx.Commit()
}

// Pinned always returns the dedicated connection to the pool.
func Pinned(ctx context.Context, db *sql.DB) error {
	conn, err := db.Conn(ctx)
	if err != nil {
		return err
	}
	defer conn.Close()

	_, err = conn.ExecContext(ctx, "select 1")
	return err
}
php
// Laravel: DB::transaction releases on every path; a manual beginTransaction does not
DB::transaction(function () {
    // short, no HTTP calls inside
});
// avoid: DB::beginTransaction(); ... early return ... (never committed or rolled back)

PHP and Laravel ​

PHP-FPM: one connection per worker Must-know ​

In plain words: Classic PHP shares nothing between requests. Every request opens a connection and throws it away, so the number of connections equals the number of busy workers.

Common misunderstanding: "PHP has no pool, so it cannot run out of connections." It runs out faster than a pooled language, because the connection count is pm.max_children per FPM pool per host, multiplied by the hosts, with no application-level cap.

Definition: Under PHP-FPM each worker process serves one request at a time; the Laravel DB facade connects lazily on the first query and the PDO handle dies with the request. The worst-case connection count is hosts × pm.max_children. PHP's PDO has an opt-in alternative, persistent connections (PDO::ATTR_PERSISTENT => true), which the PHP manual describes as connections that "are not closed at the end of the script, but are cached and re-used" when another script asks for a connection with the same credentials.

     PHP-FPM worker 1..N                   PostgreSQL (direct)                    PgBouncer (transaction mode)
1    request starts
2    first query -> PDO connects  ───────▶ fork backend (about ms)       OR   client socket accepted, server conn lent per transaction
3    queries ...
4    request ends, PDO destroyed ────────▶ backend exits                  OR   client socket closed; server conn already back in pool
     -- with 40 busy workers: 40 backends direct, or 40 client sockets and a handful of backends via the pooler
SetupConnections heldNotes
PHP-FPM, no persistenceOne per busy request, created and destroyed each timeFork cost every request; fine at low rate
PHP-FPM + PDO::ATTR_PERSISTENTOne per worker, kept for the worker's lifeSession state (open transactions, SET, temp tables) can leak between requests; unused ones still hold a backend
PHP-FPM + PgBouncer (transaction)Many client sockets, few backendsStandard answer; no persistence needed
Octane (Swoole, FrankenPHP, RoadRunner)One per worker, application stays in memorySee next section
Queue worker (queue:work)One per worker for its whole lifeIdle workers still hold a backend

Real scenario: 6 web hosts with pm.max_children = 50 give 300 potential backends against max_connections = 100; a traffic burst fills all FPM children and the database answers too many clients already. Persistent connections would make it worse: idle FPM children keep their backends too.

What prevents it: PgBouncer in front; pm.max_children sized from the budget (max_children × hosts must fit); pm.max_requests to recycle workers; no persistence unless a pooler sits in front.

Fix / how to use it: Use the Laravel pooled configuration below, and keep long jobs from holding a connection while they wait on slow I/O (DB::disconnect() before the slow part, see the job snippet).

Octane, Swoole, FrankenPHP and connection reuse Must-know ​

In plain words: Laravel Octane starts your application once and keeps it in memory, so a connection opened by one request is still open for the next. That is faster, and it changes what a connection's lifetime means.

Common misunderstanding: "Octane has a database pool." It does not; each Octane worker holds its own connection (and its own copy of the application). The number of server connections is the number of workers, not the number of requests.

Definition: Octane "boots your application once, keeps it in memory, and then feeds it requests", on FrankenPHP, Open Swoole, Swoole or RoadRunner. By default it starts one worker per CPU core (--workers overrides), and "gracefully restarts any worker once it has handled 500 requests" (--max-requests), which also recycles that worker's connection. The default config/octane.php has DisconnectFromDatabases commented out of the OperationTerminated listeners, so connections persist across requests.

RuntimeConcurrency modelConnection perGotcha
FrankenPHP (worker mode)PHP threads in a Go serverWorkerState is kept between requests; reset what you set
Swoole / Open SwooleProcess workers plus task workersWorker and task workerCoroutines need their own connection each; do not share one PDO across coroutines
RoadRunnerGo server managing PHP worker processesWorkerSame as above
PHP-FPMProcess per requestRequestNo reuse, so no stale state either
     Octane worker 3                               PostgreSQL / PgBouncer
1    boot app, connect lazily on first query
2    request 1: SET search_path = tenant_a  ─────▶ session now has tenant_a
3    request 2 (another tenant, same worker)
4    query ... runs against tenant_a            ◀── stale session state: wrong tenant
5    fix: SET LOCAL inside a transaction, or reset in OperationTerminated, or disconnect
     -- behind transaction-mode PgBouncer the same SET can even land on a different backend: random, not stable

Real scenario: Multi-tenant SaaS using a per-request SET search_path leaks tenant context between requests on Octane. A worker that crashed halfway through a transaction would return a connection with an aborted transaction, which the next request inherits unless the connection is dropped.

What provides it:

MechanismEffect
--workersCaps connections: workers × Octane instances
--max-requests (default 500)Recycles workers and their connections
DisconnectFromDatabases listenerDrops the PDO after each operation; next query reconnects
config('database.connections.*.options')PDO attributes per connection
DB::reconnect() / DB::purge()Manual reconnect
Transaction pooler in frontMakes per-request disconnect cheap

Fix / how to use it:

php
<?php

// config/octane.php (excerpt). Octane keeps the application, and therefore the
// PDO handles, alive between requests. Choose the connection policy on purpose.
use Laravel\Octane\Contracts\OperationTerminated;
use Laravel\Octane\Listeners\DisconnectFromDatabases;
use Laravel\Octane\Listeners\FlushOnce;
use Laravel\Octane\Listeners\FlushTemporaryContainerInstances;

return [
    'listeners' => [
        OperationTerminated::class => [
            FlushOnce::class,
            FlushTemporaryContainerInstances::class,

            // Option A (default, listener commented out): keep each worker's
            // connection for the next request. Fastest, and each worker holds
            // one server connection for its whole life. Budget: workers x
            // octane instances, not requests per second.
            //
            // Option B: uncomment the line below to disconnect after every operation. Behind transaction-mode
            // PgBouncer this costs a client socket per request but frees any
            // direct backend. Use it when workers vastly outnumber the budget.
            // DisconnectFromDatabases::class,
        ],
    ],
];

// Start the server with a recycling limit so connections, and any leaked
// state, do not live forever:
//   php artisan octane:start --workers=8 --max-requests=500   (500 is already the default)

Laravel 13: pooled and direct connections Important ​

In plain words: Laravel 13 lets one PostgreSQL connection entry describe two endpoints: a pooled one for normal queries and a direct one for the operations a transaction pooler cannot do.

Common misunderstanding: "Pointing DB_HOST at PgBouncer is all Laravel needs." Without pooled, Laravel uses native server-side prepared statements, which break when the next transaction lands on a different backend, and migrations run through the pooler.

Definition: The Laravel 13 database docs: transaction-mode poolers "are ideal for application queries, but some schema operations, migrations, and maintenance commands require a direct database connection." You set 'pooled' => true and give the direct endpoint in a 'direct' array. "When a PostgreSQL connection is configured as pooled, Laravel automatically enables emulated prepares for the pooled connection. The direct connection inherits any options not explicitly defined in the direct configuration and uses native prepares by default." Laravel "automatically uses the direct connection for migrations, schema dumps and restores, db:wipe, db:show, and db:table", php artisan db uses it by default (--pooled selects the pooled one), and DB::connection('pgsql::direct') asks for it explicitly.

OperationConnection usedWhy
Eloquent / query builder at request timepooledShort transactions; many clients
php artisan migrate, db:wipe, schema dump/loaddirectDDL and session settings need a real session
DB::connection('pgsql::direct')->statement('create extension ...')directExplicit choice
LISTEN / NOTIFY consumersdirect (or a session-mode pool)LISTEN never works in transaction mode
Long export with a cursor WITH HOLDdirectNeeds session
Queue workerspooled, but see jobs belowEach worker holds one client socket, not necessarily a backend

Real scenario: A managed provider exposes both a pooled port and a direct port. The app runs with DB_PORT=6432 pooled and DB_DIRECT_PORT=5432 direct; php artisan migrate works with no extra flags, while an advisory-lock-based job scheduler is pointed at the direct connection.

Fix / how to use it:

php
<?php

// config/database.php (excerpt). PostgreSQL behind PgBouncer in transaction mode.
// Port 6432 is the pooled endpoint. The direct endpoint serves migrations and
// other schema work that needs a real session.
//
// 'pooled' => true makes Laravel use emulated prepares for this connection.
// Transaction mode can hand the next transaction to a different backend, so
// the pooled connection avoids server-side prepared statements.
// No PDO::ATTR_PERSISTENT is set: PDO does not clean up persistent connections,
// and the pooler already reuses server connections.
return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '6432'),
            'database' => env('DB_DATABASE', 'shop'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            'sslmode' => env('DB_SSLMODE', 'prefer'),
            'pooled' => env('DB_POOLED', true),
            'direct' => array_filter([
                'host' => env('DB_DIRECT_HOST'),
                'port' => env('DB_DIRECT_PORT'),
                'username' => env('DB_DIRECT_USERNAME'),
                'password' => env('DB_DIRECT_PASSWORD'),
                'sslmode' => env('DB_DIRECT_SSLMODE'),
            ]),
        ],
    ],
];

The job below drops its PDO before slow external calls, and the "before" version shows what it replaces:

php
<?php

// config/database.php (excerpt). PostgreSQL directly, no pooler.
// Every PHP-FPM request opens its own connection. A queue worker keeps the
// connection it opened for as long as the worker runs.
return [
    'connections' => [
        'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '5432'),
            'database' => env('DB_DATABASE', 'shop'),
            'username' => env('DB_USERNAME', 'app'),
            'password' => env('DB_PASSWORD', ''),
            'sslmode' => 'prefer',
        ],
    ],
];
php
<?php

// app/Jobs/SyncShipments.php: a job that holds its connection idle.
namespace App\Jobs;

use App\Services\ShipmentApi;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

final class SyncShipments implements ShouldQueue
{
    use Queueable;

    public function handle(ShipmentApi $api): void
    {
        $pending = DB::table('shipments')
            ->where('synced', false)
            ->limit(100)
            ->pluck('id');

        // The PDO opened by the query above stays open while each push() call
        // waits on the shipping API. The worker holds one backend for the
        // whole time, even though it is doing nothing with the database.
        foreach ($pending as $id) {
            $api->push($id); // may take seconds per call
        }

        DB::table('shipments')->whereIn('id', $pending)->update(['synced' => true]);
    }
}
php
<?php

// app/Jobs/SyncShipments.php: the same job, releasing its PDO while it waits.
namespace App\Jobs;

use App\Services\ShipmentApi;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;

final class SyncShipments implements ShouldQueue
{
    use Queueable;

    public function handle(ShipmentApi $api): void
    {
        $pending = DB::table('shipments')
            ->where('synced', false)
            ->limit(100)
            ->pluck('id');

        // Drop the PDO before the slow part. Call this only when no transaction
        // is open. Behind transaction-mode PgBouncer, the server backend is
        // already free between transactions, so this releases only the client
        // socket. On a direct connection it also frees the backend. The next
        // query reconnects lazily.
        DB::disconnect();

        foreach ($pending as $id) {
            $api->push($id); // may take seconds per call
        }

        DB::table('shipments')->whereIn('id', $pending)->update(['synced' => true]);
    }
}

// Octane note: Octane boots the application once per worker and keeps it in
// memory, so a connection opened by one request is reused by the next. The
// default config/octane.php leaves DisconnectFromDatabases commented out in its
// OperationTerminated listeners. Keep session state (SET, temporary tables,
// advisory locks) out of request and job code behind a transaction pooler.
// The max-requests option restarts a worker after a set number of requests.

DB::disconnect() drops the PDO and the next query reconnects lazily through reconnectIfMissingConnection(). Never call it with a transaction open: dropping the PDO ends that transaction. Behind transaction-mode PgBouncer it frees only the client socket, because between transactions no server connection is held anyway.

PgBouncer ​

Pooling modes: session, transaction, statement Must-know ​

In plain words: PgBouncer sits between your app and PostgreSQL and decides when a server connection is borrowed and when it is returned. Three modes mean three answers.

Common misunderstanding: "Transaction mode is just a faster session mode." It changes the contract: the server connection you used for transaction one may not be the one for transaction two.

Definition: The PgBouncer docs define pool_mode: session ("Server is released back to pool after client disconnects", the default), transaction ("Server is released back to pool after transaction finishes") and statement ("Server is released back to pool after query finishes. Transactions spanning multiple statements are disallowed"). PgBouncer describes itself as a "Lightweight connection pooler for PostgreSQL" with "2 kB per connection by default" of memory.

orders service4 replicas x MaxOpenConns 10= 40 client connectionsbilling service4 replicas x MaxOpenConns 10= 40 client connectionsreports service4 replicas x MaxOpenConns 10= 40 client connectionsPgBouncerpool_mode = transactionmax_client_conn = 1000120 clients indefault_pool_size = 20per (database, user)PostgreSQLmax_connections = 100superuser_reserved = 32 users x 20 = 40 backends(one fork each)room left for admin, jobs12040Without the pooler: 120 backends requested, 100 allowed: FATAL: sorry, too many clients already
     Client A                       PgBouncer (transaction mode)                 PostgreSQL backends
1    BEGIN  ────────────────────▶   assign server conn S1 to A  ───────────────▶ S1: BEGIN
2    SELECT ... ────────────────▶   (A keeps S1 until COMMIT)  ────────────────▶ S1
3    COMMIT ────────────────────▶   ◀───────────────────────────────────────── S1: COMMIT; S1 back in pool
4    (A thinks, 200 ms; holds no server conn)               Client B: BEGIN → assigned S1
5    SELECT 1 (autocommit) ─────▶   assign S2 (S1 is busy with B)
6    -- A's two transactions ran on S1 and S2: any SET or PREPARE from the first is gone
Client AtxntxntxnClient BtxntxntxnClient CtxntxnClient DtxntxntxnServer conn 1ACADADServer conn 2DBBCB4 clients, 11 transactions, only 2 server connections (time goes left to right)PgBouncer assigns a server connection per transactionEach box is one transaction (BEGIN to COMMIT). The gaps between boxes are idle or think time: the server connection is back in the pool.
ModeMultiplexing ratioPrepared statementsLISTEN, SET, session advisory locksTypical use
session1 client : 1 server for the whole connectionNative, workWorkFew long-lived clients; legacy; also saves fork cost
transactionMany clients : few serversProtocol-level with max_prepared_statements; SQL-level PREPARE neverNeverWeb request/response workloads
statementMany clients : few serversCovered by max_prepared_statements as in transaction modeNever; no multi-statement transactionsPL/Proxy style autocommit

Real scenario: 3000 PHP-FPM children behind PgBouncer: max_client_conn = 5000, default_pool_size = 20. PostgreSQL sees 20 backends per database and user, PgBouncer holds 3000 sockets at about 2 kB each.

What provides it (per product):

ProductSession poolingTransaction poolingStatement pooling
PgBouncerpool_mode = session (default)pool_mode = transactionpool_mode = statement
pgcatYesYes (the default)Not documented
OdysseyYesYes, tracks transaction stateNot documented
SupavisorYesYesNot documented
Pgpool-IIConnection pooling per child processNo transaction multiplexingNo
ProxySQL (MySQL)n/aMultiplexing disabled during a transactionn/a
RDS ProxyPinned sessionsMultiplexing at transaction level when not pinnedn/a

Fix / how to use it:

ini
; pgbouncer.ini
[databases]
shop = host=10.0.0.5 port=5432 dbname=shop

[pgbouncer]
listen_port = 6432
auth_type = scram-sha-256
auth_file = /etc/pgbouncer/userlist.txt
pool_mode = transaction
default_pool_size = 20
reserve_pool_size = 5
reserve_pool_timeout = 3
max_client_conn = 2000
max_prepared_statements = 200
server_idle_timeout = 600
server_lifetime = 3600
query_wait_timeout = 10
idle_transaction_timeout = 30

What breaks in transaction mode Must-know ​

In plain words: Anything the app stores in the connection itself disappears or lands on a stranger's connection after each transaction.

Common misunderstanding: "It works in staging, so it is compatible." Breakage is non-deterministic: it appears only when the second transaction lands on a different backend, which happens under load.

Definition: The PgBouncer feature map marks these as "Never" in transaction pooling: SET/RESET, LISTEN, WITH HOLD CURSOR, PREPARE / DEALLOCATE, PRESERVE/DELETE ROWS temp tables, the LOAD statement and session-level advisory locks. Compatible: NOTIFY, WITHOUT HOLD CURSOR, ON COMMIT DROP temp tables, protocol-level prepared plans (with max_prepared_statements), cached plan reset, and startup parameters (client_encoding, DateStyle, IntervalStyle, Timezone, standard_conforming_strings, application_name), which PgBouncer tracks itself.

FeatureSession modeTransaction modeSafe replacement
SET search_path / SET ROLE / SET statement_timeoutYesNever (applies to a random later transaction)SET LOCAL inside the transaction, or role/database defaults with ALTER ROLE ... SET
LISTENYesNeverDirect connection or a session-mode pool for the listener
NOTIFYYesYes
SQL-level PREPARE / EXECUTE / DEALLOCATEYesNeverProtocol-level prepared statements (max_prepared_statements) or simple protocol
pg_advisory_lock (session)YesNever; lock outlives the transaction on a backend you no longer ownpg_advisory_xact_lock
WITH HOLD cursorYesNeverWITHOUT HOLD inside a transaction, or keyset pagination
Temp table PRESERVE ROWSYesNeverON COMMIT DROP temp table inside one transaction
LOAD, session-level extensions configYesNeverServer config
SELECT ... FOR UPDATE (row locks)YesYes: ends with the transaction

server_reset_query. When a server connection is returned in session mode, PgBouncer runs server_reset_query ("Query sent to server on connection release, before making it available to other clients"), default DISCARD ALL, so the next client gets a clean session. It does not run in transaction mode ("because in that mode, clients must not use any session-based features, since each transaction ends up in a different connection"). server_reset_query_always (default off) runs it in every mode, which "changes non-deterministic breakage to deterministic breakage": clients always lose state after each transaction. A lighter reset is DEALLOCATE ALL.

     Client A                                   PgBouncer                                 Backend S1 / S2
1    SET statement_timeout = '1s'  ─────────▶   forwards to S1                           S1: statement_timeout = 1s
2    COMMIT / transaction ends                  S1 back to pool (no reset in txn mode)     S1 keeps the 1s timeout!
3    Client B BEGIN  ───────────────────────▶   assigned S1                              B's queries now abort after 1 s
4    -- the setting leaked to another client: a bug that appears only under concurrency
5    fix: ALTER ROLE api SET statement_timeout = '5s';  or  SET LOCAL statement_timeout = '1s' inside the txn

Real scenario: A Rails or Laravel app calls SET search_path at the start of each request (multi-tenant schemas) and, behind PgBouncer, tenants see each other's data intermittently. A cron job takes pg_advisory_lock(42) for singleton execution; the lock is held by a backend that is later lent to another client, which then cannot take it, or releases it by accident.

What prevents it: use SET LOCAL (transaction-scoped), pg_advisory_xact_lock, role-level defaults, and a direct connection for session features. See Locks & Concurrency for advisory lock semantics.

Fix / how to use it:

sql
-- session state that survives a transaction pooler: scope it to the transaction
BEGIN;
SET LOCAL search_path = tenant_42, public;
SET LOCAL statement_timeout = '2s';
SELECT pg_advisory_xact_lock(hashtext('nightly-report'));   -- released at COMMIT
-- ... work ...
COMMIT;
go
// Go: SET LOCAL inside the transaction, on the connection the transaction owns
tx, _ := db.BeginTx(ctx, nil)
defer tx.Rollback()
tx.ExecContext(ctx, "SET LOCAL search_path = tenant_42, public")
php
// Laravel: DB::transaction owns one connection for the closure
DB::transaction(function () {
    DB::statement('SET LOCAL search_path = tenant_42, public');
    // queries here run in that schema
});

Prepared statements behind a transaction pooler Must-know ​

In plain words: A prepared statement lives on one specific server connection. In transaction mode the next transaction may land on another connection that has never heard of it.

Common misunderstanding: "Prepared statements cannot be used with PgBouncer." That was true until PgBouncer 1.21.0 (2023-10-16, "The one with prepared statements"), which added support for protocol-level named prepared statements.

Definition: Two different things share the name. SQL-level PREPARE name AS ...; EXECUTE name is a statement text; PgBouncer forwards it untouched, so it breaks. Protocol-level prepared statements use the extended query protocol messages Parse, Bind and Execute with a statement name, which is what most drivers (pgx, JDBC, libpq, PDO with native prepares) use under the hood. With max_prepared_statements non-zero, PgBouncer "tracks protocol-level named prepared statements", renames each unique query internally (PGBOUNCER_{unique_id}), and "transparently prepares the statement before executing it" on whichever server connection it lands on. The value is the size of an LRU cache per server connection; the 1.21.0 release notes say to set it non-zero (100 is "probably reasonable"), while the current config page lists 200 as the default, so check your version.

     Driver (pgx, named statement S_1)           PgBouncer                          Backend S1 / S2
1    Parse S_1 = "select * from orders where id=$1"  ─▶ maps S_1 -> PGBOUNCER_17    S1: Parse PGBOUNCER_17
2    Bind/Execute S_1  ──────────────────────▶   rewrite to PGBOUNCER_17            S1 executes
3    COMMIT; next transaction lands on S2        ...
4    Bind/Execute S_1  ──────────────────────▶   S2 lacks it → Parse PGBOUNCER_17 first, then Execute
5    -- before 1.21: ERROR: prepared statement "S_1" does not exist (26000)  or  already exists (42P05)
Client / driverWhat to set behind PgBouncer < 1.21Behind PgBouncer 1.21+ with max_prepared_statements
Go pgxdefault_query_exec_mode=simple_protocol (or exec)Default cache mode works; keep simple protocol if unsure
Go lib/pqbinary_parameters=yes for unnamed statementsNamed statements are tracked by PgBouncer
Laravel (PDO pgsql)'pooled' => true makes Laravel use emulated preparespooled still sensible
PHP PDO (non-Laravel)PDO::ATTR_EMULATE_PREPARES => trueNative prepares can work
Java JDBCprepareThreshold=0Works
Rails / ActiveRecordprepared_statements: falseWorks

Caveat from the PgBouncer docs: sharing prepared statements across clients means that if argument or result types change across executions PostgreSQL throws cached plan must not change result type. It most often appears during a DDL migration that adds a column; run RECONNECT on the admin console afterwards. SQL-level PREPARE, EXECUTE and DEALLOCATE are still forwarded as-is, except DEALLOCATE ALL and DISCARD ALL, which PgBouncer handles.

Real scenario: A Go service moves to PgBouncer and starts seeing intermittent prepared statement "stmtcache_..." does not exist; setting simple protocol (or upgrading PgBouncer to 1.21+ and max_prepared_statements) fixes it. The reverse trade-off: simple protocol re-parses every statement, so throughput is lower than with protocol-level prepares.

Fix / how to use it: see the pgxpool snippet's behindPooler branch and the Laravel pooled flag above.

The other poolers Good to know ​

PoolerEngineLanguage / shapeWhat it addsNotes
PgBouncerPostgreSQLC, single-threadedSmall, stable, three modes, online reconfigurationso_reuseport lets several instances share a port
pgcatPostgreSQLRustPooler and proxy with load balancing of reads across replicas, failover with health checks, mirroring, experimental shardingREADME: transaction mode does not support SET, prepared statements and advisory locks (use SET LOCAL, pg_advisory_xact_lock)
OdysseyPostgreSQLC, multi-threaded (Yandex)Pool per database-and-user pair with separate auth and mode; tracks transaction state and rolls back an abandoned transaction before reuseMulti-threaded vs PgBouncer's single thread
SupavisorPostgreSQLElixir, cloud-native, multi-tenantDynamic per-tenant pools across a cluster; README: proxies "millions of Postgres end-client connections"Developed in the Supabase GitHub organisation; targets serverless clients
Pgpool-IIPostgreSQLC middlewareConnection pooling plus replication, load balancing and failover; num_init_children × max_pool bounds its connectionsPool per child process, so more complex to size
ProxySQLMySQL / MariaDB (PostgreSQL support added)C++Multiplexing of frontend connections over backend ones, query rules, read/write split, query cacheMultiplexing is disabled while a transaction is active, after LOCK TABLES, GET_LOCK(), or queries containing @ variables
RDS ProxyRDS and Aurora (MySQL, PostgreSQL, SQL Server)ManagedPools and multiplexes; helps lambda-style connection storms and failoverConnection "pinning" when it cannot multiplex; on PostgreSQL setting a variable pins the session
Oracle DRCPOracleBuilt inPool of server processes shared among clientsServer-side, no extra proxy
MySQL Router / thread poolMySQLRouter; thread pool in Enterprise/PerconaRouting; fewer threads than connectionsNot a connection-multiplexing pooler like ProxySQL

The pinning idea is the same everywhere. ProxySQL disables multiplexing when a transaction is active or a session variable is set; RDS Proxy "pins" a connection so "each later transaction uses the same underlying database connection until the session ends" (DatabaseConnectionsCurrentlySessionPinned shows how often); PgBouncer in transaction mode has no pinning, it simply breaks what you were relying on. The cure is the same: keep session state out of request code.

Common misunderstanding: "Pgpool-II is PgBouncer with more features." Pgpool-II is middleware first (replication, load balancing, failover orchestration); its pooling holds backend connections per child process and does not multiplex transactions the way PgBouncer's transaction mode does.

Topologies ​

Pooling and read/write split Important ​

In plain words: Writes must go to the primary and reads may go to replicas; pools make that a routing decision per connection, and a per-connection decision is the wrong granularity for "read your own write".

Common misunderstanding: "The pooler can route a SELECT to a replica safely." Only if the app tolerates replica lag. A pooler cannot know that the SELECT follows an INSERT made a millisecond ago in the same request.

Definition: There are three places to split: the application (two named connections, e.g. Laravel read/write hosts), a pooler that understands routing (pgcat load balances reads across replicas; ProxySQL routes by query rules to hostgroups; Pgpool-II load-balances reads), or DNS/virtual IPs (one endpoint for the primary, one for the replica set). A transaction pool in front of two endpoints is two pools, not one.

     App (request)                      Pooler                     Primary          Replica (lag 80 ms)
1    INSERT order  ────────────────▶    write pool  ────────────▶  commit
2    SELECT order (same request) ───▶   read pool   ───────────────────────────────▶ not yet replicated
3    -- order not found: read-your-writes violated
4    fix: after a write, read from the primary for this request/session (Laravel `sticky`), or wait for the LSN
ApproachRouting decisionLag handlingNotes
Laravel read / write hosts + stickyApplication, per requeststicky => true sends reads after a write in the same request to the write connectionSimple, per-request granularity
Two PgBouncer endpoints (primary pool, replica pool)Application chooses the DSNApp decidesMost explicit; two pools to size
pgcatPooler load-balances reads across replicas and primary, health-checked failoverTolerates lag only if the app doesConfigured per pool
ProxySQL (MySQL)Query rules to hostgroups, multiplexingmax_replication_lag per serverWrites by default to the writer hostgroup
Pgpool-IIParses queries; load balancing with delay thresholdsdelay_thresholdHeavier, also handles failover
RDS ProxySeparate read-only endpoint for readersAurora replica lag appliesReader endpoint is a different pool

Real scenario: A product page reads from replicas; the "my orders" page after checkout reads from the primary. A failover moves the primary: pools that cached the old address keep failing until ConnMaxLifetime or the health check retires them. See Replication, Read Replicas & Failover for lag and failover.

Fix / how to use it:

php
// Laravel: read replicas with sticky reads
'pgsql' => [
    'read'  => ['host' => ['replica-1.internal', 'replica-2.internal']],
    'write' => ['host' => ['primary.internal']],
    'sticky' => true,
    // plus 'pooled' => true / 'direct' => [...] as above
],
go
// Go: two pools, chosen per call site
primary, replicas := mustOpen(primaryDSN, 10), mustOpen(replicaDSN, 20)
// writes and read-your-writes use primary; reports use replicas

Pooling across many services and replicas Important ​

In plain words: Every pool in every process spends from the same connection budget; nobody sees the total unless you add it up.

Common misunderstanding: "Each service sized its pool sensibly, so the total is fine." Ten sensible pools times ten services times four replicas is 400.

Definition: The budget is Σ (service instances × MaxOpenConns) plus rollout overlap, cron, migrations, admin and monitoring, and it must fit under max_connections − superuser_reserved_connections − reserved_connections. A pooler in front changes the budget from max_connections to default_pool_size × (number of database-user pairs), with max_db_connections and max_user_connections as hard caps, reserve_pool_size as the overflow, and max_client_conn as the ceiling of client sockets.

go

// Service is one deployable: how many instances, and each instance's pool cap.
type Service struct {
	Name      string
	Instances int
	MaxOpen   int
}

// Budget is the total server connections a fleet can ask for: instances times
// the per-process cap, summed over services.
func Budget(services []Service) int {
	total := 0
	for _, s := range services {
		total += s.Instances * s.MaxOpen
	}
	return total
}

// Fits reports whether the fleet fits in max_connections after reserving slots
// for superusers, replication, monitoring and migrations.
func Fits(services []Service, maxConnections, reserved int) bool {
	return Budget(services) <= maxConnections-reserved
}
ItemCountConnections
orders service4 replicas × 1040
billing service4 × 1040
reports service4 × 1040
rolling deploy overlap+50% of one service+20
migrations, cron, psql, monitoring10
Total direct150 against max_connections = 100
Via PgBouncer (default_pool_size = 20, 2 users)40 backends

Real scenario: Autoscaling doubles the orders service during a sale; with direct connections the extra pods push the total past max_connections, and the failure hits every service, including the ones that were fine. With PgBouncer the extra pods only add client sockets.

What prevents it:

ControlScope
Per-service role with CONNECTION LIMITOne service cannot starve the rest
One PgBouncer per database cluster, or sidecar per nodeShared default_pool_size, max_db_connections
max_user_connections (PgBouncer)Per user cap across pools
Autoscaler max replicas × pool sizeBudget check at deploy time (CI)
Separate pools for batch vs request trafficA slow job cannot starve checkout

Fix / how to use it: Put the arithmetic in CI: the sizing.Fits helper above fails the build when the fleet outgrows the budget.

Serverless connection storms Important ​

In plain words: Each serverless function instance is its own tiny process with its own pool, and a burst of requests creates thousands of them at the same time.

Common misunderstanding: "Serverless scales, so the database scales." The function tier scales to thousands of instances in seconds; the database still has max_connections and forks one process per connection.

Definition: With AWS Lambda, Cloud Run or edge runtimes, concurrency N means N instances, each opening its own connection(s), then freezing or dying without closing them. The pool inside an instance is pointless (size 1 is right), and a connection storm is the sudden opening of N × connections at once.

     Function platform                         Database
1    traffic spike: 800 concurrent invocations
2    each instance opens 1 connection  ──────▶ 800 backends requested
3    max_connections = 200 reached ─────────▶ FATAL: sorry, too many clients already
4    failed invocations retry (platform)  ───▶ second wave, more failures: a retry storm
5    frozen instances keep connections ─────▶ idle backends held until idle timeouts
ApproachHow it helpsCost
RDS Proxy (AWS)Pools and multiplexes connections between functions and RDS/Aurora; avoids pinning when you keep session state outExtra hop, cost, pinning rules
PgBouncer or Supavisor (hosted or self-managed)Transaction-mode pooler between functions and PostgreSQLOne more service to run
Provider pooled endpoint (managed Postgres)Built-in pooler (often PgBouncer or Supavisor) behind a second port or hostnameProvider specifics
HTTP or data-API driversNo TCP connection from the functionDifferent driver, limits
Limit function concurrencyHard cap on instancesThrottles traffic
Pool size 1 per instance, short idle timeoutEach instance holds at most one connectionCannot parallelise inside an instance

Real scenario: A marketing email triggers a webhook burst of 3000 requests in 5 seconds to a Lambda that opens a database connection; without a proxy the database refuses most, with retries making it worse. A Laravel Vapor or Octane app on serverless needs the pooled/direct split so migrations still work.

Fix / how to use it: Use a pooler or proxy, set pool size to 1 in functions, close or reuse connections outside the handler (initialise once per instance), cap platform concurrency, and set idle_session_timeout or the pooler's server_idle_timeout so frozen instances do not hold backends.

Health checks and failover Important ​

In plain words: A connection can be open and dead at the same time; a health check finds out before a user does.

Common misunderstanding: "TCP keepalive tells me the database is fine." It tells you the socket is up; a SELECT 1 through the pool tells you queries run, and neither says the endpoint is still the primary.

Definition: Health checks exist at three levels: the pool tests connections it is about to reuse (pgxpool HealthCheckPeriod, HikariCP keepaliveTime, PgBouncer server_check_query and server_check_delay), the load balancer or orchestrator tests the service (readiness endpoint with PingContext), and the pooler tests the backends (pgcat health checks, Pgpool-II health_check_period). After a failover, old connections point at a demoted primary; ConnMaxLifetime, a failed ping, or RECONNECT clears them.

CheckCostWhat it catchesPitfall
db.PingContext on /readyzOne round tripDatabase unreachableDo not use as liveness, or a DB outage restarts every pod
Pool validation before reusePer checkout, or every N secondsHalf-open connectionsAdds latency if done on every checkout
ConnMaxLifetime / MaxConnLifetimeNoneStale endpoints after failoverShort enough to react, long enough to avoid churn
SELECT pg_is_in_recovery()One round tripConnected to a replica when you want the primaryRun after reconnect
PgBouncer server_lifetime, server_idle_timeoutNoneBackends that live forever
TCP keepaliveNoneDead peers through NATSlow to notice

Real scenario: A failover switches the primary; for 10 minutes writes fail with cannot execute INSERT in a read-only transaction because pools still talk to the demoted node. pg_is_in_recovery() after connect, a short lifetime, and a pooler RECONNECT fix it.

Fix / how to use it: see the HealthHandler in the Go snippet above, HealthCheckPeriod in the pgxpool snippet, and in PgBouncer RECONNECT or PAUSE followed by RESUME on failover.

Monitoring ​

What to watch: pg_stat_activity, pool stats, waiting clients Must-know ​

In plain words: Three questions: how many connections exist and in what state, how many callers are waiting, and how long connections are held.

Common misunderstanding: "CPU and memory tell me if the pool is healthy." A saturated pool with idle database CPU looks healthy on the server dashboard.

Definition: pg_stat_activity has one row per backend; state is active, idle, idle in transaction, idle in transaction (aborted), fastpath function call or disabled, and wait_event_type/wait_event say what an active backend waits on (Lock, LWLock, IO, Client). PgBouncer's admin console shows SHOW POOLS (cl_active, cl_waiting, sv_active, sv_idle, sv_used, sv_tested, sv_login, maxwait), SHOW STATS (total_xact_count, total_wait_time, avg_wait_time), SHOW CLIENTS, SHOW SERVERS, SHOW CONFIG, SHOW LISTS, SHOW DATABASES. The maxwait description is the one to alert on: "If this starts increasing, then the current pool of servers does not handle requests quickly enough."

sql
-- connections by state and role
SELECT usename, state, count(*)
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY 1, 2 ORDER BY 3 DESC;

-- who is waiting on what
SELECT wait_event_type, wait_event, count(*)
FROM pg_stat_activity
WHERE state = 'active' AND wait_event IS NOT NULL
GROUP BY 1, 2 ORDER BY 3 DESC;

-- headroom
SELECT current_setting('max_connections')::int AS max_conn,
       current_setting('superuser_reserved_connections')::int AS reserved,
       count(*) AS used
FROM pg_stat_activity WHERE backend_type = 'client backend';
     pgbouncer=# SHOW POOLS;
      database | user | cl_active | cl_waiting | sv_active | sv_idle | sv_used | maxwait | pool_mode
      shop     | api  |       180 |         35 |        20 |       0 |       0 |       4 | transaction
     -- 35 clients waiting, maxwait 4 s, no idle server: the pool is too small or queries are too slow
MetricSourceAlert when
Active backends vs corespg_stat_activitySustained > 2 × cores
idle in transaction count and agepg_stat_activityAny older than a few seconds
Connection headroommax_connections minus usedBelow 10%
cl_waiting, maxwaitPgBouncercl_waiting > 0 for more than a few seconds
WaitCount, WaitDurationGo DBStatsRate rising
EmptyAcquireCount, CanceledAcquireCountpgxpool.StatRate rising
total_wait_timeSHOW STATSRising relative to total_query_time
DatabaseConnectionsCurrentlySessionPinnedCloudWatch (RDS Proxy)High vs total

Real scenario: Latency alarms fire; dashboards show database CPU at 20%. SHOW POOLS reveals cl_waiting = 40 and pg_stat_activity shows twelve idle in transaction sessions from the same deploy.

Fix / how to use it: Export db.Stats() or Stat() as metrics, scrape PgBouncer with an exporter that reads SHOW POOLS and SHOW STATS, and run the PoolStats command when paged.

php
<?php

// app/Console/Commands/PoolStats.php: who holds the server connections right now.
// It uses the direct connection, so it sees the real PostgreSQL backends and
// not the pooler's view. Run it as: php artisan db:pool-stats
namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

final class PoolStats extends Command
{
    protected $signature = 'db:pool-stats';

    protected $description = 'Show backends by state, the longest idle-in-transaction sessions and the headroom left';

    public function handle(): int
    {
        $db = DB::connection('pgsql::direct');

        $byState = $db->select(<<<'SQL'
            select coalesce(state, 'background') as state,
                   usename,
                   count(*) as backends,
                   max(now() - state_change) as longest_in_state
            from pg_stat_activity
            where backend_type = 'client backend'
            group by 1, 2
            order by backends desc
        SQL);
        $this->table(['state', 'role', 'backends', 'longest_in_state'], array_map(fn ($r) => (array) $r, $byState));

        $stuck = $db->select(<<<'SQL'
            select pid, usename, application_name, now() - xact_start as xact_age, left(query, 60) as last_query
            from pg_stat_activity
            where state in ('idle in transaction', 'idle in transaction (aborted)')
            order by xact_start
            limit 10
        SQL);
        $this->table(['pid', 'role', 'app', 'xact_age', 'last_query'], array_map(fn ($r) => (array) $r, $stuck));

        $head = $db->selectOne(<<<'SQL'
            select current_setting('max_connections')::int as max_connections,
                   current_setting('superuser_reserved_connections')::int as reserved,
                   (select count(*) from pg_stat_activity where backend_type = 'client backend') as used
        SQL);
        $left = $head->max_connections - $head->reserved - $head->used;
        $this->info("max_connections={$head->max_connections} reserved={$head->reserved} used={$head->used} headroom={$left}");

        return $left > 0 ? self::SUCCESS : self::FAILURE;
    }
}

Per-engine and per-product behaviour ​

ConcernPostgreSQLMySQL / InnoDBSQL ServerOracleMongoDBRedis
Server connectionProcessThreadWorker via schedulerDedicated or shared serverThreadSocket on single-threaded loop
Default capmax_connections 100max_connections 15132767 (user connections)PROCESSES / SESSIONS65536 default maxIncomingConnections (depends on OS limits)maxclients 10000
Built-in poolerNoneThread pool (Enterprise, Percona)Client-side pool in driverDRCPDriver poolNone
External poolersPgBouncer, pgcat, Odyssey, Supavisor, Pgpool-II, RDS ProxyProxySQL, MySQL Router, RDS ProxyRDS Proxy (RDS SQL Server)CMAN-TDM, DRCPmongosEnvoy proxy, Twemproxy
Client pool settingspool size, lifetime, idlesameMax Pool Size, Min Pool Size, Connection LifetimeUCP, ODP.NET poolingmaxPoolSize, waitQueueTimeoutMS, maxIdleTimeMSclient-specific
Session state to avoid behind a poolerSET, LISTEN, PREPARE, advisory locks, temp tablesSET, user variables (@), GET_LOCK, temp tablesSET, #temp tables, app rolespackage state, ALTER SESSIONcursors, transactions (sessions)SELECT n, MULTI, WATCH, SUBSCRIBE
Cap error53300 too many clients1040 Too many connections17809ORA-00018connection refusedmax number of clients reached

PostgreSQL, MySQL, SQL Server and Oracle all work behind a client-side pool; the difference is that on PostgreSQL the server-side connection cost is highest, so an external pooler matters the most there. SQLite has no server connections; its pool exists to bound writers (one writer at a time in WAL mode). CockroachDB and Spanner clients use ordinary pooled drivers with a small multiple of vCPUs.

Mechanics ​

PgBouncer knobs and states Important ​

KnobDefaultMeaning
pool_modesessionsession, transaction or statement
max_client_conn100Client sockets allowed; raise the OS file-descriptor limit with it
default_pool_size20Server connections per (database, user) pair
min_pool_size0Keep this many warm
reserve_pool_size / reserve_pool_timeout0 / 5 sExtra connections after a client waited this long
max_db_connectionsunsetServer connections per database regardless of user
max_user_connectionsunsetServer connections per user
server_lifetime3600 sClose server connections after this age
server_idle_timeout600 sClose idle server connections
server_reset_query / server_reset_query_alwaysDISCARD ALL / offCleanup on release (session mode)
server_check_query / server_check_delayLiveness check before reuse after idle
query_wait_timeout120 sDisconnect a client that waits this long for a server connection
client_idle_timeout0 (off)Close idle clients
idle_transaction_timeout0 (off)Disconnect clients idle inside a transaction
max_prepared_statements200 (current docs)Protocol-level prepared statement tracking per server connection
ignore_startup_parameters / track_extra_parametersWhich unknown startup parameters to ignore or track
so_reuseportoffSeveral PgBouncer processes on one port to use more cores

Admin console commands: SHOW POOLS, SHOW STATS, SHOW CLIENTS, SHOW SERVERS, SHOW CONFIG, RELOAD (re-read the config), PAUSE (wait for clients to finish and hold new queries, useful for a primary switch), RESUME, RECONNECT (close server connections as they become idle and re-prepare; use after DDL), KILL db, KILL_CLIENT id, SHUTDOWN WAIT_FOR_CLIENTS (graceful drain).

The max_client_conn arithmetic. PgBouncer's docs: the theoretical maximum of file descriptors is max_client_conn + (max pool_size × total databases × total users). Set ulimit -n above it.

     Client                         PgBouncer                                Reason
1    connect, no free server conn   queue in cl_waiting                      pool at default_pool_size
2    5 s (reserve_pool_timeout)     use a reserve_pool_size connection       burst absorbed
3    120 s without service          disconnect client                        query_wait_timeout
4    server down, retries           clients wait in queue                    server_login_retry, or reject

Error codes and messages you will see Must-know ​

ErrorWhereMeaningAction
FATAL: sorry, too many clients already (53300)PostgreSQLmax_connections reachedPool or pooler; lower pool sizes
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attributePostgreSQLOnly reserved slots leftSame; keep admin slots
FATAL: too many connections for role "x" (53300)PostgreSQLCONNECTION LIMIT of the roleRaise or fix the leak
FATAL: terminating connection due to idle-in-transaction timeout (25P03)PostgreSQLidle_in_transaction_session_timeout firedShorten the transaction
prepared statement "S_1" does not exist (26000)PostgreSQL via poolerNamed statement on another backendSimple protocol or max_prepared_statements
prepared statement "S_1" already exists (42P05)PostgreSQL via poolerSame cause, other directionSame
cached plan must not change result typePostgreSQLSchema changed under a cached planRECONNECT after DDL
context deadline exceededGoDeadline hit, possibly while waiting for a connectionCheck WaitDuration
sql: database is closed, driver: bad connectionGoPool closed or connection brokenLifetime settings, retry
SQLSTATE[08006]PHP PDOConnection failure including too many clientsPool, retry with backoff
no more connections allowed (max_client_conn)PgBouncerClient socket cap reachedRaise max_client_conn, check fds
query_wait_timeoutPgBouncerWaited too long for a server connectionPool too small or queries too slow
1040 Too many connections, 1226MySQLServer or user capProxySQL or lower pools

Solving the classic problems ​

Too many connections from a fleet Must-know ​

SolutionHowAdvantageCost or limitation
Smaller app poolsMaxOpenConns from the budgetFree, immediateNeeds shorter transactions
PgBouncer transaction modeMany clients, few serversLarge ratioSession features break
Raise max_connectionsConfig and restartQuick reliefMore memory and snapshot work; not a fix
Per-role limitsCONNECTION LIMITContains a noisy neighbourNeeds roles per workload
Read replicas for readersSeparate poolSplits loadLag
sql
-- the minimal, durable fix: roles with limits and a pooler-friendly timeout
ALTER ROLE api SET idle_in_transaction_session_timeout = '15s';
ALTER ROLE api CONNECTION LIMIT 60;

Go: SetMaxOpenConns from the budget (see sizing.Budget); Laravel: 'pooled' => true and DB_PORT=6432, as in the config above.

Exhaustion under a slow dependency Must-know ​

SolutionHowAdvantageCost
Request deadlinecontext.WithTimeout before the queryBounded waitCallers must handle 503
No I/O inside a transactionCall APIs before BEGIN or after COMMIT (use an outbox)Short hold timeRestructuring
Separate poolsRequest vs batchIsolationMore pools to size
Bulkhead / circuit breakerCap concurrent DB callersProtects the poolExtra code
statement_timeout, lock_timeoutPer roleBounds the damageNeeds retry logic
Backoff and jitter on retryClientStops retry stormsLatency
go
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
err := db.QueryRowContext(ctx, "select ...").Scan(&v)
if errors.Is(err, context.DeadlineExceeded) { http.Error(w, "busy", http.StatusServiceUnavailable) }
php
// Laravel: fail fast and surface a 503 instead of queueing
DB::statement("SET LOCAL lock_timeout = '2s'"); // inside DB::transaction

Session features that must survive a pooler Important ​

Use SET LOCAL and pg_advisory_xact_lock, ALTER ROLE ... SET, or route those code paths to a direct connection (pgsql::direct). The code is in What breaks in transaction mode.

Retry and failure handling ​

ErrorMeaningRetry?
53300 too_many_connectionsCapacityYes, with backoff and jitter; never in a tight loop
57P01 admin_shutdown, 08006, 08003Connection lost (failover, restart)Yes, on a new connection; only idempotent work
25P03 idle_in_transaction_session_timeoutYou held a transaction idleFix the code; retry the whole transaction
40001, 40P01Serialization or deadlockYes (see Isolation Levels)
context deadline exceeded waiting for a connectionPool saturatedShed load; do not retry immediately
go
// Go: retry only connection errors, with exponential backoff and jitter
for attempt := 0; attempt < 4; attempt++ {
    err := doWork(ctx)
    if err == nil || !isConnectionError(err) { return err }
    time.Sleep(time.Duration(1<<attempt)*50*time.Millisecond + time.Duration(rand.Intn(50))*time.Millisecond)
}
php
// Laravel: DB::transaction($callback, attempts: 3) retries deadlocks; for connection loss
// Laravel already reconnects once when it detects a lost connection (causedByLostConnection)

Choosing a setup ​

SituationRecommendedExtra techniqueReason
One app, one database, low trafficApp pool only (5 to 10)ConnMaxLifetime, deadline per requestSimplest correct setup
Many app instances or PHP-FPMPgBouncer, transaction modemax_prepared_statements, SET LOCAL, pooled in LaravelLarge client:server ratio
Legacy app needing SET, LISTEN, advisory locksPgBouncer session mode, or directDedicated pool per featureCompatibility over ratio
Serverless functionsRDS Proxy, Supavisor, or provider poolerPool size 1, cap concurrencyAbsorbs connection storms
Read-heavy with replicasSeparate read pool, sticky writesLag-aware routingOffload primary
Multi-tenant with SET search_pathTransaction mode with SET LOCAL, or schema-qualified namesPer-tenant rolesAvoids leaking state
Batch/ETL jobsOwn role, own small pool, direct connectionCONNECTION LIMIT, statement_timeoutCannot starve requests
MySQL fleetProxySQL multiplexingRead/write split rulesEquivalent of PgBouncer
Managed AWS databaseRDS ProxyMinimise pinningPooling plus failover handling
Needs sharded routing or read balancing in the poolerpgcat or Pgpool-IITest thoroughlyMore features, more risk

In architecture: from a single process to a distributed system ​

Pooling is the part of a design that turns "how many callers" into "how many database connections". Every architectural step multiplies the callers; the pooling design decides whether the database sees the multiplication.

Monolith: one process, one database ​

One process, one *sql.DB (or one PHP-FPM pool with PgBouncer). The simplest correct usage: one pool created in main, MaxOpenConns from the budget, ConnMaxLifetime set, a deadline on every request, /healthz that reports db.Stats(). Example: a Go monolith on two hosts with MaxOpenConns = 10 uses at most 20 connections on a database that tolerates about 20 active; no external pooler is needed. For a Laravel monolith under PHP-FPM with 40 workers on one host, a local PgBouncer in transaction mode turns 40 backends into about 10.

Modular monolith and multiple databases ​

Modules own schemas or databases. Each (database, user) pair is its own pool in PgBouncer (default_pool_size applies per pair), so adding a database to the same server adds pools and therefore connections. Give each module a role with CONNECTION LIMIT, and keep batch modules away from request modules with separate roles. In Laravel, each module may use a named connection (pgsql, reporting), each with its own pooled and direct settings; a module that needs LISTEN gets a session-mode or direct connection. Example: a billing module reading a ledger schema and an analytics module reading replicas use two pools with separate budgets.

Microservices: per-service pools times replicas ​

Each service owns a database (or schema) and its pool. A shared PostgreSQL instance serves several services, so the budget is the sum across services (the sizing.Fits helper). The failure mode is cross-service: one service's slow query exhausts its own pool and, if the database is shared, may starve the others via lock waits and CPU. Containment: separate roles with limits, a pooler with max_user_connections, per-service deadlines, and bulkheads so a database slowdown does not spread through synchronous calls.

     checkout (4 pods)            billing (4 pods)              inventory (4 pods)        PgBouncer             PostgreSQL
1    pool 10 each = 40 clients    pool 10 each = 40            pool 10 each = 40          120 clients in        40 backends
2    billing starts a slow report; its pool saturates: cl_waiting rises for the billing role only
3    checkout and inventory unaffected: separate roles, separate pools, max_user_connections per role
4    -- with a shared pool and no limits, billing's report could hold all 100 backends

Across service boundaries a connection cannot span a call: a database transaction does not include another service's database, so sagas, outbox and idempotency replace it (see Distributed SQL, Consensus & 2PC). The pooling rule that matches is: never hold a connection or transaction while calling another service; call first, then open a short transaction, or write to an outbox and publish after commit.

Distributed data: replicas, caches and failover ​

Replicas. Each replica endpoint is another pool. Reads that must see their own writes need the primary or a lag-aware route; see Replication, Read Replicas & Failover. After failover, pools hold connections to the demoted node until lifetime or health checks retire them; a pooler RECONNECT or PAUSE/RESUME makes the switch orderly.

Caches. A cache in front of the database (see Redis) reduces λ in Little's law, which shrinks the pool you need; a cache stampede does the opposite and produces a burst that exhausts the pool, so use request coalescing or locks around the refill.

Sharded and distributed SQL. With sharding (Citus, Vitess, application-level), every shard has its own pool: MaxOpenConns × shards per process, which grows fast. Poolers that understand sharding (pgcat experimentally, Pgpool-II, ProxySQL for MySQL) move this out of the app. CockroachDB and Spanner clients keep a pool per node or per endpoint with small sizes; see Distributed SQL, Consensus & 2PC.

Multi-region. Cross-region latency raises W (hold time) for the same query; Little's law says the pool must grow in proportion, or the app should keep the transaction local to the region.

Scaling path: 1×, 10×, 100× ​

ScaleShapePooling design
1× (one host, hundreds of req/s)One process, one databaseApp pool of 5 to 20, lifetime and deadline, no external pooler
10× (a dozen instances)Several hosts or PHP-FPM fleetPgBouncer transaction mode, max_prepared_statements, SET LOCAL, Laravel pooled/direct, per-role limits
100× (many services, serverless)Autoscaled fleets, replicas, regionsDedicated pooler tier or managed proxy (RDS Proxy, Supavisor), pooler per region, pool budgets enforced in CI, read pool vs write pool, batch isolation, connection-storm protection
BeyondSharding, distributed SQLPer-shard pools, routing poolers; see Storage & Data Scaling

Lab ​

Setup: a PostgreSQL limited to four CPUs and max_connections = 100, PgBouncer in transaction mode with default_pool_size = 8, and the load tool from the snippet. The PgBouncer image and its environment variable names are those of edoburu/pgbouncer; if you use another image, mount your own pgbouncer.ini instead.

yaml
# docker-compose.yml
services:
  pg:
    image: postgres:17
    environment: { POSTGRES_PASSWORD: secret, POSTGRES_USER: app, POSTGRES_DB: lab }
    command: ["postgres", "-c", "max_connections=100", "-c", "shared_preload_libraries=pg_stat_statements"]
    cpus: 4
    ports: ["5432:5432"]
  bouncer:
    image: edoburu/pgbouncer
    environment:
      DB_HOST: pg
      DB_USER: app
      DB_PASSWORD: secret
      DB_NAME: lab
      POOL_MODE: transaction
      DEFAULT_POOL_SIZE: "8"
      MAX_CLIENT_CONN: "1000"
      AUTH_TYPE: scram-sha-256
      ADMIN_USERS: app
    ports: ["6432:5432"]
    depends_on: [pg]

The load tool (go run . in this directory; it takes -clients, -pool, -requests, -hold-ms, -rows, -timeout):

go
// Command lab drives a pool with many concurrent clients and prints latency
// percentiles and pool wait statistics. Run it against PostgreSQL directly and
// against PgBouncer with the same flags and compare.
//
//	DATABASE_URL='postgres://app:secret@127.0.0.1:5432/lab' go run . -clients 500 -pool 90
//
// Behind PgBouncer in transaction mode add default_query_exec_mode=simple_protocol
// to the DSN so the driver does not rely on per-connection prepared statements.
package main

import (
	"context"
	"database/sql"
	"flag"
	"fmt"
	"log"
	"os"
	"slices"
	"sync"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

func main() {
	clients := flag.Int("clients", 500, "concurrent client goroutines")
	pool := flag.Int("pool", 10, "SetMaxOpenConns for this process (0 = unlimited)")
	requests := flag.Int("requests", 20, "requests per client")
	holdMs := flag.Int("hold-ms", 0, "if > 0, run pg_sleep for this many ms (holds a connection, no CPU) instead of the CPU query")
	rows := flag.Int("rows", 300000, "rows summed by the CPU query")
	timeout := flag.Duration("timeout", 5*time.Second, "per-request deadline, including the wait for a connection")
	flag.Parse()

	dsn := os.Getenv("DATABASE_URL")
	if dsn == "" {
		log.Fatal("set DATABASE_URL")
	}

	db, err := sql.Open("pgx", dsn)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()
	db.SetMaxOpenConns(*pool)
	db.SetMaxIdleConns(*pool)

	var (
		mu        sync.Mutex
		latencies []time.Duration
		failures  int
		wg        sync.WaitGroup
	)
	start := time.Now()
	for c := 0; c < *clients; c++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for i := 0; i < *requests; i++ {
				ctx, cancel := context.WithTimeout(context.Background(), *timeout)
				t0 := time.Now()
				var err error
				if *holdMs > 0 {
					_, err = db.ExecContext(ctx, "select pg_sleep($1)", float64(*holdMs)/1000)
				} else {
					_, err = db.ExecContext(ctx, "select sum(i) from generate_series(1, $1::int) i", *rows)
				}
				d := time.Since(t0)
				cancel()

				mu.Lock()
				if err != nil {
					failures++
				} else {
					latencies = append(latencies, d)
				}
				mu.Unlock()
			}
		}()
	}
	wg.Wait()
	elapsed := time.Since(start)

	slices.Sort(latencies)
	pct := func(p float64) time.Duration {
		if len(latencies) == 0 {
			return 0
		}
		return latencies[int(float64(len(latencies)-1)*p)]
	}
	s := db.Stats()
	fmt.Printf("ok=%d failed=%d elapsed=%s throughput=%.0f/s\n",
		len(latencies), failures, elapsed.Round(time.Millisecond), float64(len(latencies))/elapsed.Seconds())
	fmt.Printf("p50=%s p95=%s p99=%s\n", pct(0.50), pct(0.95), pct(0.99))
	fmt.Printf("pool: max_open=%d open=%d in_use=%d wait_count=%d wait_duration=%s\n",
		s.MaxOpenConnections, s.OpenConnections, s.InUse, s.WaitCount, s.WaitDuration.Round(time.Millisecond))
}

Run docker compose up -d and create the table used by experiment 2: CREATE TABLE orders (id int primary key, status text); INSERT INTO orders SELECT g, 'new' FROM generate_series(1, 1000) g;. Then in a second terminal keep a monitor open: docker compose exec pg psql -U app lab, running SELECT state, count(*) FROM pg_stat_activity WHERE backend_type = 'client backend' GROUP BY 1; every second (\watch 1).

Experiment 1: exhaust a pool and watch the waits.

# terminal A (load), pool of 5, 20 clients each holding a connection 500 ms, 1 s deadline
DATABASE_URL='postgres://app:secret@127.0.0.1:5432/lab' go run . -clients 20 -pool 5 -hold-ms 500 -requests 4 -timeout 1s
# expected (approximate):
#   ok < 80, failed > 0 (context deadline exceeded: requests that waited the full 1 s for a connection)
#   pool: max_open=5 ... wait_count in the tens, wait_duration in the tens of seconds
# terminal B (monitor): active = 5 for the whole run, never more; the database is not busy: pg_sleep uses no CPU

Little's law predicts it: 20 clients arrive at once and each holds a connection 0.5 s, so a pool of 5 serves 10 requests/second while 20 clients ask for 40/second.

Experiment 2: a leaked transaction, and the timeout that ends it.

-- terminal A
BEGIN; UPDATE orders SET status = 'x' WHERE id = 1;   -- never commit; leave the terminal idle
-- terminal B
SELECT pid, state, now() - xact_start AS age FROM pg_stat_activity WHERE state LIKE 'idle in tr%';
--  state = idle in transaction, age growing
ALTER ROLE app SET idle_in_transaction_session_timeout = '10s';   -- applies to new sessions
-- reconnect terminal A, BEGIN again, wait 10 s:
-- FATAL:  terminating connection due to idle-in-transaction timeout

Experiment 3: direct, 500 clients.

# 500 pooled connections direct to PostgreSQL: the server refuses most of them
DATABASE_URL='postgres://app:secret@127.0.0.1:5432/lab' go run . -clients 500 -pool 500 -requests 20
# expected: ok=... failed=thousands   FATAL: sorry, too many clients already (SQLSTATE 53300)

# a reasonable direct pool: the connection budget (about 90) fits
DATABASE_URL='postgres://app:secret@127.0.0.1:5432/lab' go run . -clients 500 -pool 90 -requests 20
# expected: ok=10000 failed=0  p50 high (many backends fight for 4 CPUs), p99 high, throughput = X/s

Experiment 4: the same 500 clients through PgBouncer.

DATABASE_URL='postgres://app:secret@127.0.0.1:6432/lab?default_query_exec_mode=simple_protocol' go run . -clients 500 -pool 500 -requests 20
# expected: ok=10000 failed=0; PostgreSQL shows 8 backends, not 90; throughput similar or better, p99 lower
# terminal C: docker compose exec bouncer psql -p 5432 -U app pgbouncer -c 'SHOW POOLS;'   -- cl_waiting > 0, sv_active = 8, maxwait small

Typical result shape (yours will differ by hardware): with a CPU-bound query, 90 backends on 4 CPUs give high latency from contention while 8 backends give lower p50 and p99 at about the same or higher throughput. That is the HikariCP axiom measured: the waiting moved from the database into the pooler's queue.

Experiment 5: what transaction mode breaks. Set DEFAULT_POOL_SIZE: "1" and restart the bouncer, then:

# session 1                                          # session 2 (same user and database)
psql -p 6432 -U app lab                              psql -p 6432 -U app lab
SET statement_timeout = '1s';                        SHOW statement_timeout;
-- leaves the server connection with 1s              -- 1s: your setting leaked into another client's session
PREPARE q AS SELECT 1;  EXECUTE q;                   EXECUTE q;
-- works while the same server connection is held    -- ERROR: prepared statement "q" does not exist (SQL-level PREPARE is forwarded as-is)

Restore the pool size afterwards, and try SET LOCAL inside BEGIN ... COMMIT to see it stay contained.

Common misconceptions ​

BeliefReality
A bigger pool means more throughputPast the knee, throughput falls and latency rises; keep it small and let callers wait
Pool exhaustion means the database is overloadedThe database is usually idle; a few slow callers hold all the connections
MaxOpenConns limits my database loadIt limits one process; the fleet total is instances × cap
PgBouncer is transparentOnly in session mode; transaction mode removes session state
Prepared statements cannot work with PgBouncerProtocol-level ones can since 1.21.0 with max_prepared_statements; SQL-level PREPARE still cannot
Persistent PDO connections are a poolThey are one cached connection per worker, with no limit control, and leak session state
idle connections are freeEach holds a backend process and memory; idle in transaction also holds locks and blocks vacuum
Raising max_connections fixes too many clientsIt raises the memory and snapshot cost and needs a restart; pooling or smaller pools fix the cause
sql.Open opens a connectionIt validates arguments; the first query or Ping connects
Serverless scales the database tooFunction concurrency scales; database connections do not, without a proxy
DB::disconnect() frees a backend behind PgBouncerIn transaction mode it frees only the client socket; the backend was already free
A health check proves the primary is the primaryA ping proves a connection works; check pg_is_in_recovery() after failover

Cheat sheet ​

TopicWhat to remember
Why poolSetup cost is high, and the database needs a concurrency cap
PostgreSQL connectionA forked process plus snapshot work; GetSnapshotData() grew with connection count until PostgreSQL 14
Starting size(cores × 2) + spindles active connections; load test to find the knee
Little's lawL = λ × W: pool ≈ requests/s × hold time × 2 for headroom
Fleet budgetΣ instances × MaxOpenConns ≤ max_connections − reserved
Go knobsSetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTime; Stats() for WaitCount
pgxpoolMaxConns (default max(4, NumCPU)), MaxConnLifetimeJitter, HealthCheckPeriod, AfterRelease
Acquire timeoutPass a context with a deadline; the wait for a connection ends with it
Exhaustionin_use == max, rising wait counts, low database CPU; fix hold time first
Leaksdefer rows.Close(), defer tx.Rollback(); idle_in_transaction_session_timeout
PHP-FPMOne connection per busy worker; hosts × pm.max_children is the worst case
OctaneOne connection per worker, kept across requests; --max-requests recycles
Laravel 13pooled (emulated prepares) plus direct (migrations, pgsql::direct)
PgBouncer modessession (all features), transaction (no SET/LISTEN/PREPARE/session advisory locks), statement (no multi-statement)
Prepared statementsProtocol-level work with max_prepared_statements (1.21+); SQL-level do not
Monitoringpg_stat_activity states, SHOW POOLS (cl_waiting, maxwait), DBStats.WaitCount
LimitsCONNECTION LIMIT per role/database; max_user_connections, max_db_connections in PgBouncer

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does an idle PostgreSQL connection still cost something, and why did it cost more before PostgreSQL 14? Important ​

Answer

Answer: Each connection is a forked backend process with private memory (catalog and plan caches). Before PostgreSQL 14, GetSnapshotData() scanned all connections, so many idle ones slowed the active ones. Since 14 the snapshot cost is much lower, but the process and memory remain.

2 — An 8-core server with all data in cache: what is the starting pool for active connections, and what do you do next? Must-know ​

Answer

Answer: (8 × 2) + 0 = 16. Treat it as a starting point and load test with real queries to find the knee.

3 — A service handles 1500 req/s, and each holds a connection for 4 ms on average. What pool do you need? Must-know ​

Answer

Answer: Little's law: L = 1500 × 0.004 = 6 in use on average; with headroom of 2 to 3 the pool is about 12 to 18. Per process, divide by the number of instances.

4 — What does SetMaxOpenConns(0) do, and what is the default MaxIdleConns? Must-know ​

Answer

Answer: Zero means unlimited open connections, which is the default; MaxIdleConns defaults to 2 (and is lowered to MaxOpenConns if that is smaller).

5 — How do you set an acquisition timeout with database/sql? Important ​

Answer

Answer: Pass a context with a deadline to the query method. The wait for a free connection ends on release or ctx.Done(), so the deadline is the timeout. pgxpool.Acquire(ctx) works the same way.

6 — Which three symptoms identify pool exhaustion rather than a slow database? Must-know ​

Answer

Answer: InUse == MaxOpenConnections with rising WaitCount/WaitDuration (or cl_waiting > 0 in PgBouncer), low database CPU, and many sessions idle in transaction or waiting on a lock in pg_stat_activity.

7 — Which PgBouncer pooling mode do you use for a normal web app, and which features break? Important ​

Answer

Answer: Transaction mode. SET/RESET, LISTEN, SQL-level PREPARE/DEALLOCATE, session-level advisory locks, WITH HOLD cursors and PRESERVE ROWS temp tables break; use SET LOCAL, pg_advisory_xact_lock, protocol-level prepares and a direct connection for the rest.

8 — Why do prepared statements fail behind PgBouncer before 1.21, and what changed? Good to know ​

Answer

Answer: A named statement exists on one backend, and the next transaction may use another. PgBouncer 1.21.0 added tracking of protocol-level named statements: with max_prepared_statements non-zero it re-prepares them on whichever backend is assigned.

9 — In Laravel 13, what do pooled and direct do? Good to know ​

Answer

Answer: pooled turns on emulated prepares for the pooled connection; direct describes the endpoint used for migrations, schema dumps, db:wipe, db:show, db:table and DB::connection('pgsql::direct').

10 — Why does max_connections = 1000 not solve too many clients already? Must-know ​

Answer

Answer: It increases per-connection memory and snapshot overhead and needs a restart; the cause is too many callers each holding a backend. Reduce pool sizes or add a pooler.

11 — What does idle_in_transaction_session_timeout protect, and where do you set it? Important ​

Answer

Answer: It terminates sessions that stay idle inside an open transaction, which hold locks and block vacuum. Set it with ALTER ROLE ... SET per workload, or server-wide, and mirror it with PgBouncer's idle_transaction_timeout.

12 — A serverless function opens one connection per invocation and the database falls over during a burst. What changes? Must-know ​

Answer

Answer: Put a pooler or proxy (RDS Proxy, PgBouncer, Supavisor) in front, use pool size 1 in the function, cap function concurrency, and set idle timeouts so frozen instances do not hold backends.

Glossary ​

TermMeaning
Connection poolA set of open connections lent to callers and returned for reuse
Backend (PostgreSQL)The server process that serves one client connection
fork()The system call the postmaster uses to start a backend
GetSnapshotData()PostgreSQL function that builds a transaction's snapshot; its cost grew with connection count
SnapshotThe set of transactions a query may see; each transaction takes one
max_connectionsPostgreSQL setting for the maximum concurrent connections (default 100)
superuser_reserved_connectionsSlots kept for superusers (default 3)
reserved_connectionsSlots kept for roles with pg_use_reserved_connections (PostgreSQL 16 and later)
CONNECTION LIMITPer-role or per-database cap in CREATE/ALTER ROLE and ALTER DATABASE
KneeThe concurrency point after which throughput falls
Little's lawL = λ × W: average items in a system equal arrival rate times time in the system
Hold timeTime between acquiring and releasing a connection
HikariCPJava JDBC pool whose wiki holds the pool sizing axiom
SetMaxOpenConnsGo cap on open connections in *sql.DB
SetMaxIdleConnsGo number of idle connections kept
SetConnMaxLifetimeGo maximum age of a connection
SetConnMaxIdleTimeGo maximum idle time of a connection
DBStatsGo pool statistics (WaitCount, WaitDuration, InUse, Idle)
pgxpoolpgx's own connection pool with MaxConns, MinConns, lifetime, jitter and health check
Acquisition timeoutDeadline for obtaining a connection from the pool
Pool exhaustionAll connections in use, new callers wait
Connection leakA connection checked out and never returned
Idle in transactionA session inside a transaction doing nothing; holds locks and blocks vacuum
idle_in_transaction_session_timeoutPostgreSQL setting that ends such sessions
idle_session_timeoutPostgreSQL setting that ends idle sessions outside a transaction
statement_timeout, lock_timeoutPostgreSQL limits for query time and lock wait
PHP-FPMPHP process manager; one request per worker; pm.max_children caps workers
Persistent connectionPDO connection kept by the worker after the request (PDO::ATTR_PERSISTENT)
OctaneLaravel server that keeps the application in memory (FrankenPHP, Swoole, RoadRunner)
SwoolePHP extension for coroutine-based servers, used by Octane
FrankenPHPPHP application server written in Go, used by Octane
pooled / directLaravel 13 PostgreSQL options for the pooler endpoint and the direct endpoint
PgBouncerLightweight PostgreSQL connection pooler
Session poolingServer connection held for the whole client session
Transaction poolingServer connection held for one transaction
Statement poolingServer connection held for one statement
server_reset_queryQuery run on a server connection when it returns to the pool (DISCARD ALL)
max_prepared_statementsPgBouncer 1.21+ setting for tracking protocol-level prepared statements
default_pool_sizePgBouncer server connections per (database, user)
reserve_pool_sizeExtra PgBouncer connections after waiting reserve_pool_timeout
query_wait_timeoutPgBouncer limit on waiting for a server connection
cl_waiting, maxwaitSHOW POOLS columns for waiting clients and longest wait
PinningA proxy tying a client to one backend because of session state (RDS Proxy)
MultiplexingMany client connections sharing few server connections (ProxySQL, RDS Proxy)
pgcatRust PostgreSQL pooler with load balancing, failover and mirroring
OdysseyMulti-threaded PostgreSQL pooler from Yandex
SupavisorElixir multi-tenant PostgreSQL pooler
ProxySQLProxy and pooler for MySQL and MariaDB
RDS ProxyAWS managed database proxy and pooler
Pgpool-IIMiddleware with pooling, load balancing, replication and failover
DRCPOracle Database Resident Connection Pooling
Read/write splitSending writes to the primary and reads to replicas
Connection stormMany instances opening connections at once
Health checkA periodic test that a connection or backend works

References ​

See also: Locks & Concurrency, Replication, Read Replicas & Failover, MVCC, VACUUM & Bloat, Isolation Levels.

Built by Morteza Negahi