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 for | Go to |
|---|---|
| The numbers to memorise | Everything in one minute |
| Why pools exist and the trade-off | Why connection pooling exists |
| What one PostgreSQL connection costs | The cost of a connection |
max_connections, reserved slots, CONNECTION LIMIT | max_connections and per-role limits |
| Pool size formula, HikariCP axiom, Little's law | Pool sizing |
SetMaxOpenConns, SetConnMaxLifetime, pgxpool | Application pools in Go |
| Acquire timeouts, exhaustion symptoms, leaks | Exhaustion and leaks |
| PHP-FPM, persistent connections, Octane | PHP: one connection per worker |
pooled vs direct in Laravel 13 | Laravel 13 pooled and direct |
| Session, transaction, statement mode | PgBouncer pooling modes |
| What breaks in transaction mode | What breaks |
| Prepared statements behind a pooler | Prepared statements |
| pgcat, Odyssey, Supavisor, ProxySQL, RDS Proxy, Pgpool-II | The other poolers |
| Read/write split, many services, serverless | Topologies |
| Monitoring and timeouts | Monitoring |
| Every PgBouncer knob and error | Mechanics |
| Code for the classic problems | Solving the classic problems |
| Which setup for which workload | Choosing a setup |
| Monolith to distributed | In architecture |
| Reproduce exhaustion and the PgBouncer comparison | Lab |
Everything in one minute
The layers. Every layer in the path can pool; each multiplies or divides the connection count.
| Layer | Example | What a "connection" is there | Who pays |
|---|---|---|---|
| Application pool | Go *sql.DB, pgxpool.Pool, HikariCP, PDO | A socket plus a server backend | Each process |
| External pooler | PgBouncer, pgcat, Odyssey, Supavisor, RDS Proxy | A cheap client socket in, a shared server connection out | One small service |
| Database | PostgreSQL max_connections | A forked backend process | The server (memory, snapshots) |
The numbers.
| Rule | Value | Source of the number |
|---|---|---|
| Starting active connections | (core_count * 2) + effective_spindle_count | PostgreSQL wiki, HikariCP wiki |
| Average connections in use | L = λ × W (Little's law) | Queueing theory |
| Fleet budget | instances × MaxOpenConns summed over services must fit max_connections minus reserved | Arithmetic |
| PgBouncer client cost | about 2 kB per connection by default | PgBouncer features page |
PostgreSQL default max_connections | 100 | PostgreSQL docs |
Go database/sql defaults | MaxOpenConns unlimited, MaxIdleConns 2 | Go package docs |
| PgBouncer defaults | default_pool_size 20, max_client_conn 100, query_wait_timeout 120 s | PgBouncer config |
The three PgBouncer modes.
| Mode | Server connection returns to the pool | Breaks | Typical use |
|---|---|---|---|
| session | When the client disconnects | Nothing | Legacy apps, LISTEN, long sessions |
| transaction | When the transaction ends | SET, LISTEN, PREPARE, session advisory locks, WITH HOLD cursors, PRESERVE ROWS temp tables | Web apps with short transactions |
| statement | After each statement | Everything multi-statement | PL/Proxy style autocommit only |
The three things to do.
| Situation | Do this |
|---|---|
| Many small app instances | Give each instance a small pool (5 to 20) and put PgBouncer in transaction mode in front |
| Latency spikes under load | Look at wait counts first (Go WaitCount, PgBouncer cl_waiting), then at the slow query holding connections |
Migrations, LISTEN, pg_dump | Use 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 cheap | Queries compete inside the database, which is expensive |
| Each query runs near full speed | Each query slows down; total throughput eventually falls |
| Predictable memory | One 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 transactions | Hides 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 = 10caps 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:
| Part | What happens | Scale |
|---|---|---|
| Fork and startup | fork() of the postmaster, backend initialisation, authentication (SCRAM, TLS handshake), loading catalog caches lazily | Milliseconds per connect, far more than a simple query |
| Memory | Private process memory: catalog and relation caches (CacheMemoryContext), plan caches, per-session buffers, plus work_mem for each sort or hash while running | Commonly several MB per backend at rest, much more under big queries; measure on your workload |
| Snapshot work | Each transaction takes a snapshot of which transactions are in progress; this work grows with the number of connections | The GetSnapshotData() function dominated profiles with thousands of connections |
| Contention | Spinlocks, lightweight locks and the pg_locks tables, plus context switches between runnable processes | Shows 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 onceReal 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):
| Product | Connection model | Consequence |
|---|---|---|
| PostgreSQL | Process per connection | Pooler in front is standard practice; no built-in pooler |
| MySQL / InnoDB | Thread per connection (a thread pool exists in Enterprise and Percona builds) | Cheaper than a process, still bounded by max_connections (default 151) |
| SQL Server | Worker threads multiplexed by the scheduler | Client-side ADO.NET pool (Max Pool Size, default 100) |
| Oracle | Dedicated server processes, or shared servers and DRCP (Database Resident Connection Pooling) | DRCP is the built-in pooler |
| MongoDB | Driver pool per client (maxPoolSize, default 100 in the drivers) | A connection is a thread server-side; mongos adds its own pools |
| Redis | Single-threaded command loop, connection is a socket (maxclients, default 10000) | Cheap connections; pooling mostly saves round trips |
| SQLite | In-process, no server | A "pool" only limits file handles and writers |
| CockroachDB / Spanner | Network-served SQL; connection counts still bounded | Documentation 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 53300Real 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):
| Engine | Server-wide cap | Per-user or per-database cap | Error |
|---|---|---|---|
| PostgreSQL | max_connections (100) | ALTER ROLE ... CONNECTION LIMIT n, ALTER DATABASE ... CONNECTION LIMIT n | 53300 too_many_connections |
| MySQL | max_connections (151) | max_user_connections, CREATE USER ... WITH MAX_USER_CONNECTIONS | 1040 Too many connections, 1226 user limit |
| SQL Server | user connections option (0 = up to 32767) | Resource Governor | Error 17809 (maximum user connections reached) |
| Oracle | PROCESSES, SESSIONS | Profile SESSIONS_PER_USER | ORA-00018, ORA-02391 |
| MongoDB | net.maxIncomingConnections | Per-client driver maxPoolSize | Connection refused |
| Redis | maxclients | None built in | ERR max number of clients reached |
Fix / how to use it:
-- 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: make the per-process cap explicit, so the fleet sum can be computed
db.SetMaxOpenConns(10)// 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 kneeReal 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:
| Source | What it gives | Limit |
|---|---|---|
Formula (cores × 2) + spindles | A first guess for active connections | Starting point, not a law |
| Load test with your queries | The real knee | Needs production-like data and concurrency |
pg_stat_activity active count under peak | What the workload really uses | Measured on today's workload |
| HikariCP deadlock bound | Minimum for correctness with nested connection use | Not 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 growsThis 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:
| Input | Where to measure it |
|---|---|
λ | Application metrics: requests that open a transaction per second |
W | Time between Acquire and Release; DBStats.InUse sampled, or tracing spans around checkout |
Tail of W | p99 of the hold time, not the mean |
| Server concurrency | count(*) 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).
// 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// 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 eachApplication 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."
| Knob | Default | Effect | Added in |
|---|---|---|---|
SetMaxOpenConns(n) | 0 (unlimited) | Hard cap on open connections; callers block when it is reached | Go 1.2 |
SetMaxIdleConns(n) | 2 | Connections kept open while idle; reduced to MaxOpenConns if that is lower | Go 1.1 |
SetConnMaxLifetime(d) | 0 (forever) | Connections older than d are closed lazily before reuse | Go 1.6 |
SetConnMaxIdleTime(d) | 0 (forever) | Connections idle longer than d are closed lazily | Go 1.15 |
db.Stats() | WaitCount, WaitDuration, InUse, Idle, MaxIdleClosed, MaxIdleTimeClosed, MaxLifetimeClosed | Go 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 countedReal 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:
// 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
}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)
}
}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(),
})
}
}// 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:
// 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.
| Concern | database/sql | pgxpool |
|---|---|---|
| Cap | SetMaxOpenConns (0 = unlimited) | MaxConns (default max(4, NumCPU)) |
| Keep warm | none | MinConns |
| Lifetime | SetConnMaxLifetime | MaxConnLifetime plus MaxConnLifetimeJitter |
| Idle | SetConnMaxIdleTime | MaxConnIdleTime, HealthCheckPeriod |
| Veto reuse | driver ResetSession / IsValid | BeforeAcquire, AfterRelease |
| Wait metrics | WaitCount, WaitDuration | EmptyAcquireCount, EmptyAcquireWaitTime, CanceledAcquireCount |
| Prepared statements | driver decides | default 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:
// 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).
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 bottleneckSymptoms you can recognise:
| Layer | Signal | Meaning |
|---|---|---|
Go database/sql | InUse == MaxOpenConnections, rising WaitCount and WaitDuration | Callers queue for a connection |
pgxpool | AcquiredConns == MaxConns, rising EmptyAcquireCount, CanceledAcquireCount | Same, plus callers that gave up |
| PgBouncer | SHOW POOLS: cl_waiting > 0, large maxwait | Clients wait for a server connection |
| PostgreSQL | pg_stat_activity: many idle in transaction or wait_event_type = 'Lock' | The connections are held, not working |
| HTTP | 503 or timeouts with low database CPU | Pool wait counted inside request latency |
| Laravel | SQLSTATE[08006] / too many clients already, queue jobs piling up | Workers 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:
| Protection | Where | Effect |
|---|---|---|
defer rows.Close(), defer tx.Rollback(), defer conn.Close() | Go code | Releases on every path |
idle_in_transaction_session_timeout | PostgreSQL (per role, database or server) | Terminates sessions idle inside a transaction; default 0 (off) |
idle_session_timeout | PostgreSQL 14 and later | Terminates plain idle sessions; less important, as the docs say |
transaction_timeout | PostgreSQL 17 and later | Bounds the total transaction duration |
idle_transaction_timeout | PgBouncer | Disconnects clients idle in transaction |
statement_timeout, lock_timeout | PostgreSQL | Bounds the query itself and the lock wait |
ConnMaxLifetime, AfterRelease | Pool | Retires or vetoes bad connections |
Fix / how to use it:
-- 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;// 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
}// 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
}// 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| Setup | Connections held | Notes |
|---|---|---|
| PHP-FPM, no persistence | One per busy request, created and destroyed each time | Fork cost every request; fine at low rate |
PHP-FPM + PDO::ATTR_PERSISTENT | One per worker, kept for the worker's life | Session state (open transactions, SET, temp tables) can leak between requests; unused ones still hold a backend |
| PHP-FPM + PgBouncer (transaction) | Many client sockets, few backends | Standard answer; no persistence needed |
| Octane (Swoole, FrankenPHP, RoadRunner) | One per worker, application stays in memory | See next section |
Queue worker (queue:work) | One per worker for its whole life | Idle 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.
| Runtime | Concurrency model | Connection per | Gotcha |
|---|---|---|---|
| FrankenPHP (worker mode) | PHP threads in a Go server | Worker | State is kept between requests; reset what you set |
| Swoole / Open Swoole | Process workers plus task workers | Worker and task worker | Coroutines need their own connection each; do not share one PDO across coroutines |
| RoadRunner | Go server managing PHP worker processes | Worker | Same as above |
| PHP-FPM | Process per request | Request | No 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 stableReal 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:
| Mechanism | Effect |
|---|---|
--workers | Caps connections: workers × Octane instances |
--max-requests (default 500) | Recycles workers and their connections |
DisconnectFromDatabases listener | Drops 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 front | Makes per-request disconnect cheap |
Fix / how to use it:
<?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.
| Operation | Connection used | Why |
|---|---|---|
| Eloquent / query builder at request time | pooled | Short transactions; many clients |
php artisan migrate, db:wipe, schema dump/load | direct | DDL and session settings need a real session |
DB::connection('pgsql::direct')->statement('create extension ...') | direct | Explicit choice |
LISTEN / NOTIFY consumers | direct (or a session-mode pool) | LISTEN never works in transaction mode |
Long export with a cursor WITH HOLD | direct | Needs session |
| Queue workers | pooled, but see jobs below | Each 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
// 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
// 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
// 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
// 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.
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| Mode | Multiplexing ratio | Prepared statements | LISTEN, SET, session advisory locks | Typical use |
|---|---|---|---|---|
| session | 1 client : 1 server for the whole connection | Native, work | Work | Few long-lived clients; legacy; also saves fork cost |
| transaction | Many clients : few servers | Protocol-level with max_prepared_statements; SQL-level PREPARE never | Never | Web request/response workloads |
| statement | Many clients : few servers | Covered by max_prepared_statements as in transaction mode | Never; no multi-statement transactions | PL/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):
| Product | Session pooling | Transaction pooling | Statement pooling |
|---|---|---|---|
| PgBouncer | pool_mode = session (default) | pool_mode = transaction | pool_mode = statement |
| pgcat | Yes | Yes (the default) | Not documented |
| Odyssey | Yes | Yes, tracks transaction state | Not documented |
| Supavisor | Yes | Yes | Not documented |
| Pgpool-II | Connection pooling per child process | No transaction multiplexing | No |
| ProxySQL (MySQL) | n/a | Multiplexing disabled during a transaction | n/a |
| RDS Proxy | Pinned sessions | Multiplexing at transaction level when not pinned | n/a |
Fix / how to use it:
; 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 = 30What 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.
| Feature | Session mode | Transaction mode | Safe replacement |
|---|---|---|---|
SET search_path / SET ROLE / SET statement_timeout | Yes | Never (applies to a random later transaction) | SET LOCAL inside the transaction, or role/database defaults with ALTER ROLE ... SET |
LISTEN | Yes | Never | Direct connection or a session-mode pool for the listener |
NOTIFY | Yes | Yes | |
SQL-level PREPARE / EXECUTE / DEALLOCATE | Yes | Never | Protocol-level prepared statements (max_prepared_statements) or simple protocol |
pg_advisory_lock (session) | Yes | Never; lock outlives the transaction on a backend you no longer own | pg_advisory_xact_lock |
WITH HOLD cursor | Yes | Never | WITHOUT HOLD inside a transaction, or keyset pagination |
Temp table PRESERVE ROWS | Yes | Never | ON COMMIT DROP temp table inside one transaction |
LOAD, session-level extensions config | Yes | Never | Server config |
SELECT ... FOR UPDATE (row locks) | Yes | Yes: 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 txnReal 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:
-- 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: 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")// 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 / driver | What to set behind PgBouncer < 1.21 | Behind PgBouncer 1.21+ with max_prepared_statements |
|---|---|---|
Go pgx | default_query_exec_mode=simple_protocol (or exec) | Default cache mode works; keep simple protocol if unsure |
Go lib/pq | binary_parameters=yes for unnamed statements | Named statements are tracked by PgBouncer |
| Laravel (PDO pgsql) | 'pooled' => true makes Laravel use emulated prepares | pooled still sensible |
| PHP PDO (non-Laravel) | PDO::ATTR_EMULATE_PREPARES => true | Native prepares can work |
| Java JDBC | prepareThreshold=0 | Works |
| Rails / ActiveRecord | prepared_statements: false | Works |
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
| Pooler | Engine | Language / shape | What it adds | Notes |
|---|---|---|---|---|
| PgBouncer | PostgreSQL | C, single-threaded | Small, stable, three modes, online reconfiguration | so_reuseport lets several instances share a port |
| pgcat | PostgreSQL | Rust | Pooler and proxy with load balancing of reads across replicas, failover with health checks, mirroring, experimental sharding | README: transaction mode does not support SET, prepared statements and advisory locks (use SET LOCAL, pg_advisory_xact_lock) |
| Odyssey | PostgreSQL | C, multi-threaded (Yandex) | Pool per database-and-user pair with separate auth and mode; tracks transaction state and rolls back an abandoned transaction before reuse | Multi-threaded vs PgBouncer's single thread |
| Supavisor | PostgreSQL | Elixir, cloud-native, multi-tenant | Dynamic per-tenant pools across a cluster; README: proxies "millions of Postgres end-client connections" | Developed in the Supabase GitHub organisation; targets serverless clients |
| Pgpool-II | PostgreSQL | C middleware | Connection pooling plus replication, load balancing and failover; num_init_children × max_pool bounds its connections | Pool per child process, so more complex to size |
| ProxySQL | MySQL / MariaDB (PostgreSQL support added) | C++ | Multiplexing of frontend connections over backend ones, query rules, read/write split, query cache | Multiplexing is disabled while a transaction is active, after LOCK TABLES, GET_LOCK(), or queries containing @ variables |
| RDS Proxy | RDS and Aurora (MySQL, PostgreSQL, SQL Server) | Managed | Pools and multiplexes; helps lambda-style connection storms and failover | Connection "pinning" when it cannot multiplex; on PostgreSQL setting a variable pins the session |
| Oracle DRCP | Oracle | Built in | Pool of server processes shared among clients | Server-side, no extra proxy |
| MySQL Router / thread pool | MySQL | Router; thread pool in Enterprise/Percona | Routing; fewer threads than connections | Not 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| Approach | Routing decision | Lag handling | Notes |
|---|---|---|---|
Laravel read / write hosts + sticky | Application, per request | sticky => true sends reads after a write in the same request to the write connection | Simple, per-request granularity |
| Two PgBouncer endpoints (primary pool, replica pool) | Application chooses the DSN | App decides | Most explicit; two pools to size |
| pgcat | Pooler load-balances reads across replicas and primary, health-checked failover | Tolerates lag only if the app does | Configured per pool |
| ProxySQL (MySQL) | Query rules to hostgroups, multiplexing | max_replication_lag per server | Writes by default to the writer hostgroup |
| Pgpool-II | Parses queries; load balancing with delay thresholds | delay_threshold | Heavier, also handles failover |
| RDS Proxy | Separate read-only endpoint for readers | Aurora replica lag applies | Reader 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:
// 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: two pools, chosen per call site
primary, replicas := mustOpen(primaryDSN, 10), mustOpen(replicaDSN, 20)
// writes and read-your-writes use primary; reports use replicasPooling 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.
// 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
}| Item | Count | Connections |
|---|---|---|
| orders service | 4 replicas × 10 | 40 |
| billing service | 4 × 10 | 40 |
| reports service | 4 × 10 | 40 |
| rolling deploy overlap | +50% of one service | +20 |
| migrations, cron, psql, monitoring | 10 | |
| Total direct | 150 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:
| Control | Scope |
|---|---|
Per-service role with CONNECTION LIMIT | One service cannot starve the rest |
| One PgBouncer per database cluster, or sidecar per node | Shared default_pool_size, max_db_connections |
max_user_connections (PgBouncer) | Per user cap across pools |
| Autoscaler max replicas × pool size | Budget check at deploy time (CI) |
| Separate pools for batch vs request traffic | A 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| Approach | How it helps | Cost |
|---|---|---|
| RDS Proxy (AWS) | Pools and multiplexes connections between functions and RDS/Aurora; avoids pinning when you keep session state out | Extra hop, cost, pinning rules |
| PgBouncer or Supavisor (hosted or self-managed) | Transaction-mode pooler between functions and PostgreSQL | One more service to run |
| Provider pooled endpoint (managed Postgres) | Built-in pooler (often PgBouncer or Supavisor) behind a second port or hostname | Provider specifics |
| HTTP or data-API drivers | No TCP connection from the function | Different driver, limits |
| Limit function concurrency | Hard cap on instances | Throttles traffic |
| Pool size 1 per instance, short idle timeout | Each instance holds at most one connection | Cannot 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.
| Check | Cost | What it catches | Pitfall |
|---|---|---|---|
db.PingContext on /readyz | One round trip | Database unreachable | Do not use as liveness, or a DB outage restarts every pod |
| Pool validation before reuse | Per checkout, or every N seconds | Half-open connections | Adds latency if done on every checkout |
ConnMaxLifetime / MaxConnLifetime | None | Stale endpoints after failover | Short enough to react, long enough to avoid churn |
SELECT pg_is_in_recovery() | One round trip | Connected to a replica when you want the primary | Run after reconnect |
PgBouncer server_lifetime, server_idle_timeout | None | Backends that live forever | |
| TCP keepalive | None | Dead peers through NAT | Slow 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."
-- 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| Metric | Source | Alert when |
|---|---|---|
| Active backends vs cores | pg_stat_activity | Sustained > 2 × cores |
idle in transaction count and age | pg_stat_activity | Any older than a few seconds |
| Connection headroom | max_connections minus used | Below 10% |
cl_waiting, maxwait | PgBouncer | cl_waiting > 0 for more than a few seconds |
WaitCount, WaitDuration | Go DBStats | Rate rising |
EmptyAcquireCount, CanceledAcquireCount | pgxpool.Stat | Rate rising |
total_wait_time | SHOW STATS | Rising relative to total_query_time |
DatabaseConnectionsCurrentlySessionPinned | CloudWatch (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
// 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
| Concern | PostgreSQL | MySQL / InnoDB | SQL Server | Oracle | MongoDB | Redis |
|---|---|---|---|---|---|---|
| Server connection | Process | Thread | Worker via scheduler | Dedicated or shared server | Thread | Socket on single-threaded loop |
| Default cap | max_connections 100 | max_connections 151 | 32767 (user connections) | PROCESSES / SESSIONS | 65536 default maxIncomingConnections (depends on OS limits) | maxclients 10000 |
| Built-in pooler | None | Thread pool (Enterprise, Percona) | Client-side pool in driver | DRCP | Driver pool | None |
| External poolers | PgBouncer, pgcat, Odyssey, Supavisor, Pgpool-II, RDS Proxy | ProxySQL, MySQL Router, RDS Proxy | RDS Proxy (RDS SQL Server) | CMAN-TDM, DRCP | mongos | Envoy proxy, Twemproxy |
| Client pool settings | pool size, lifetime, idle | same | Max Pool Size, Min Pool Size, Connection Lifetime | UCP, ODP.NET pooling | maxPoolSize, waitQueueTimeoutMS, maxIdleTimeMS | client-specific |
| Session state to avoid behind a pooler | SET, LISTEN, PREPARE, advisory locks, temp tables | SET, user variables (@), GET_LOCK, temp tables | SET, #temp tables, app roles | package state, ALTER SESSION | cursors, transactions (sessions) | SELECT n, MULTI, WATCH, SUBSCRIBE |
| Cap error | 53300 too many clients | 1040 Too many connections | 17809 | ORA-00018 | connection refused | max 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
| Knob | Default | Meaning |
|---|---|---|
pool_mode | session | session, transaction or statement |
max_client_conn | 100 | Client sockets allowed; raise the OS file-descriptor limit with it |
default_pool_size | 20 | Server connections per (database, user) pair |
min_pool_size | 0 | Keep this many warm |
reserve_pool_size / reserve_pool_timeout | 0 / 5 s | Extra connections after a client waited this long |
max_db_connections | unset | Server connections per database regardless of user |
max_user_connections | unset | Server connections per user |
server_lifetime | 3600 s | Close server connections after this age |
server_idle_timeout | 600 s | Close idle server connections |
server_reset_query / server_reset_query_always | DISCARD ALL / off | Cleanup on release (session mode) |
server_check_query / server_check_delay | Liveness check before reuse after idle | |
query_wait_timeout | 120 s | Disconnect a client that waits this long for a server connection |
client_idle_timeout | 0 (off) | Close idle clients |
idle_transaction_timeout | 0 (off) | Disconnect clients idle inside a transaction |
max_prepared_statements | 200 (current docs) | Protocol-level prepared statement tracking per server connection |
ignore_startup_parameters / track_extra_parameters | Which unknown startup parameters to ignore or track | |
so_reuseport | off | Several 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 rejectError codes and messages you will see Must-know
| Error | Where | Meaning | Action |
|---|---|---|---|
FATAL: sorry, too many clients already (53300) | PostgreSQL | max_connections reached | Pool or pooler; lower pool sizes |
FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute | PostgreSQL | Only reserved slots left | Same; keep admin slots |
FATAL: too many connections for role "x" (53300) | PostgreSQL | CONNECTION LIMIT of the role | Raise or fix the leak |
FATAL: terminating connection due to idle-in-transaction timeout (25P03) | PostgreSQL | idle_in_transaction_session_timeout fired | Shorten the transaction |
prepared statement "S_1" does not exist (26000) | PostgreSQL via pooler | Named statement on another backend | Simple protocol or max_prepared_statements |
prepared statement "S_1" already exists (42P05) | PostgreSQL via pooler | Same cause, other direction | Same |
cached plan must not change result type | PostgreSQL | Schema changed under a cached plan | RECONNECT after DDL |
context deadline exceeded | Go | Deadline hit, possibly while waiting for a connection | Check WaitDuration |
sql: database is closed, driver: bad connection | Go | Pool closed or connection broken | Lifetime settings, retry |
SQLSTATE[08006] | PHP PDO | Connection failure including too many clients | Pool, retry with backoff |
no more connections allowed (max_client_conn) | PgBouncer | Client socket cap reached | Raise max_client_conn, check fds |
query_wait_timeout | PgBouncer | Waited too long for a server connection | Pool too small or queries too slow |
1040 Too many connections, 1226 | MySQL | Server or user cap | ProxySQL or lower pools |
Solving the classic problems
Too many connections from a fleet Must-know
| Solution | How | Advantage | Cost or limitation |
|---|---|---|---|
| Smaller app pools | MaxOpenConns from the budget | Free, immediate | Needs shorter transactions |
| PgBouncer transaction mode | Many clients, few servers | Large ratio | Session features break |
Raise max_connections | Config and restart | Quick relief | More memory and snapshot work; not a fix |
| Per-role limits | CONNECTION LIMIT | Contains a noisy neighbour | Needs roles per workload |
| Read replicas for readers | Separate pool | Splits load | Lag |
-- 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
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Request deadline | context.WithTimeout before the query | Bounded wait | Callers must handle 503 |
| No I/O inside a transaction | Call APIs before BEGIN or after COMMIT (use an outbox) | Short hold time | Restructuring |
| Separate pools | Request vs batch | Isolation | More pools to size |
| Bulkhead / circuit breaker | Cap concurrent DB callers | Protects the pool | Extra code |
statement_timeout, lock_timeout | Per role | Bounds the damage | Needs retry logic |
| Backoff and jitter on retry | Client | Stops retry storms | Latency |
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) }// Laravel: fail fast and surface a 503 instead of queueing
DB::statement("SET LOCAL lock_timeout = '2s'"); // inside DB::transactionSession 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
| Error | Meaning | Retry? |
|---|---|---|
53300 too_many_connections | Capacity | Yes, with backoff and jitter; never in a tight loop |
57P01 admin_shutdown, 08006, 08003 | Connection lost (failover, restart) | Yes, on a new connection; only idempotent work |
25P03 idle_in_transaction_session_timeout | You held a transaction idle | Fix the code; retry the whole transaction |
40001, 40P01 | Serialization or deadlock | Yes (see Isolation Levels) |
context deadline exceeded waiting for a connection | Pool saturated | Shed load; do not retry immediately |
// 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)
}// 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
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| One app, one database, low traffic | App pool only (5 to 10) | ConnMaxLifetime, deadline per request | Simplest correct setup |
| Many app instances or PHP-FPM | PgBouncer, transaction mode | max_prepared_statements, SET LOCAL, pooled in Laravel | Large client:server ratio |
Legacy app needing SET, LISTEN, advisory locks | PgBouncer session mode, or direct | Dedicated pool per feature | Compatibility over ratio |
| Serverless functions | RDS Proxy, Supavisor, or provider pooler | Pool size 1, cap concurrency | Absorbs connection storms |
| Read-heavy with replicas | Separate read pool, sticky writes | Lag-aware routing | Offload primary |
Multi-tenant with SET search_path | Transaction mode with SET LOCAL, or schema-qualified names | Per-tenant roles | Avoids leaking state |
| Batch/ETL jobs | Own role, own small pool, direct connection | CONNECTION LIMIT, statement_timeout | Cannot starve requests |
| MySQL fleet | ProxySQL multiplexing | Read/write split rules | Equivalent of PgBouncer |
| Managed AWS database | RDS Proxy | Minimise pinning | Pooling plus failover handling |
| Needs sharded routing or read balancing in the pooler | pgcat or Pgpool-II | Test thoroughly | More 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 backendsAcross 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×
| Scale | Shape | Pooling design |
|---|---|---|
| 1× (one host, hundreds of req/s) | One process, one database | App pool of 5 to 20, lifetime and deadline, no external pooler |
| 10× (a dozen instances) | Several hosts or PHP-FPM fleet | PgBouncer transaction mode, max_prepared_statements, SET LOCAL, Laravel pooled/direct, per-role limits |
| 100× (many services, serverless) | Autoscaled fleets, replicas, regions | Dedicated 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 |
| Beyond | Sharding, distributed SQL | Per-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.
# 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):
// 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 CPULittle'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 timeoutExperiment 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/sExperiment 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 smallTypical 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
| Belief | Reality |
|---|---|
| A bigger pool means more throughput | Past the knee, throughput falls and latency rises; keep it small and let callers wait |
| Pool exhaustion means the database is overloaded | The database is usually idle; a few slow callers hold all the connections |
MaxOpenConns limits my database load | It limits one process; the fleet total is instances × cap |
| PgBouncer is transparent | Only in session mode; transaction mode removes session state |
| Prepared statements cannot work with PgBouncer | Protocol-level ones can since 1.21.0 with max_prepared_statements; SQL-level PREPARE still cannot |
| Persistent PDO connections are a pool | They are one cached connection per worker, with no limit control, and leak session state |
idle connections are free | Each holds a backend process and memory; idle in transaction also holds locks and blocks vacuum |
Raising max_connections fixes too many clients | It raises the memory and snapshot cost and needs a restart; pooling or smaller pools fix the cause |
sql.Open opens a connection | It validates arguments; the first query or Ping connects |
| Serverless scales the database too | Function concurrency scales; database connections do not, without a proxy |
DB::disconnect() frees a backend behind PgBouncer | In transaction mode it frees only the client socket; the backend was already free |
| A health check proves the primary is the primary | A ping proves a connection works; check pg_is_in_recovery() after failover |
Cheat sheet
| Topic | What to remember |
|---|---|
| Why pool | Setup cost is high, and the database needs a concurrency cap |
| PostgreSQL connection | A 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 law | L = λ × W: pool ≈ requests/s × hold time × 2 for headroom |
| Fleet budget | Σ instances × MaxOpenConns ≤ max_connections − reserved |
| Go knobs | SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime, SetConnMaxIdleTime; Stats() for WaitCount |
| pgxpool | MaxConns (default max(4, NumCPU)), MaxConnLifetimeJitter, HealthCheckPeriod, AfterRelease |
| Acquire timeout | Pass a context with a deadline; the wait for a connection ends with it |
| Exhaustion | in_use == max, rising wait counts, low database CPU; fix hold time first |
| Leaks | defer rows.Close(), defer tx.Rollback(); idle_in_transaction_session_timeout |
| PHP-FPM | One connection per busy worker; hosts × pm.max_children is the worst case |
| Octane | One connection per worker, kept across requests; --max-requests recycles |
| Laravel 13 | pooled (emulated prepares) plus direct (migrations, pgsql::direct) |
| PgBouncer modes | session (all features), transaction (no SET/LISTEN/PREPARE/session advisory locks), statement (no multi-statement) |
| Prepared statements | Protocol-level work with max_prepared_statements (1.21+); SQL-level do not |
| Monitoring | pg_stat_activity states, SHOW POOLS (cl_waiting, maxwait), DBStats.WaitCount |
| Limits | CONNECTION LIMIT per role/database; max_user_connections, max_db_connections in PgBouncer |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| Connection pool | A 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 |
| Snapshot | The set of transactions a query may see; each transaction takes one |
max_connections | PostgreSQL setting for the maximum concurrent connections (default 100) |
superuser_reserved_connections | Slots kept for superusers (default 3) |
reserved_connections | Slots kept for roles with pg_use_reserved_connections (PostgreSQL 16 and later) |
CONNECTION LIMIT | Per-role or per-database cap in CREATE/ALTER ROLE and ALTER DATABASE |
| Knee | The concurrency point after which throughput falls |
| Little's law | L = λ × W: average items in a system equal arrival rate times time in the system |
| Hold time | Time between acquiring and releasing a connection |
| HikariCP | Java JDBC pool whose wiki holds the pool sizing axiom |
SetMaxOpenConns | Go cap on open connections in *sql.DB |
SetMaxIdleConns | Go number of idle connections kept |
SetConnMaxLifetime | Go maximum age of a connection |
SetConnMaxIdleTime | Go maximum idle time of a connection |
DBStats | Go pool statistics (WaitCount, WaitDuration, InUse, Idle) |
pgxpool | pgx's own connection pool with MaxConns, MinConns, lifetime, jitter and health check |
| Acquisition timeout | Deadline for obtaining a connection from the pool |
| Pool exhaustion | All connections in use, new callers wait |
| Connection leak | A connection checked out and never returned |
| Idle in transaction | A session inside a transaction doing nothing; holds locks and blocks vacuum |
idle_in_transaction_session_timeout | PostgreSQL setting that ends such sessions |
idle_session_timeout | PostgreSQL setting that ends idle sessions outside a transaction |
statement_timeout, lock_timeout | PostgreSQL limits for query time and lock wait |
| PHP-FPM | PHP process manager; one request per worker; pm.max_children caps workers |
| Persistent connection | PDO connection kept by the worker after the request (PDO::ATTR_PERSISTENT) |
| Octane | Laravel server that keeps the application in memory (FrankenPHP, Swoole, RoadRunner) |
| Swoole | PHP extension for coroutine-based servers, used by Octane |
| FrankenPHP | PHP application server written in Go, used by Octane |
pooled / direct | Laravel 13 PostgreSQL options for the pooler endpoint and the direct endpoint |
| PgBouncer | Lightweight PostgreSQL connection pooler |
| Session pooling | Server connection held for the whole client session |
| Transaction pooling | Server connection held for one transaction |
| Statement pooling | Server connection held for one statement |
server_reset_query | Query run on a server connection when it returns to the pool (DISCARD ALL) |
max_prepared_statements | PgBouncer 1.21+ setting for tracking protocol-level prepared statements |
default_pool_size | PgBouncer server connections per (database, user) |
reserve_pool_size | Extra PgBouncer connections after waiting reserve_pool_timeout |
query_wait_timeout | PgBouncer limit on waiting for a server connection |
cl_waiting, maxwait | SHOW POOLS columns for waiting clients and longest wait |
| Pinning | A proxy tying a client to one backend because of session state (RDS Proxy) |
| Multiplexing | Many client connections sharing few server connections (ProxySQL, RDS Proxy) |
| pgcat | Rust PostgreSQL pooler with load balancing, failover and mirroring |
| Odyssey | Multi-threaded PostgreSQL pooler from Yandex |
| Supavisor | Elixir multi-tenant PostgreSQL pooler |
| ProxySQL | Proxy and pooler for MySQL and MariaDB |
| RDS Proxy | AWS managed database proxy and pooler |
| Pgpool-II | Middleware with pooling, load balancing, replication and failover |
| DRCP | Oracle Database Resident Connection Pooling |
| Read/write split | Sending writes to the primary and reads to replicas |
| Connection storm | Many instances opening connections at once |
| Health check | A periodic test that a connection or backend works |
References
- Go,
database/sqlpackage documentation: https://pkg.go.dev/database/sql - Go source,
database/sql/sql.go: https://github.com/golang/go/blob/master/src/database/sql/sql.go - pgx v5,
pgxpooldocumentation: https://pkg.go.dev/github.com/jackc/pgx/v5/pgxpool - pgx v5.7.5,
pgxpool/pool.go: https://github.com/jackc/pgx/blob/v5.7.5/pgxpool/pool.go - pgx v5.7.5,
conn.go(DefaultQueryExecModeand the PgBouncer note): https://github.com/jackc/pgx/blob/v5.7.5/conn.go - "About Pool Sizing", HikariCP Wiki: https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
- PostgreSQL wiki, "Number Of Database Connections": https://wiki.postgresql.org/wiki/Number_Of_Database_Connections
- PostgreSQL documentation, "Connections and Authentication": https://www.postgresql.org/docs/current/runtime-config-connection.html
- PostgreSQL documentation, "How Connections Are Established": https://www.postgresql.org/docs/current/connect-estab.html
- PostgreSQL documentation, "Client Connection Defaults" (
idle_in_transaction_session_timeout): https://www.postgresql.org/docs/current/runtime-config-client.html - PostgreSQL documentation,
CREATE ROLE(CONNECTION LIMIT): https://www.postgresql.org/docs/current/sql-createrole.html - PostgreSQL documentation, "The Cumulative Statistics System" (
pg_stat_activity): https://www.postgresql.org/docs/current/monitoring-stats.html - "Analyzing the Limits of Connection Scalability in Postgres", Citus Data (Andres Freund): https://www.citusdata.com/blog/2020/10/08/analyzing-connection-scalability/
- PgBouncer, "Features": https://www.pgbouncer.org/features.html
- PgBouncer, "Configuration": https://www.pgbouncer.org/config.html
- PgBouncer, "Usage" (admin console): https://www.pgbouncer.org/usage.html
- PgBouncer, "Changelog" (1.21.0, prepared statements): https://www.pgbouncer.org/changelog.html
- pgcat README: https://github.com/postgresml/pgcat
- Odyssey README: https://github.com/yandex/odyssey
- Supavisor README: https://github.com/supabase/supavisor
- ProxySQL, "Multiplexing": https://proxysql.com/documentation/multiplexing/
- Amazon RDS Proxy, "Avoiding pinning": https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-pinning.html
- Pgpool-II documentation, "Connection Pooling": https://www.pgpool.net/docs/latest/en/html/runtime-config-connection-pooling.html
- Little's law, Wikipedia (secondary source for the statement of the law): https://en.wikipedia.org/wiki/Little's_law
- PHP manual, "Connections and Connection management" (PDO persistent connections): https://www.php.net/manual/en/pdo.connections.php
- Laravel 13 documentation, Database (pooled PostgreSQL connections): https://laravel.com/docs/13.x/database
- Laravel 13 documentation, Octane: https://laravel.com/docs/13.x/octane
- Laravel Octane default
config/octane.php: https://github.com/laravel/octane/blob/master/config/octane.php - Laravel framework source,
DatabaseManagerandConnection(disconnect,reconnectIfMissingConnection): https://github.com/laravel/framework/tree/13.x/src/Illuminate/Database
See also: Locks & Concurrency, Replication, Read Replicas & Failover, MVCC, VACUUM & Bloat, Isolation Levels.