A connection pool runs dry under LLM load because requests hold connections while they wait, not because the pool is small.
We fixed it in two steps: release the database connection before the slow LLM call, then move pooling into PgBouncer's statement mode. That took our backend from about 50 to about 1,500 concurrent AI requests on 20-25 database connections. This post is for engineers running long LLM requests on FastAPI, SQLAlchemy and Postgres. It covers what failed, what fixed it and what it costs.
The numbers come from our own load tests, which stopped at 1,500 concurrent requests for a backend with 10,000 total users. We haven't gone beyond that. A team did this work, and I'm writing up what we learned.
Why did our connection pool run out at 50 concurrent requests?
The app worked until about 50 requests ran at once. Then it slowed down, and it took us weeks to see why: each request held a database connection while it did AI work, so the pool became a hard ceiling.
We used FastAPI's dependency injection to open one session per request:
@app.post("/chat")
async def chat(user_input: str, session: Session = Depends(get_session)):
response = llm.generate(user_input)
session.add(ChatMessage(...))
session.commit()
return response
That's fine for a normal API. Our AI requests were different, because each one was an agent run that could outlive the request. One looked like this:
- The user submits a query, the session opens and a connection is acquired.
- We retrieve context from vectors (5-10 seconds, connection idle).
- We call the LLM (10-30 seconds, connection still idle).
- The agent refines the response (5 seconds, connection still idle).
- The session closes.
The connection did almost no work and was held for the whole request. With 50 users at once, 50 connections sat idle, the pool filled up and new requests queued behind them.
How do you check whether your requests hold connections while they wait?
Ask Postgres while a load test runs:
SELECT state, count(*)
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state;
The Postgres docs define idle in transaction as a backend in a transaction that isn't executing a query, and idle as one waiting for a new client command. If many connections sit in either state while requests are inside an LLM call, you're holding connections you aren't using. Which state you see depends on when your session opens its transaction.
Why doesn't a bigger application-level pool fix it?
Pooling exists because a new connection is expensive. Each one opens a TCP socket, negotiates TLS, authenticates and initializes a session before any query runs.
Setup usually takes 10-50ms, depending on network latency and database load, and PostgreSQL also starts a separate backend process for every connection, so thousands of open connections cost memory long before the database is busy. A pool keeps connections open and lends them out to skip that cost.
The first thing we tried was SQLAlchemy's built-in pool, which keeps pool_size connections open and allows max_overflow extra ones under load. A typical configuration looks like this:
engine = create_engine(
"postgresql://user:password@localhost/db",
poolclass=QueuePool,
pool_size=20, # keep 20 connections open
max_overflow=10, # allow up to 10 more
pool_pre_ping=True # test a connection before using it
)
Ours was a pool of 25, and we kept exhausting it. Bigger pools hit the same wall. At 1,500 concurrent requests, each holding a connection for 20-40 seconds, we'd have been 60 times over capacity. A pool only helps if connections come back quickly, and ours stayed checked out for the whole request.
How do you stop holding a connection while the LLM works?
Do this first, because it needs no new infrastructure. The one-session-per-endpoint pattern was the real bottleneck, so we changed when code asks for a connection: do the AI work with no database access, then open a session, write and close it straight away.
@app.post("/agentic-rag")
async def agentic_rag(query: str):
# 1. AI work, no database access
context = await retrieve_rag_context(query) # 10s
response = await llm.generate(query, context) # 20s
# 2. Now we need the database: get it, use it, release it
session = Session()
try:
session.add(ChatLog(query=query, response=response))
session.commit()
finally:
session.close()
return {"response": response}
Which PgBouncer pool mode fits long-running AI requests?
Releasing connections early shortens how long each one is held. PgBouncer then shares a small set of server connections across every application process. It sits between the application and PostgreSQL, and its pool_mode decides when a connection goes back to the pool:
| Mode | Connection is released | Fits |
|---|---|---|
| Session | When the client disconnects | Web apps with login and logout |
| Transaction | When the transaction finishes | Traditional REST APIs |
| Statement | When the query finishes | Long-running AI workflows |
Transaction mode wasn't enough. If you call an LLM inside a transaction, the connection stays held and idle for the whole call. Statement mode releases it the moment the query finishes, even though the request is still running.
The cost is real. The PgBouncer docs say transactions spanning multiple statements are disallowed in this mode, so each statement has to stand alone. Code that expects several statements to roll back together no longer works:
# Don't do this in statement mode
session.add(ProcessLog(...))
session.flush() # connection goes back to the pool
external_api_call() # no connection held here
session.add(ProcessResult(...))
session.commit() # may use a different connection
How do you set up PgBouncer for this?
Deploy PgBouncer on a dedicated server or container:
docker run -d \
-v /path/to/pgbouncer.ini:/etc/pgbouncer/pgbouncer.ini \
-p 6432:6432 \
pgbouncer:latest
Set statement mode in pgbouncer.ini:
pool_mode = statement
max_client_conn = 2000
default_pool_size = 20
default_pool_size is the number of server connections per user and database pair, and max_client_conn is how many clients may connect to PgBouncer itself. Both are in the PgBouncer config reference.
Then turn off application-level pooling. SQLAlchemy's NullPool opens a connection on checkout and closes it on release, so PgBouncer does all the pooling:
engine = create_engine(
os.getenv("DATABASE_URL"), # points at PgBouncer
poolclass=NullPool
)
The name "null pooling" comes from this SQLAlchemy class. Statement mode is the PgBouncer side of the same setup.
How do you watch it in production?
PgBouncer has an admin console. Connect with psql and use the commands in the usage docs:
psql -h pgbouncer.internal -p 6432 -U pgbouncer -d pgbouncer
show pools; # pool status
show clients; # connected clients
show stats; # performance statistics
| Symptom | Likely cause | What to do |
|---|---|---|
| "no more connections available" | Pool exhausted | Raise max_client_conn and audit how long sessions stay open |
| "connection lost" errors | Stale server connections | Check server_check_query and server_check_delay in PgBouncer |
| Pool slowly fills up | Connection leak | Use try/finally with session.close()
|
What did the load tests show?
We load-tested the change from 50 up to 1,500 concurrent requests:
| Metric | Before | After | Change |
|---|---|---|---|
| Max concurrency | ~50 | ~1,500 | 30x |
| Database RAM | 3.5GB | 400MB | ~9x lower |
| P95 latency at 50 concurrent | 450ms | 95ms | 4.7x faster |
| Database connections | 250+ | 20-25 | 10x fewer |
What to do first
Run the pg_stat_activity query above during a load test. If connections sit idle while requests wait on the LLM, release them before the call, and only then decide whether you need PgBouncer. Raising the pool size won't help.
Thanks to the team I built this with.
Originally published at abubakar-siddik.com.



Top comments (0)