ACID: atomicity and durability
medium 26 minA transaction turns several changes into one: all of them happen or none do, and once committed they survive a crash.
A small store with a write-ahead log
Read it, run it, change a line and run it again.
Loading editor…
The log is a list that survives a crash, the data files are a dict that may be out of date. Try a crash at any step.
The same in JavaScript
// Node.js with the pg packageconst { Pool } = require("pg");const pool = new Pool();async function transfer(from, to, amount) { if (!(amount > 0) || from === to) throw new Error("bad transfer"); const client = await pool.connect(); // one connection for the whole transaction try { await client.query("BEGIN"); const debit = await client.query( "UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1", [amount, from], ); if (debit.rowCount !== 1) throw new Error("insufficient funds"); const credit = await client.query( "UPDATE accounts SET balance = balance + $1 WHERE id = $2", [amount, to], ); if (credit.rowCount !== 1) throw new Error("no such account"); await client.query("COMMIT"); } catch (e) { await client.query("ROLLBACK"); throw e; } finally { client.release(); }}The same in SQL
-- SQL Server: transfer $100 from account 1 to account 2SET XACT_ABORT ON;BEGIN TRANSACTION;UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;IF @@ROWCOUNT <> 1BEGIN ROLLBACK; -- insufficient funds RETURN;ENDUPDATE accounts SET balance = balance + 100 WHERE id = 2;IF @@ROWCOUNT <> 1BEGIN ROLLBACK; -- no such account RETURN;ENDINSERT INTO transfers (src, dst, amount, created_at)VALUES (1, 2, 100, SYSUTCDATETIME());COMMIT;-- PostgreSQL: a savepoint keeps the transfer when an optional step failsBEGIN;UPDATE accounts SET balance = balance - 100 WHERE id = 1;UPDATE accounts SET balance = balance + 100 WHERE id = 2;SAVEPOINT after_transfer;INSERT INTO notifications (user_id, message) VALUES (1, 'Transfer sent');-- only if the INSERT failed, the application sends:-- ROLLBACK TO SAVEPOINT after_transfer;COMMIT;