Lesson 223 of 296
Transactions and ACID
What you will learn
- What a transaction is
- BEGIN, COMMIT and ROLLBACK
- The four ACID properties, explained simply
- Savepoints
- Transactions in application code
- Keeping transactions short
On this page
What is a transaction?
A transaction groups several statements into one unit of work: either all of them take effect, or none do.
The classic example: transfer £30 from Aisha to Ben. Two updates: subtract from Aisha, add to Ben. If the server crashes between them, £30 disappears. Inside a transaction, that cannot happen.
BEGIN;
UPDATE accounts SET balance_pence = balance_pence - 3000 WHERE id = 1;
UPDATE accounts SET balance_pence = balance_pence + 3000 WHERE id = 2;
COMMIT;BEGINstarts the transaction.COMMITmakes all changes permanent and visible to others.ROLLBACKundoes everything since BEGIN.
Tested on PostgreSQL:
BEGIN;
UPDATE products SET price_pence = price_pence + 100 WHERE id = 1;
SELECT price_pence FROM products WHERE id = 1; -- 999 inside the transaction
ROLLBACK;
SELECT price_pence FROM products WHERE id = 1; -- 899 again: the change was undoneIf any statement fails (for example a constraint violation), PostgreSQL marks the transaction as failed and you must roll back. Without an explicit BEGIN, every single statement runs in its own automatic transaction (autocommit).
ACID
The four guarantees of a transaction:
| Letter | Property | Simple meaning | Example |
|---|---|---|---|
| A | Atomicity | All or nothing | Both transfer updates happen, or neither |
| C | Consistency | The database moves from one valid state to another; all constraints hold | A CHECK balance_pence >= 0 makes an overdrawing transfer fail entirely |
| I | Isolation | Concurrent transactions do not see each other's half-finished work (to the degree set by the isolation level, Lesson 224) | Another user never sees the money "in the air" |
| D | Durability | Once committed, data survives crashes and power loss | PostgreSQL writes changes to the write-ahead log (WAL) on disk before confirming the commit |
Consistency in action, on the test database (balance 10000 pence):
UPDATE accounts SET balance_pence = balance_pence - 20000 WHERE id = 1;Result: ERROR: new row for relation "accounts" violates check constraint "accounts_balance_pence_check". Inside a transfer transaction, this error causes a rollback of the whole transfer.
Savepoints
A savepoint is a marker inside a transaction you can roll back to, without undoing everything:
BEGIN;
INSERT INTO orders ...;
SAVEPOINT before_items;
INSERT INTO order_items ...; -- fails
ROLLBACK TO SAVEPOINT before_items; -- undo only the items
COMMIT;ORMs use savepoints to implement nested transactions.
Transactions in application code
With the pg driver, a transaction must run on one connection from the pool (not pool.query, which may use a different connection each time):
import type { Pool } from "pg";
export async function transfer(pool: Pool, fromId: number, toId: number, amountPence: number): Promise<void> {
if (amountPence <= 0) throw new Error("Amount must be positive");
const client = await pool.connect();
try {
await client.query("BEGIN");
await client.query("UPDATE accounts SET balance_pence = balance_pence - $1 WHERE id = $2", [amountPence, fromId]);
await client.query("UPDATE accounts SET balance_pence = balance_pence + $1 WHERE id = $2", [amountPence, toId]);
await client.query("COMMIT");
} catch (err) {
await client.query("ROLLBACK");
throw err;
} finally {
client.release();
}
}finallyalways returns the connection to the pool, even after errors. Forgettingrelease()leaks connections until the pool is exhausted and the app hangs.balance_pence - $1is computed by the database, which avoids the lost-update problem shown in Lesson 225.- Prisma uses
prisma.$transaction(...)(Lesson 230).
Keep transactions short
While a transaction is open it may hold locks that block other users. Never:
- Call an external API (payment provider, email) inside a transaction.
- Wait for user input inside a transaction.
- Do slow work between statements.
Do the slow work before or after; use the outbox pattern (Lesson 204) to trigger side effects after commit.
How to say it in an interview
"A transaction groups statements so they all commit or all roll back. ACID means atomicity, all or nothing; consistency, constraints always hold, so a CHECK on balance makes an invalid transfer fail as a whole; isolation, concurrent transactions do not see each other's partial work to the level configured; and durability, committed data survives crashes thanks to the write-ahead log. In Node I run a transaction on a single pooled client with BEGIN, COMMIT, ROLLBACK in catch and release in finally, do arithmetic in SQL, and keep transactions short with no external calls inside."
Key words
| Word | Meaning |
|---|---|
| Transaction | A group of statements that succeed or fail together |
| COMMIT / ROLLBACK | Make permanent / undo |
| Autocommit | Each statement is its own transaction |
| ACID | Atomicity, Consistency, Isolation, Durability |
| Write-ahead log | A log written to disk before changes are confirmed |
| Savepoint | A point inside a transaction to roll back to |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.