Connection pooling and database limits
Learn why databases run out of connections, how to size and guard a pool, and what breaks when you put PgBouncer in front of Postgres.
Updated since you finished it. We changed this lesson after you marked it done. Your progress is kept.
What broke
On 30 October 2026, some requests to github.com hung for up to about 10 seconds. Then they failed with a server error. At the worst point, about 43% of pull request merge attempts failed. About 3.5% of API calls failed too. 1
GitHub's report blames a connection pool, not the database itself. A pool used by many github.com services had reached its limit. For several minutes, no connections were available. 1
The pool was already near its limit. Then some update requests began to hold their connections far longer than expected. Each one started writing a change, then ran a separate lookup that could take several seconds. During that lookup, the connection was "reserved but unused". 1
New requests waited for a free connection. When the connection timeout expired, they failed. 1
GitHub changed the order. The slow lookup now runs before the write starts, so it holds no connection. GitHub is also looking at limits on how long a pooled connection can be held. 1
It happens for real
GitHub · 30 Oct 2026GitHub requests fail when a shared database connection pool runs outSome github.com requests hung for up to about 10 seconds and then failed. At the worst point, about 43% of pull request merge attempts failed, and about 3.5% of API calls. All incidents tagged “databases”The idea in simple words
A database connection is expensive to open and expensive to keep. So apps open a few, keep them, and lend them out. That set of reusable connections is a connection pool.
A pool is a tiny resource with a queue in front of it. A request borrows a connection, uses it and gives it back. If all connections are out, the next request waits. If it waits too long, it fails.
So a pool works only if two things are true. The pool is the right size. And every borrower gives the connection back quickly.
The key idea. The database can serve only a few connections well. Keep pools small, count them across every app instance, and hold a connection only while you are actually talking to the database.
How it works
Why connections are scarce
The Postgres lesson showed the process-per-user model. For every new connection, the postmaster starts a new backend process. 2 Before the first query, that backend must also check the client's credentials. 12 AWS describes this as "the memory and CPU overhead" of opening a connection. 13
The default max_connections is typically 100. Postgres sizes some resources, including shared memory, from it. 3 Three slots are reserved for superusers by default. 3 Your app gets the rest.
Why not just raise it to 5,000? Memory is not the main problem. Andres Freund measured idle connections at below 2 MiB each with a good setup. 4 The real cost is that every open connection makes the others slower. In tests he published in 2020, a single active connection ran less than half as fast with 5,000 mostly idle connections open. 4 Few connections, kept busy, beat many idle ones.
Sizing an app-side pool
A pool like HikariCP for Java has four settings that matter most: 6
- Maximum size (
maximumPoolSize). Idle plus in-use connections. Default 10. - Minimum idle (
minimumIdle). The authors recommend leaving it unset, so the pool stays a fixed size. - Acquire timeout (
connectionTimeout). How long a caller waits for a connection before an error. Default 30 seconds. - Max lifetime (
maxLifetime). Retire a connection after this age. Set it "several seconds shorter" than any limit imposed by the database or network.
How big? Smaller than you think. HikariCP's "About Pool Sizing" page describes an Oracle demo. Cutting the pool from 2,048 connections to 96 cut response times from about 100 ms to about 2 ms. 5 A database server has a few CPU cores. Beyond some point, more connections only add switching and waiting.
The page gives a formula from the PostgreSQL project as a starting point: 5
connections = ((core_count * 2) + effective_spindle_count)core_count excludes hyper-threads. effective_spindle_count is zero if your active data is fully cached. It grows toward the number of disks as more reads miss the cache. The page says there has been no analysis yet of how well it works with SSDs. 5 So treat it as a first guess. Load test around it and keep the size that gives the best latency.
There is also a floor. If one request needs several connections at once, a small pool can deadlock. The minimum is threads × (connections per thread − 1) + 1. 5 Our advice: better still, design each request to need only one connection.
To check the app side, use Little's law from the tail latency lesson. Connections in use = requests per second × seconds each request holds one. At 500 requests a second and 10 ms per hold, about 5 are in use. GitHub's lookups took several seconds. At 3 seconds you would need 1,500.
The multiplication problem
Every app instance has its own pool. So the database sees the sum.
Take 30 pods with a pool of 20 each. That is 600 connections against a limit near 100. Autoscaling and rolling deploys make it worse, because old and new pods run at the same time. Our advice: treat serverless functions as the extreme case. Each running copy may open its own connection, and many copies can start at once.
Write the sum down. pods at peak × pool size + admin tools + cron jobs must stay below the database limit. When it cannot, put a shared pooler in the middle.
External poolers: PgBouncer and RDS Proxy
PgBouncer can accept many client connections and share a few server connections among them. It has three pooling modes: 8
- Session pooling. A client keeps one server connection until it disconnects. Every Postgres feature works. It is the default. 9
- Transaction pooling. A client gets a server connection only for one transaction. This is where the big savings are.
- Statement pooling. Transaction pooling that forbids multi-statement transactions.
Transaction pooling breaks anything that lives in the session, because your next transaction may run on another connection. PgBouncer's docs list these as unsupported: 8
SETandRESET.LISTEN.- Session-level advisory locks.
- SQL
PREPAREandDEALLOCATE, andWITH HOLDcursors. - Temporary tables that live past one transaction, and
LOAD.
Two common workarounds: SET LOCAL, which lasts only for the transaction, and pg_advisory_xact_lock, which is released at commit. RDS Proxy, for example, does not pin on transaction-level advisory locks. 14
Prepared statements used to be the big pain. PgBouncer 1.21.0 added support for protocol-level named prepared statements in October 2023. 10 Since 1.24.0, it is on by default, with max_prepared_statements at 200. 10 9 SQL-level PREPARE still does not work. 8 Also note that PgBouncer is single-threaded and uses one CPU core per instance. 9
On AWS, RDS Proxy is a managed pooler. It queues or throttles connections it cannot serve at once. Past your limits, it rejects them. 13 When a Postgres session uses SET, LISTEN, SQL PREPARE, session advisory locks, temporary tables or even nextval, among others, the proxy "pins" that client to one database connection. 14 Pinned connections cannot be shared, so watch the pinning metric. 14
Exhaustion and leaks
Here is a simplified model of what happened at GitHub. The pool size and timings are made up:
- The pool has 4 open connections. A request borrows one, runs a 5 ms query and gives it back. Most of the time, most connections are free.
- Some update requests start a write, then wait 3 seconds on a slow lookup. Their connections are borrowed but idle. Nobody else can use them.
- A few of those requests take every connection. Each new request now waits in the pool's queue for a connection to come back.
- The waits end at the acquire timeout, and the requests fail. The database may be almost idle. The pool is full of connections doing nothing.
- The fix: do the slow lookup before you borrow a connection. Hold it only for the write. Now the same traffic leaves 3 connections free.
Pool exhaustion looks strange from the outside. The app is slow and returns errors. But the database CPU is low and its queries are fast. The time is spent waiting for a connection, not running a query.
The acquire timeout is your safety valve. A 30-second default means callers hang for 30 seconds first. 6 Set it below your request deadline, so a full pool fails fast. Then load shedding and backpressure can do their jobs.
A connection leak is a borrow without a return. Each leak shrinks the pool by one, until nothing is left. The psycopg docs warn that forgetting putconn() "will deplete the pool". 7
# Leaks: if execute() raises, the connection never goes back.
conn = pool.getconn()
conn.execute(sql)
pool.putconn(conn)
# Safe: the block always returns it.
with pool.connection() as conn:
conn.execute(sql)To find leaks, turn on HikariCP's leakDetectionThreshold. It logs a message when a connection has been out of the pool longer than that. It is off by default. 6 On the server, look in pg_stat_activity for sessions in the state idle in transaction. 12 Set idle_in_transaction_session_timeout to end them. 11
Trade-offs
| Option | Gain | Cost | Use when |
|---|---|---|---|
| No pool | Simple. | A new backend process per request. 2 | Scripts and one-off jobs. |
| App-side pool | No extra hop. Every feature works. | Total = pods × size. | A fixed, small number of instances. |
| PgBouncer, session mode | Every feature works. 8 | Saves little. One client still holds one connection. | Many short-lived client connections. |
| PgBouncer, transaction mode | Many clients share a few connections. | No session state, LISTEN or session locks. 8 | Many pods or serverless functions. |
| RDS Proxy | Managed. Queues, then rejects. 13 | Pinning stops sharing. 14 | You run on RDS and want no pooler to operate. |
Raise max_connections | One config line. | More shared memory, and slower active connections. 3 4 | Small steps only, after measuring. |
Simple rule: small app pools, a sum you have written down, and a transaction-mode pooler once instances multiply.
At work: how a senior uses this
- Keep a table of every client of the database: service, peak instances, pool size. Check the sum against
max_connectionsbefore each scale-up. - Ask in review: "Does this code hold a connection while it waits for something else?" HTTP calls, queue publishes and file uploads go before or after the transaction.
- Set the acquire timeout below the request deadline. Alert on time waiting for a connection, not only query time.
- Graph pool metrics: active, idle, waiting and time to acquire.
- Turn on leak detection in staging and production, set to a few times your longest normal transaction.
- Before moving to transaction pooling, search the code for
SET,LISTEN,pg_advisory_lock,PREPAREand temporary tables. - Keep
maxLifetimebelow any timeout in PgBouncer, proxies or load balancers.
With AI
What to ask the agent
"List every place in this service that borrows a database connection. For each, say what else happens while it is held: HTTP calls, sleeps, retries or queue sends."
"We have 24 pods, a HikariCP pool of 30 and Postgres with 4 cores and max_connections 200. Work out the total connections at peak and during a rolling deploy, and propose pool sizes."
"We plan to put PgBouncer in transaction mode in front of this app. Search the code for session state that will break: SET, LISTEN, advisory locks, SQL PREPARE, WITH HOLD cursors and temporary tables."
What to check yourself
- Every
getconnor manual borrow has a matching return in afinallyblock or awithblock. - The proposed pool size came from a load test, not just from the formula.
- The agent counted all instances during a deploy, not only at normal load.
- Lock code uses
pg_advisory_xact_lock, not session-level advisory locks, if you use transaction pooling. - Your PgBouncer version is 1.21 or later before you rely on prepared statements, and
max_prepared_statementsis not 0.
Check yourself
Your progress is saved only in this browser. Export it to keep it safe.
You have finished 5 lessons. Your progress lives only in this browser. Export a copy so you don’t lose it.
Go deeper
Show 14 sources and related lessons
- GitHub availability report: October 2026 (opens in a new tab)
The October 30 entry, where a shared database connection pool ran out and requests failed across github.com. - PostgreSQL documentation: 51.2. How Connections Are Established (opens in a new tab)
The process-per-user model, where the postmaster starts one backend process per connection. - PostgreSQL documentation: 19.3. Connections and Authentication (opens in a new tab)
max_connections, its default, and the slots reserved for superusers. - Andres Freund, Analyzing the Limits of Connection Scalability in Postgres (opens in a new tab)
Measurements showing that memory is not the main limit, and that thousands of idle connections slow down active ones. - About Pool Sizing · brettwooldridge/HikariCP Wiki (opens in a new tab)
Why a small pool is faster, the starting formula, and the minimum size that avoids pool deadlock. - HikariCP README (brettwooldridge/HikariCP on GitHub) (opens in a new tab)
Every pool setting with its default, including connectionTimeout, maxLifetime and leakDetectionThreshold. - psycopg_pool – Connection pool implementations (opens in a new tab)
The Python pool API, its wait timeout and the warning that a missing putconn() depletes the pool. - PgBouncer features (opens in a new tab)
The three pooling modes and a table of which Postgres features work in each. - PgBouncer config (opens in a new tab)
pool_mode, pool sizes, max_prepared_statements, and the note that PgBouncer is single-threaded. - PgBouncer changelog (opens in a new tab)
Version 1.21.0 adds protocol-level prepared statements; 1.24.0 turns them on by default. - PostgreSQL documentation: 19.11. Client Connection Defaults (opens in a new tab)
idle_in_transaction_session_timeout, and a warning about idle timeouts behind poolers. - PostgreSQL documentation: 27.2. The Cumulative Statistics System (opens in a new tab)
The pg_stat_activity view and its state values, such as "idle in transaction". - Amazon RDS Proxy - Amazon Relational Database Service (opens in a new tab)
A managed pooler that queues, throttles and finally rejects connections it cannot serve. - Avoiding pinning an RDS Proxy (opens in a new tab)
Which Postgres statements tie a client to one database connection and stop reuse.
Real incident: GitHub, 30 Oct 2026: GitHub requests fail when a shared database connection pool runs out
Case studies: Cloudflare: Pingora: replacing NGINX with a proxy written in Rust
Related: PostgreSQL in depth · Tail latency and queueing · Backpressure and flow control · Load shedding and graceful degradation · Circuit breakers, bulkheads and fallbacks
Before this: Postgres and Tail latency and queueing. Next to it: Backpressure, Load shedding and Circuit breakers and bulkheads.