Transactions and migrations
Overview
Two topics that keep a database trustworthy:
- Transactions make a group of changes all-or-nothing, so a crash or error halfway through can’t leave your data half-updated.
- Migrations make changes to the database structure — new tables, new columns — repeatable and version-controlled, so every developer’s machine, the test server and production all have the same schema.
Why transactions?
Moving ₹500 from Asha’s wallet to Ravi’s takes two updates. What if the server crashes after the first?
await pool.query('UPDATE wallets SET balance = balance - 500 WHERE user_id = $1', [asha]);
// 💥 crash here — Asha has lost ₹500 and Ravi never received it
await pool.query('UPDATE wallets SET balance = balance + 500 WHERE user_id = $1', [ravi]);Inside a transaction, Postgres guarantees that either every statement takes effect (COMMIT) or none of them do (ROLLBACK). Other connections never see the half-finished state.
Transactions with pg
A transaction must run entirely on one connection. pool.query() might use a different connection each time, so check one out with pool.connect():
const client = await pool.connect();
try {
await client.query('BEGIN');
await client.query('UPDATE wallets SET balance = balance - $1 WHERE user_id = $2', [500, asha]);
await client.query('UPDATE wallets SET balance = balance + $1 WHERE user_id = $2', [500, ravi]);
await client.query('INSERT INTO transfers (from_id, to_id, amount) VALUES ($1, $2, $3)', [asha, ravi, 500]);
await client.query('COMMIT');
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release(); // ALWAYS give the connection back
}Forgetting client.release() leaks a connection. Leak ten and the pool is empty — every request waits forever. The finally block makes sure it always happens.
A reusable helper
That boilerplate is easy to get wrong, so write it once:
// src/db.js
export async function withTransaction(work) {
const client = await pool.connect();
try {
await client.query('BEGIN');
const result = await work(client);
await client.query('COMMIT');
return result;
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
}await withTransaction(async (client) => {
await client.query('UPDATE wallets …', […]);
await client.query('UPDATE wallets …', […]);
});Throw anywhere inside — a validation failure, a database error — and everything is rolled back.
Race conditions and locking
Transactions alone don’t stop two requests from reading the same value at the same moment. Imagine a course with one seat left and two students clicking “Enrol” simultaneously: both read seats_taken = 29 of 30, both decide there’s room, both enrol — 31 students.
Lock the row you’re about to change with SELECT … FOR UPDATE. The second transaction waits until the first commits, then reads the updated value:
await withTransaction(async (client) => {
const { rows: [course] } = await client.query(
'SELECT seat_limit, seats_taken FROM courses WHERE id = $1 FOR UPDATE',
[courseId],
);
if (course.seats_taken >= course.seat_limit) throw new HttpError(409, 'Course is full');
// …insert enrolment, increment seats_taken
});Alternatives: a single atomic statement (UPDATE courses SET seats_taken = seats_taken + 1 WHERE id = $1 AND seats_taken < seat_limit RETURNING id), or database constraints (CHECK (seats_taken <= seat_limit), UNIQUE (user_id, course_id)). Constraints are the strongest defence — the database itself refuses bad data.
Keep transactions short. Don’t call external APIs or wait for user input inside one; locks are held until it ends, and other requests queue behind them.
Migrations
Your schema changes as the app grows: new tables, new columns, new indexes. These changes must happen identically on every database — your laptop, a teammate’s, CI, staging, production — and in the right order.
A migration is a script for one schema change. Migrations are numbered, committed to Git with your code, and run in order. The database records which ones it has already applied, so each runs exactly once.
-- migrations/002_create_courses.sql
CREATE TABLE courses (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL,
description text NOT NULL DEFAULT '',
level text NOT NULL DEFAULT 'Beginner'
CHECK (level IN ('Beginner', 'Intermediate', 'Advanced')),
status text NOT NULL DEFAULT 'draft',
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE UNIQUE INDEX courses_title_lower_idx ON courses (lower(title));A minimal migration runner
Tools such as node-pg-migrate, Knex, or your ORM’s migration command do this for you. But a basic runner is only a few lines, and shows exactly how they work:
// scripts/migrate.js
import { readdir, readFile } from 'node:fs/promises';
import path from 'node:path';
import { pool, withTransaction } from '../src/db.js';
const dir = path.join(import.meta.dirname, '..', 'migrations');
await pool.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
name text PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT now()
)`);
const { rows } = await pool.query('SELECT name FROM schema_migrations');
const applied = new Set(rows.map((r) => r.name));
const files = (await readdir(dir)).filter((f) => f.endsWith('.sql')).sort();
for (const file of files) {
if (applied.has(file)) continue;
const sql = await readFile(path.join(dir, file), 'utf8');
await withTransaction(async (client) => {
await client.query(sql);
await client.query('INSERT INTO schema_migrations (name) VALUES ($1)', [file]);
});
console.log(`Applied ${file}`);
}
await pool.end();{ "scripts": { "db:migrate": "node --env-file=.env scripts/migrate.js" } }Each migration runs inside a transaction (Postgres supports transactional schema changes), so a failing migration leaves nothing half-done.
Migration rules
- Never edit a migration that has run anywhere shared. Write a new one that changes things further.
- Run migrations as a deployment step, before the new code starts — not from inside every app process.
- Make changes backwards-compatible so old and new code can run side by side during a deploy. To rename a column: add the new one, copy data, deploy code that uses it, and only later drop the old one.
- Add indexes for columns you filter or join on. On big production tables, use
CREATE INDEX CONCURRENTLY(outside a transaction) so writes aren’t blocked.
Seed data
A seed script fills a development database with sample data, so new developers have something to work with straight away:
{ "scripts": { "db:seed": "node --env-file=.env scripts/seed.js", "db:reset": "npm run db:migrate && npm run db:seed" } }Seeds are for development and tests — never run them against production.
Schema changes are code changes. Review them in pull requests, test them in CI against a real database, and deploy them through your pipeline — never by hand in a production console.
Enrol with a seat limit
Write enrol(userId, courseId) using a transaction. Lock the course row, check seats_taken < seat_limit, insert into enrolments, and increment seats_taken. Throw a 409 error if the course is full or the user is already enrolled (unique constraint).
import { withTransaction } from './db.js';
export async function enrol(userId, courseId) {
// your code here
}import { withTransaction } from './db.js';
import { HttpError } from './errors.js';
export async function enrol(userId, courseId) {
return withTransaction(async (client) => {
const { rows: [course] } = await client.query(
'SELECT seat_limit, seats_taken FROM courses WHERE id = $1 FOR UPDATE',
[courseId],
);
if (!course) throw new HttpError(404, 'Course not found');
if (course.seats_taken >= course.seat_limit) throw new HttpError(409, 'Course is full');
try {
await client.query(
'INSERT INTO enrolments (user_id, course_id) VALUES ($1, $2)',
[userId, courseId],
);
} catch (err) {
if (err.code === '23505') throw new HttpError(409, 'Already enrolled');
throw err;
}
await client.query('UPDATE courses SET seats_taken = seats_taken + 1 WHERE id = $1', [courseId]);
});
}Summary
- A transaction groups statements so they all commit or all roll back.
- Run every statement of a transaction on the same client from
pool.connect(), and always release it. - A
withTransactionhelper handles BEGIN, COMMIT, ROLLBACK and release in one place. SELECT … FOR UPDATElocks rows to prevent races between concurrent requests.- Migrations are numbered SQL files that change the schema in order, run once each, and are committed with the code.