Connection Pooling Implementation in TypeScript
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Connection Pooling runs in O(1) time and O(n) space, in TypeScript as in every other language.
- ✓The runtime is node-postgres or the driver of your choice; TypeScript adds generic row typing (pool.query<UserRow>) and, more usefully, the ability to make the leak structurally impossible.
- ✓Wrap acquire and release in a single higher-order function and export only that, plus a withTransaction variant that issues begin, commit and rollback.
- ✓The TypeScript trap: The type system will not catch a missing release, because acquiring and releasing are ordinary method calls with no linear-type relationship, pool.connect() returns a PoolClient whose type says nothing about the obligation to release it.
- ✓Erased; runtime cost is the driver cost. The wrapper adds one closure per query, which is irrelevant next to a network round trip.
What Connection Pooling actually is
Connection Pooling in TypeScript: what you actually reach for
TypeScript implementation
import pg from 'pg';
import type { PoolClient, QueryResultRow } from 'pg';
const pool = new pg.Pool({ max: 10, connectionTimeoutMillis: 5_000 });
/** The ONLY way to get a client, callers cannot forget to release. */
export async function withClient<T>(fn: (c: PoolClient) => Promise<T>): Promise<T> {
const client = await pool.connect();
try {
return await fn(client);
} finally {
client.release();
}
}
export function withTransaction<T>(fn: (c: PoolClient) => Promise<T>): Promise<T> {
return withClient(async (client) => {
await client.query('begin');
try {
const out = await fn(client);
await client.query('commit');
return out;
} catch (err) {
await client.query('rollback');
throw err;
}
});
}
export async function query<T extends QueryResultRow>(
sql: string,
params: readonly unknown[] = [],
): Promise<T[]> {
const res = await pool.query<T>(sql, params as unknown[]);
return res.rows; // NOTE: <T> is an assertion, not a runtime validation
}
// The pool is never exported: the leak is structurally unreachable.Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe TypeScript-specific trap
Performance in TypeScript, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which TypeScript type or library should I use for Connection Pooling?
The runtime is node-postgres or the driver of your choice; TypeScript adds generic row typing (pool.query<UserRow>) and, more usefully, the ability to make the leak structurally impossible. Expose only a withClient<T>(fn: (c: PoolClient) => Promise<T>): Promise<T> helper and keep the pool private, so no caller ever holds a client they could forget to release. @types/pg provides Pool, PoolClient and QueryResult<T>.
What is the most common TypeScript mistake when implementing Connection Pooling?
The type system will not catch a missing release, because acquiring and releasing are ordinary method calls with no linear-type relationship, pool.connect() returns a PoolClient whose type says nothing about the obligation to release it. That is precisely why the withClient wrapper is the right abstraction rather than a stylistic preference. A second, quieter trap: pool.query<T> does not VALIDATE that rows match T, so a schema change makes the types confidently wrong until something dereferences a missing field.
How does Connection Pooling actually perform in TypeScript?
Erased; runtime cost is the driver cost. The wrapper adds one closure per query, which is irrelevant next to a network round trip. The genuine engineering win is that centralising acquisition gives you exactly one place to add timing, tracing and slow-query logging for every database call in the process. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying for GitHub Copilot, check its student and free-tier options on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.