Skip to content

Lesson 6 of 14 · 22m

Pools, Transactions, and the Check-Then-Write Race

Postgres connections are processes with a `max_connections` ceiling — pool them, transact multi-writes, and let constraints beat races.

A PostgreSQL connection is a forked backend process holding roughly 10 MB of memory, and max_connections defaults to 100. An API that opens a Client per request is a service that melts at the 101st concurrent request with FATAL: sorry, too many clients — SQLSTATE 53300. Nearly everything about real data access flows from those two numbers.

The pool is a queue you didn't know you had

import { Pool } from "pg";
const pool = new Pool({ connectionString: url, max: 10 });
const { rows } = await pool.query("SELECT 1"); // borrow, run, return

pool.query borrows a connection, runs, returns it. max: 10 means the eleventh concurrent query waits — and that queue is where "the database is slow" mysteries live: the query took 4 ms, the nine requests ahead of it took 900. Size it with arithmetic, not vibes: replicas × pool.max < max_connections − headroom, reserving slots for migrations and other services. Set statement_timeout so one bad query cannot squat on a slot forever, idle_in_transaction_session_timeout so a leaked transaction cannot hold one, and connectionTimeoutMillis so pool exhaustion fails fast instead of hanging handlers. The arithmetic once, concretely: five replicas at max: 10 is fifty backend slots — half a default max_connections before migrations or a psql session take theirs. And pool.on('error', …) is not optional: a backend killed underneath you surfaces as an idle-client error, and with no handler it is an uncaught exception.

Transactions are the only atomicity you get

const client = await pool.connect();
try {
  await client.query("BEGIN");
  await client.query("UPDATE accounts SET balance = balance - $1 WHERE id = $2", [amt, a]);
  await client.query("UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amt, b]);
  await client.query("COMMIT");
} catch (e) {
  await client.query("ROLLBACK");
  throw e;
} finally {
  client.release();
}

Two writes or zero — that is what COMMIT buys. The default isolation level is read committed: each statement sees the latest committed row, which is why the check-then-write race exists at all. FOR UPDATE locks the row you're about to mutate; FOR UPDATE SKIP LOCKED is the trick that turns a Postgres table into a workable job queue — workers skip rows others hold. And the rule juniors break first: never hold a borrowed connection across an await fetch() to another service. You are queueing your database behind somebody else's latency. Higher isolation levels change the contract too: serializable trades the anomalies away for 40001 serialization failures the client is expected to retry — correctness bought with a retry loop. Note the finally is load-bearing: forget client.release() once and the pool quietly shrinks by one per leaked transaction until requests queue forever.

The check-then-write race

// WRONG — two concurrent requests both see 'no user', both insert:
if (!(await exists(email))) await insert(email);

// RIGHT — the constraint is atomic; the race cannot exist:
await db.query(
  "INSERT INTO users(email) VALUES($1) ON CONFLICT(email) DO NOTHING",
  [email]
);

Checking first is a bug that only appears under concurrency — which is to say, in production. Uniqueness is enforced by a UNIQUE constraint, not an if. Same family: pg_advisory_lock for claiming one owner of a scheduled job across replicas — SELECT pg_try_advisory_lock($1) claims a key cluster-wide, and the lock dies with the session, so a crashed worker releases it for free.

Poolers trade features for scale

PgBouncer in pool_mode=transaction multiplexes many clients onto few backend connections — which silently breaks session-scoped features: SET, advisory locks, LISTEN, temp tables, anything that lives outside one transaction. Named prepared statements used to be on that casualty list; since PgBouncer 1.21, max_prepared_statements tracks them per client and rewrites the protocol names — the one exception, and only when enabled. The feature that tripped it is worth naming: a name: field on a node-postgres query config is what creates a named prepared statement in the first place. pool_mode=session keeps the features and gives up the multiplexing; pgcat is the Rust take on the same trade, Supabase's Supavisor the Elixir one, RDS Proxy the managed version. Know which mode you're in before blaming the driver. Drizzle, Knex, and Prisma all sit on pools; bun:sqlite is synchronous by design (fine — SQLite runs in-process), and Node added node:sqlite in 22.5. Migrations are versioned DDL files, not hand edits — bun run db:migrate or your ORM's equivalent, run forward, in order, before the new code ships.

// Runnable: the pool queue idea
const poolMax = 10, inflight = 23;
console.log("queries running:", Math.min(poolMax, inflight));
console.log("queued:", Math.max(0, inflight - poolMax));

The practice

One pool per process, sized against max_connections; transactions for multi-write; constraints over checks; timeouts on the pool itself; never await a network call while holding a connection.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.