The one-line mental model
A Node database layer is a shared, finite resource wrapped in an API: the driver multiplexes your queries onto pooled connections, and every decision about pooling, transactions and query shape either protects that resource or quietly exhausts it.
By the end of this lesson you will be able to justify a pool size for your workload, write a Prisma or Mongoose query that does not block the event loop, ship a schema change without a maintenance window, and recognise an N+1 pattern in a code review before it reaches production.
Prerequisites
- !Node.js modules and async functions
- !Basic SQL: joins, indexes and transactions
What You'll Learn
- 1Compare drivers, query builders and ORMs against real constraints
- 2Size a connection pool and explain why bigger is not safer
- 3Write migrations that are reversible and safe under load
- 4Detect and fix N+1 and unindexed query patterns
Driver, builder or ORM
Every option trades control for convenience, and the right answer depends on how much of the query you need to see.
| Layer | Examples | Best when | Cost |
|---|---|---|---|
| Raw driver | pg, mysql2, mongodb | You need exact SQL, cursors or bulk COPY | You own parameterisation, pooling and row mapping |
| Query builder | Knex, Kysely | Mixed read/write logic with dynamic filters | Migrations and SQL are still mostly yours |
| Typed ORM | Prisma, TypeORM | CRUD-heavy apps where types must travel end to end | Learning curve, generated clients, occasional leaky abstractions |
| Document ODM | Mongoose | Flexible schemas with validation and middleware | Weak joins, schema drift, implicit casting surprises |
A useful rule: if your workload is dominated by analytics queries, window functions or batch updates, a builder keeps the SQL legible; if it is dominated by entity CRUD behind an API, an ORM removes hundreds of lines of mapping. Teams often run Prisma for application entities and the raw pg driver for reporting jobs, which is a perfectly healthy combination.
Whatever you choose, one rule is non-negotiable: always parameterise user input. String concatenation into SQL is not merely a security hole, it also defeats the database's plan cache, so the same query with a different literal compiles again every time.
Pooling: the constraint people get wrong
Node gives you one thread, but databases expect many concurrent sessions. A pool sits between them: your handlers borrow a connection, run a query, and return it. Every connection that sits idle in your pool is a session the database must maintain, and every query waiting for a free connection adds latency you cannot observe without metrics.
import { Pool } from 'pg';
const pool = new Pool({
host: process.env.PGHOST,
database: process.env.PGDATABASE,
max: 20, // ceiling: keep well under database max_connections
idleTimeoutMillis: 30_000,
connectionTimeoutMillis: 2_000,
statement_timeout: 10_000,
});
pool.on('error', (err) => console.error('idle client error', err));
export async function query(text, params) {
const started = Date.now();
try {
const res = await pool.query(text, params);
if (Date.now() - started > 500) {
console.warn({ text, ms: Date.now() - started, rows: res.rowCount });
}
return res.rows;
} catch (err) {
if (err.code === '40001' || err.code === '40P01') throw err; // retryable
console.error({ text, code: err.code, message: err.message });
throw err;
}
}
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();
}
}
Sizing starts from the database, not the app. A cluster allowing 100 connections shared by six API instances gives you roughly 16 each, so set max below that and let queueing happen visibly. A common starting point is 2Ã the effective CPU core count of the database, adjusted upward only when metrics show connections saturated while CPU is idle. The real danger is a transaction that holds a connection while waiting on an external API: a pool of twenty can be drained by twenty slow calls, and every other request queues behind them.
Prisma with PostgreSQL
Prisma generates a typed client from a declarative schema, which makes relationships and migrations explicit.
// schema.prisma
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Customer {
id String @id @default(cuid())
email String @unique
country String
orders Order[]
createdAt DateTime @default(now())
}
model Order {
id String @id @default(cuid())
totalCents Int
status String @default("pending")
customer Customer @relation(fields: [customerId], references: [id])
customerId String
createdAt DateTime @default(now())
@@index([customerId, status])
@@index([createdAt])
}
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient({ log: ['warn', 'error'] });
// One query with an explicit include beats two round trips
const orders = await prisma.order.findMany({
where: { status: 'paid', customer: { country: 'DE' } },
orderBy: { createdAt: 'desc' },
take: 50,
include: { customer: { select: { email: true, country: true } } },
});
// Atomic multi-record write: both rows commit or neither does
const created = await prisma.$transaction([
prisma.order.create({ data: { totalCents: 4999, customerId: 'cus_1' } }),
prisma.customer.update({ where: { id: 'cus_1' }, data: { lastOrderAt: new Date() } }),
]);
console.log(orders.length, created[0].id);
await prisma.$disconnect();
Generated types give you editor completion on every filter, which catches typos such as a misspelled column before the query runs. The trap is findMany inside a loop: it looks clean and produces one query per iteration. Batch with findMany({ where: { id: { in: ids } } }) or createMany instead.
Mongoose: validation, lean reads and change streams
Document databases trade joins for application-side modelling, and Mongoose supplies the schema, validation and lifecycle hooks that Mongo itself does not enforce.
import mongoose from 'mongoose';
const eventSchema = new mongoose.Schema({
userId: { type: String, required: true, index: true },
type: { type: String, enum: ['click', 'view', 'purchase'], required: true },
amount: { type: Number, min: 0, default: 0 },
occurredAt: { type: Date, default: Date.now },
}, { timestamps: true });
eventSchema.index({ userId: 1, occurredAt: -1 });
export const Event = mongoose.model('Event', eventSchema);
await mongoose.connect(process.env.MONGO_URI, { serverSelectionTimeoutMS: 3000 });
// lean() skips building full documents: cheaper for read-only list endpoints
const recent = await Event.find({ userId: 'u_9' })
.sort({ occurredAt: -1 })
.limit(20)
.lean();
const total = await Event.aggregate([
{ $match: { occurredAt: { $gte: new Date(Date.now() - 7 * 864e5) } } },
{ $group: { _id: '$type', count: { $sum: 1 }, revenue: { $sum: '$amount' } } },
]);
Two Mongoose behaviours cause most production incidents. Casting is silent: assigning a string to a Number field throws only when you save, so invalid input surfaces far from the request handler. And because there are no joins, populating a reference per row recreates the N+1 problem in a different costume; aggregate with $lookup for reporting instead of looping over populate.
Migrating without a maintenance window
Schema changes are where uptime is lost. The safe pattern is expand, migrate, contract: add new columns as nullable or defaulted, backfill in batches, switch the application to read and write both shapes, then remove the old column in a later deploy.
// scripts/migrate.js â run with: node scripts/migrate.js 2026-03-01-batch-index
import { readdirSync } from 'node:fs';
import { withTransaction, query } from '../src/db.js';
const [, , name] = process.argv;
if (!name) throw new Error('usage: node scripts/migrate.js <migration-name>');
const files = readdirSync(new URL('./migrations/', import.meta.url))
.filter((f) => f.endsWith('.js'))
.sort();
const { up, down } = await import(`./migrations/${name}.js`);
await withTransaction(async (client) => {
await client.query(
'CREATE TABLE IF NOT EXISTS schema_migrations (name text PRIMARY KEY, applied_at timestamptz DEFAULT now())'
);
const applied = await client.query('SELECT name FROM schema_migrations');
if (applied.rows.some((r) => r.name === name)) {
console.log(`${name} already applied, skipping`);
return;
}
await up(client);
await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [name]);
console.log(`applied ${name}`);
});
console.log(`applied ${files.length} migrations available, ${name} complete`);
Backfills deserve the same discipline: update in bounded batches of a few thousand rows with a short sleep between them, so replication lag stays flat and locks are released quickly. Never issue one UPDATE across a table of tens of millions of rows inside a single transaction.
Retries, timeouts and the errors you must handle
Databases fail in ways that look like application bugs: a connection resets mid-query, a primary fails over, a deadlock is chosen as the victim, or a statement simply runs too long. Each of those errors has a different correct response, and treating them all the same either hides outages or multiplies them.
Classify before you retry. Serialization failures and deadlocks are safe to retry immediately with the same transaction, because the database already rolled you back cleanly. Connection timeouts are ambiguous: the statement may have committed, so retrying a non-idempotent insert can duplicate a row, and the safe move is to use an idempotency key or check for an existing record first. Constraint violations are never retryable, they are a logic or data problem that must surface to the caller. Authentication and permission errors indicate configuration drift and should page someone rather than spin.
Timeouts are equally important on both sides. A statement timeout bounds how long the database works on your query, and a connect timeout bounds how long you wait to start; without both, one wedged query can exhaust your pool and cascade across every endpoint that shares it. Set them per call site where the workload differs: a report can wait ten seconds, an autocomplete endpoint cannot. Log the timeout class along with the query fingerprint so on-call can tell a slow index from a missing one at 3 a.m.
Idempotency completes the picture. Give mutating endpoints a client-supplied key, store the first response against it, and return the stored result when the same key arrives again. That single pattern absorbs client retries, gateway timeouts and mobile users on flaky networks without producing duplicate orders, which is exactly the failure that makes stakeholders lose trust in the API.
Common Mistakes
Creating a new pool per request or per module instance
Fix: Create one shared pool at startup and import it, so the database sees a bounded number of sessions
Awaiting a query inside a for loop over hundreds of ids
Fix: Fetch with an IN clause, use createMany, or load a mapping table once and join in memory
Running a destructive column drop in the same release that stops reading it
Fix: Split into expand, migrate and contract deploys separated by at least one release
Letting a slow external call happen while a transaction holds a connection
Fix: Commit first or fetch the external data before opening the transaction
Best Practices
- Set statement_timeout and connectionTimeoutMillis so runaway queries fail loudly
- Add composite indexes that match the WHERE and ORDER BY of your hottest queries
- Log slow queries with duration and row count, and alert on the trend rather than one-off spikes
- Wrap multi-statement writes in a transaction with explicit retry on serialization failures
- Run migrations from CI against a snapshot, not by hand against production
Interview Questions
Q1: How would you size a PostgreSQL pool for a Node API?
Start from the database budget: max_connections divided by the number of instances, capped near 2Ã the DB CPU cores, then tune using saturation and queue-wait metrics.
Q2: What is the N+1 query problem and how do you fix it?
A loop issues one query per parent row, turning N rows into N+1 round trips; fix it with a batched IN query, a join, or an aggregate.
Q3: Why use lean() in Mongoose?
It returns plain objects without hydrating full documents, which reduces allocation and construction cost on read-heavy endpoints.
Q4: Describe an expand-migrate-contract rollout.
Add the new shape, backfill in batches, dual-read and dual-write, then drop the old shape in a later deploy so no version of the app sees a missing column.
Key Takeaways
- Choose the lowest layer that still gives you the safety you need; raw SQL and ORMs can coexist
- Pool size is a database budget, not a concurrency dial; unbounded connections cause outages elsewhere
- Parameterise everything: security and plan-cache reuse come together
- N+1 appears in both relational and document data models; batch or aggregate instead
- Schema changes need expand, backfill, switch and contract as separate, reversible steps