← Back to Backend, page 2

backend-0029 · Easy fresher

What does ACID mean for database transactions, and how do you use a transaction to make a multi-step change all-or-nothing?

ACID stands for Atomicity (all steps happen or none), Consistency (constraints are respected, so the data moves from one valid state to another), Isolation (concurrent transactions do not see each other's half-done work, to a degree set by the isolation level) and Durability (committed data survives crashes). Wrap related statements in BEGIN and COMMIT. If any statement fails, ROLLBACK undoes all of them. Savepoints let you undo part of a transaction.

Full answer
  • Atomicity: a money transfer is two updates (debit and credit). Without a transaction a crash between them loses money. With a transaction both apply or neither does.
  • Consistency: the database enforces rules (NOT NULL, foreign keys, CHECK balance >= 0). A statement that breaks a rule fails and the transaction cannot commit as is. Your application rules (for example "total stays the same") are your responsibility.
  • Isolation: other sessions see the old values until you commit (details depend on the isolation level, see the next items).
  • Durability: after COMMIT returns, the change is in the write-ahead log on disk, so it survives a crash.

How to use them

  • Keep transactions short. Do not wait for a user or a slow external call inside one, because open transactions hold locks and block cleanup (vacuum).
  • In PostgreSQL, an error inside a transaction puts it in an aborted state: you must ROLLBACK (or roll back to a savepoint) before running more statements.
  • SAVEPOINT name and ROLLBACK TO name undo a part (for example one optional step) while keeping the earlier work.
  • One statement is already atomic by itself. Use a transaction when several statements must succeed together.
  • Handle retries for serialisation failures and deadlocks (error codes 40001 and 40P01).
javascript
const { Client } = require('pg');

(async () => {
  const db = new Client(); await db.connect();
  await db.query(`
    DROP TABLE IF EXISTS bk29_accounts;
    CREATE TABLE bk29_accounts (id int PRIMARY KEY, balance int NOT NULL CHECK (balance >= 0));
    INSERT INTO bk29_accounts VALUES (1, 100), (2, 50);`);
  const balances = async () => (await db.query('SELECT balance FROM bk29_accounts ORDER BY id')).rows.map((r) => r.balance).join(', ');

  async function transfer(from, to, amount) {
    try {
      await db.query('BEGIN');
      await db.query('UPDATE bk29_accounts SET balance = balance - $1 WHERE id = $2', [amount, from]);
      await db.query('UPDATE bk29_accounts SET balance = balance + $1 WHERE id = $2', [amount, to]);
      await db.query('COMMIT');
      return 'committed';
    } catch (err) {
      await db.query('ROLLBACK');
      return `rolled back (${err.code} ${err.constraint})`;
    }
  }

  console.log('start                       :', await balances());
  console.log('transfer 30 from 1 to 2     :', await transfer(1, 2, 30), '->', await balances());
  console.log('transfer 500 from 1 to 2    :', await transfer(1, 2, 500), '->', await balances(), '(the credit was never kept)');

  // Without a transaction, the first statement stays even when the second fails.
  await db.query('UPDATE bk29_accounts SET balance = balance + 10 WHERE id = 2');
  await db.query('UPDATE bk29_accounts SET balance = balance - 999 WHERE id = 1').catch(() => {});
  console.log('no transaction, second fails:', await balances(), '(only half of the change happened)');

  // A savepoint undoes only the failing part.
  await db.query('BEGIN');
  await db.query('UPDATE bk29_accounts SET balance = balance + 1 WHERE id = 1');
  await db.query('SAVEPOINT optional_step');
  await db.query('UPDATE bk29_accounts SET balance = balance - 1000 WHERE id = 2').catch(() => {});
  await db.query('ROLLBACK TO optional_step');
  await db.query('COMMIT');
  console.log('with a savepoint            :', await balances(), '(first change kept)');

  await db.query('DROP TABLE bk29_accounts');
  await db.end();
})();

Runs on the local PostgreSQL. A CHECK constraint makes the second step fail, so the effect of ROLLBACK and of missing transactions can be seen in the balances. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): start : 100, 50 transfer 30 from 1 to 2 : committed -> 70, 80 transfer 500 from 1 to 2 : rolled back (23514 bk29_accounts_balance_check) -> 70, 80 (the credit was never kept) no transaction, second fails: 70, 90 (only half of the change happened) with a savepoint : 71, 90 (first change kept)

Key points

  • Atomicity: all or nothing.
  • Consistency: constraints keep data valid.
  • Isolation limits what concurrent transactions can see.
  • Durability: committed data survives crashes.
  • Keep transactions short and handle errors with ROLLBACK.

Common mistakes

  • Doing multi-step changes without a transaction.
  • Holding a transaction open while calling a payment API.
  • Ignoring the aborted transaction state after an error.
  • Assuming isolation is perfect by default.
  • Swallowing errors and committing anyway.

Follow-ups

  • What does the write-ahead log do?
  • What is the default isolation level in PostgreSQL?
  • What happens to a transaction if the connection drops?

Tips

  • Spell out ACID with one example each.
  • Use the bank transfer.
  • Mention short transactions.