Data · L2Connection pooling and database limits

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.

L2 SeniorData19 min read
Fact-checked by AI against cited sources · Human review pendingLast reviewed 13 Nov 2026 · How we check content
Section 1 of 8

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

Section 2 of 8

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.

Section 3 of 8

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

  • SET and RESET.
  • LISTEN.
  • Session-level advisory locks.
  • SQL PREPARE and DEALLOCATE, and WITH HOLD cursors.
  • 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:

A pool of 4 connections fills up when requests hold connections they are not usingApp pool: at most 4 connections Normalqueryfreefreefree~5 ms eachBorrow, query, give back. Mostly free. Slow stepqueryheldheldfree3 s idleWrite started, then a slow lookup. Fullheldheldheldheld50 waitNew requests queue for a connection. TimeouterrorsWaits end at the acquire timeout.The database may not be busy. Fixwritefreefreefreeslow lookup first, then borrow SeniorPath
  1. 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.
  2. 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.
  3. A few of those requests take every connection. Each new request now waits in the pool's queue for a connection to come back.
  4. 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.
  5. 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.
Step 1 of 5

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

Section 4 of 8

Trade-offs

OptionGainCostUse when
No poolSimple.A new backend process per request. 2Scripts and one-off jobs.
App-side poolNo extra hop. Every feature works.Total = pods × size.A fixed, small number of instances.
PgBouncer, session modeEvery feature works. 8Saves little. One client still holds one connection.Many short-lived client connections.
PgBouncer, transaction modeMany clients share a few connections.No session state, LISTEN or session locks. 8Many pods or serverless functions.
RDS ProxyManaged. Queues, then rejects. 13Pinning stops sharing. 14You run on RDS and want no pooler to operate.
Raise max_connectionsOne config line.More shared memory, and slower active connections. 3 4Small steps only, after measuring.

Simple rule: small app pools, a sum you have written down, and a transaction-mode pooler once instances multiply.

Section 5 of 8

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_connections before 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, PREPARE and temporary tables.
  • Keep maxLifetime below any timeout in PgBouncer, proxies or load balancers.
Section 6 of 8

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 getconn or manual borrow has a matching return in a finally block or a with block.
  • 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_statements is not 0.
Section 7 of 8

Check yourself

1. Your service has 25 pods, each with a fixed-size pool of 10 (HikariCP's default). Postgres has max_connections = 300. What happens during a deploy that briefly runs 40 pods?

Show answer

The pods need 400 connections, more than the server allows, so some fail to connect. Each pod has its own pool. 25 × 10 = 250 fits, but 40 × 10 = 400 is over the limit, and 3 slots are reserved for superusers.

2. A request starts a transaction, calls a payment API for 4 seconds, then commits. What is the main pool problem?

Show answer

It holds a connection for 4 seconds while doing no database work. The connection is borrowed but idle. A few of these requests can take the whole pool, as in GitHub's October 2026 incident.

3. You move from direct connections to PgBouncer in transaction mode. Which code is most likely to break?

Show answer

A job that takes a session-level advisory lock, then runs several transactions. Session-level advisory locks are not supported in transaction pooling. The next transaction may run on a different server connection.

4. Which pool setting logs a warning when a connection may have leaked?

Show answer

leakDetectionThreshold HikariCP logs a possible leak when a connection has been out of the pool longer than this threshold. It is off by default.

Your progress is saved only in this browser. Export it to keep it safe.

Was this clear?
Report a mistake (opens GitHub in a new tab)
Section 8 of 8

Go deeper

Show 14 sources and related lessons
  1. 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.
  2. 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.
  3. PostgreSQL documentation: 19.3. Connections and Authentication (opens in a new tab)
    max_connections, its default, and the slots reserved for superusers.
  4. 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.
  5. 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.
  6. HikariCP README (brettwooldridge/HikariCP on GitHub) (opens in a new tab)
    Every pool setting with its default, including connectionTimeout, maxLifetime and leakDetectionThreshold.
  7. 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.
  8. PgBouncer features (opens in a new tab)
    The three pooling modes and a table of which Postgres features work in each.
  9. PgBouncer config (opens in a new tab)
    pool_mode, pool sizes, max_prepared_statements, and the note that PgBouncer is single-threaded.
  10. PgBouncer changelog (opens in a new tab)
    Version 1.21.0 adds protocol-level prepared statements; 1.24.0 turns them on by default.
  11. 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.
  12. 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".
  13. 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.
  14. 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

Term

See full entry

Jump to a section

  1. 1What broke
  2. 2The idea in simple words
  3. 3How it works
  4. 4Trade-offs
  5. 5At work
  6. 6With AI
  7. 7Check yourself
  8. 8Go deeper