Writing Database Connection Pool Code With LLMs in November 2026: Create One Pool Per Process, Always Release in finally, and Size It Against Your Database's Connection Limit
Ask an AI coding assistant to "connect to Postgres" and you will almost always get code that works on your laptop. The query runs, the test passes, and you move on. The trouble shows up later: under real traffic the app starts hanging, requests time out waiting for a connection, or the database starts refusing logins with "too many clients already." Almost every one of those failures traces back to how the connection pool was set up, and connection pool code is exactly the kind of thing LLMs get subtly wrong because it looks fine until there is load.
This post walks through what a connection pool actually does, the specific mistakes generated code tends to make, and a short checklist you can hand to the model (and to yourself) before the code ships. Examples use Node.js with node-postgres and Python with SQLAlchemy, but the same ideas apply to HikariCP in Java, database/sql in Go, and most other drivers.
What a connection pool is for
Opening a database connection is expensive. There is a TCP handshake, usually TLS, authentication, and on PostgreSQL a new backend process on the server for every connection. Doing that for every request adds latency and puts real load on the database.
A pool keeps a small set of open connections and lends them out. Your code borrows one, runs its queries, and gives it back. If all connections are busy, the next caller waits in line until one is returned, or until a timeout fires. That is the whole idea, and it leads to three rules that most pool bugs break:
- There should be one pool per process, created once and shared.
- Every borrowed connection must be returned, on every code path, including errors.
- The pool's maximum size, multiplied by the number of processes, must fit inside the database's connection limit.
A connection pool works like a store's supply of carts: a fixed number, shared by everyone, and it only works if each one gets returned. Image: We provide shopping carts for your convenience. Please return them to the store or cart corrals. by dankeck, CC0, via Wikimedia Commons.
Mistake 1: creating a pool inside the request handler
This is the most common thing generated code gets wrong, especially when you ask for "an endpoint that reads users from the database." The model writes a self-contained function, and to make it self-contained it creates the pool right there:
// Don't do this
app.get("/users/:id", async (req, res) => {
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const { rows } = await pool.query("SELECT * FROM users WHERE id = $1", [req.params.id]);
res.json(rows[0]);
});
Every request now builds a brand-new pool, opens a fresh connection, and never closes the pool. Under load you open connections faster than idle timeouts clean them up, and the database hits its limit. The fix is to create the pool once, at module load, and import it wherever you need it:
// db.js
import pg from "pg";
export const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
max: 10, // most connections this process will open
idleTimeoutMillis: 30_000, // close connections idle this long
connectionTimeoutMillis: 5_000 // fail instead of waiting forever for a free slot
});
pool.on("error", (err) => {
// An idle client hit an error (for example, the server restarted).
console.error("Unexpected error on idle database client", err);
});
// routes.js
import { pool } from "./db.js";
app.get("/users/:id", async (req, res) => {
const { rows } = await pool.query("SELECT id, email FROM users WHERE id = $1", [req.params.id]);
res.json(rows[0] ?? null);
});
The same applies in Python. A SQLAlchemy Engine owns the pool, so create_engine() belongs at module level, not inside a function that runs per request:
# db.py
from sqlalchemy import create_engine
engine = create_engine(
DATABASE_URL,
pool_size=5, # connections kept open
max_overflow=5, # extra connections allowed during bursts
pool_timeout=5, # seconds to wait for a free connection
pool_recycle=1800, # replace connections older than 30 minutes
pool_pre_ping=True, # test a connection before handing it out
)
When you prompt the model, say it directly: "Create the pool once in a shared module and import it. Never create a pool or engine inside a request handler."
Mistake 2: borrowing a connection and not giving it back
For a single query, pool.query() in node-postgres borrows and returns the connection for you. But transactions need several queries on the same connection, so you have to check one out with pool.connect() and release it yourself. This is where leaks come from. Generated code often looks like this:
// Leaks a connection whenever a query throws
const client = await pool.connect();
await client.query("BEGIN");
await client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
await client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
await client.query("COMMIT");
client.release();
If either UPDATE throws, the code never reaches ROLLBACK or release(). The connection stays checked out with an open transaction. Do that ten times with a pool of ten and every later request waits until it times out. The app looks "hung" while the database looks mostly idle, which is a confusing combination to debug at 2 a.m.
The fix is try/catch/finally, with the release in finally so it runs on every path:
export async function transfer(from, to, amount) {
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amount, from]);
await client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to]);
await client.query("COMMIT");
} catch (err) {
await client.query("ROLLBACK").catch(() => {});
throw err;
} finally {
client.release();
}
}
Even better, write this once as a helper so nobody has to remember the pattern:
export async function withTransaction(fn) {
const client = await pool.connect();
try {
await client.query("BEGIN");
const result = await fn(client);
await client.query("COMMIT");
return result;
} catch (err) {
await client.query("ROLLBACK").catch(() => {});
throw err;
} finally {
client.release();
}
}
In Python, the context manager does the same job. with engine.begin() as conn: commits on success, rolls back on an exception, and returns the connection to the pool either way. If the model writes conn = engine.connect() without a with block, ask it to rewrite.
Watch for early returns as well. A handler that checks out a client, then does if (!user) return res.status(404)... before the release line, leaks a connection on every 404. A finally block covers that case too.
Mistake 3: sizing the pool without doing the math
LLMs tend to pick a pool size that sounds generous, like 50 or 100, because "more connections means more throughput." It usually doesn't. A database server has a limited number of CPU cores and disks, and past a certain point extra concurrent queries just compete with each other. More importantly, there is a hard ceiling: PostgreSQL's max_connections setting, which defaults to 100, and managed providers often set their own limits per plan.
The number that matters is the total across every process that talks to the database:
total connections = (pool max + overflow) × processes per server × servers
+ migrations, cron jobs, admin tools, monitoring
A concrete example: four app containers, each running two worker processes, each with a pool max of 20. That is 4 × 2 × 20 = 160 connections, which already exceeds a default limit of 100 before you open a single psql session. Drop the pool max to 10 and you are at 80, leaving headroom for migrations and for you to log in during an incident.
Steps to size it:
- Look up the real connection limit:
SHOW max_connections;in PostgreSQL, or your provider's documentation for your plan. - Subtract a reserve for admin access, migrations, and background jobs. Keeping 10 to 20 percent free is a sensible starting point.
- Count how many processes will run at peak, including during deploys, when old and new instances can overlap.
- Divide the remainder by that count. That is your per-process maximum, including any overflow setting.
- Start smaller than that number and raise it only if you see requests waiting for connections while the database still has spare capacity.
Give the model these numbers. "We run 4 containers with 2 workers each and the database allows 100 connections. Size the pool and show the math." It will do the arithmetic correctly when it has the inputs. It cannot guess your deployment from the code.
A docking station has a fixed number of bikes. Size your pool the same way: count every rider across every process before you decide how many to keep. Image: Barclays Bike Docking Station, Hyde Park by David Anstiss, CC BY-SA 2.0, via Wikimedia Commons.
Mistake 4: no timeouts anywhere
Defaults vary by library, and some of them wait forever. In node-postgres, connectionTimeoutMillis defaults to 0, which means a caller waits indefinitely for a free connection. When the pool is exhausted, requests pile up silently instead of failing.
You want timeouts at three levels:
- Waiting for a connection from the pool.
connectionTimeoutMillisin node-postgres,pool_timeoutin SQLAlchemy,connectionTimeoutin HikariCP. A few seconds is usually right for a web request. Failing fast with a clear error is better than a request that hangs for a minute. - How long a single query can run. In PostgreSQL,
statement_timeoutcancels runaway queries on the server side. You can set it per role, per database, or per connection. - How long a transaction can sit idle. PostgreSQL's
idle_in_transaction_session_timeoutends sessions that opened a transaction and then stopped doing anything, which is exactly what a leaked connection from Mistake 2 looks like. It also releases the locks that transaction was holding.
Setting the server-side timeouts on the application's database role means every connection gets them without changing code:
ALTER ROLE app_user SET statement_timeout = '15s';
ALTER ROLE app_user SET idle_in_transaction_session_timeout = '60s';
Pick values that fit your workload. A reporting job may legitimately need longer queries, so give it its own role with its own limits rather than raising the limit for the whole app.
Mistake 5: ignoring serverless and many-instance deployments
On serverless platforms, each function instance has its own memory and therefore its own pool. Scale up to a few hundred concurrent instances and even a pool max of 5 can mean hundreds or thousands of connections. A generated example that works perfectly in a long-running server can overwhelm the database once it runs in a serverless function.
Options, roughly in order of how often they fit:
- Use an external connection pooler such as PgBouncer, or the pooled connection endpoint your database provider offers. Your app connects to the pooler, and the pooler keeps a small number of real connections to the database.
- Keep the in-process pool tiny, often a max of 1 to 3 per instance, and create it outside the handler so warm invocations reuse it.
- Use the provider's HTTP or serverless driver if it has one, which avoids holding long-lived TCP connections from each instance.
One thing to check when you add a pooler: in PgBouncer's transaction pooling mode, consecutive transactions from your app may run on different server connections. Session-level state such as SET commands, session advisory locks, temporary tables, and LISTEN does not carry over reliably. Named prepared statements have also been a historical source of errors in that mode, although recent PgBouncer versions added support for them when configured. Tell the model which pooler and mode you use, and ask it to flag any code that depends on session state.
Mistake 6: no visibility into the pool
When things slow down, you need to know whether the pool is the bottleneck. Most pools expose counters. In node-postgres, pool.totalCount, pool.idleCount, and pool.waitingCount tell you how many connections exist, how many are free, and how many callers are queued. Log or export those periodically:
setInterval(() => {
console.log(JSON.stringify({
msg: "db_pool",
total: pool.totalCount,
idle: pool.idleCount,
waiting: pool.waitingCount
}));
}, 30_000).unref();
A waiting count that stays above zero means requests are queuing for connections. If the database itself is not busy at the same time, suspect a leak or a pool that is too small. On the database side, this query shows what every connection is doing:
SELECT state, count(*)
FROM pg_stat_activity
WHERE datname = current_database()
GROUP BY state;
Many rows in idle in transaction point straight back at Mistake 2.
Shutting down cleanly
When the process stops, close the pool after in-flight requests finish: await pool.end() in node-postgres, engine.dispose() in SQLAlchemy. Otherwise connections linger on the server until it notices the client is gone. In test suites, forgetting this is why the test runner hangs after all tests pass.
A prompt checklist for pool code
Paste something like this along with your request:
- Create the pool or engine once in a shared module. Never create one per request or per function call.
- Use the library's single-query helper for one-off queries. For transactions, check out a connection and release it in
finally, with aROLLBACKon error. - Here is our deployment: [number of instances, workers per instance, database connection limit]. Size the pool and show the math, leaving headroom.
- Set a timeout for acquiring a connection. Suggest
statement_timeoutandidle_in_transaction_session_timeoutvalues for our app role. - We run on [long-running servers / serverless] with [no pooler / PgBouncer in transaction mode]. Flag anything that depends on session state.
- Log pool counters and close the pool on shutdown.
How to test it before production
Pool bugs hide under light traffic, so test under pressure on purpose:
- Force a leak check. Set the pool max to 2 in a test environment, then call an endpoint that fails partway through a transaction ten times in a row. If the eleventh normal request still succeeds, your error paths release connections correctly.
- Exhaust the pool. Send more concurrent requests than the pool max with a slow query, for example
SELECT pg_sleep(2). Requests beyond the limit should wait, then fail with a clear timeout error after the acquire timeout, not hang. - Restart the database while the app is running. The app should log errors, recover, and serve requests again once the database is back, without needing a restart of its own.
- Check the real connection count in
pg_stat_activityduring a load test and compare it with the math you did for sizing.
The short version
An LLM will happily write database code that connects, queries, and returns the right rows. What it can't know is how many copies of your app run, what your database's limit is, or which code paths fail halfway through. Create one pool per process, release every connection in finally, size the pool against the real connection limit across all your processes, put timeouts on waiting and on queries, and test with a deliberately tiny pool. Do those five things and most "the database is down" incidents that are really "the pool is exhausted" incidents go away.
Comments
Post a Comment