Belajar
← All lessons

How database transactions work

A transfer that crashes halfway

App
Database
Disk (WAL)

transfer.js

// no transaction: each query commits on its ownawait db.query("UPDATE accounts SET balance = balance - 300 WHERE id = 'ana'");await db.query("UPDATE accounts SET balance = balance + 300 WHERE id = 'budi'"); // one transaction: all or nothingawait db.query("BEGIN");await db.query("UPDATE accounts SET balance = balance - 300 WHERE id = 'ana'");await db.query("UPDATE accounts SET balance = balance + 300 WHERE id = 'budi'");await db.query("COMMIT");

database.js

// what the database does on COMMITwal.append(tx.changes);wal.flush(); // on disk before we answertx.markCommitted(); // and when a client vanishes mid-transactionsocket.on("close", () => {  if (tx.isOpen) tx.rollback();});

Run a transfer yourself BEGIN, COMMIT, ROLLBACK

Amount to move from Ana to Budi300
psql session
Committed, what other sessions see
What your session sees

balance has CHECK (balance >= 0), so taking more than Ana has fails

transfer.sql

CREATE TABLE accounts (  id text PRIMARY KEY,  balance int CHECK (balance >= 0)); BEGIN;UPDATE accounts SET balance = balance - 300 WHERE id = 'ana';UPDATE accounts SET balance = balance + 300 WHERE id = 'budi';COMMIT;   -- both changes become visible together -- or throw the whole thing awayROLLBACK;

Two withdrawals at once the lost update

Session A
Database
Session B

withdraw.js

// A and B both run this, at the same momentasync function withdraw(id, amount) {  await db.query("BEGIN");  const { rows } = await db.query(    "SELECT balance FROM accounts WHERE id = $1" +      " FOR UPDATE", // only in the FOR UPDATE version    [id],  );  const next = rows[0].balance - amount; // computed in the app  await db.query("UPDATE accounts SET balance = $1 WHERE id = $2", [next, id]);  await db.query("COMMIT"); // frees the row lock}

Topics

Next: How SQL joins work

Open lesson