ACID and the transaction
One transfer, two writes
Section titled “One transfer, two writes”Alice has 100 and Bob has 50. Alice sends Bob 30. In a database that is two writes: take 30 from Alice, add 30 to Bob. Between those two writes the 30 is in neither account.
If the program crashes at that moment, the 30 has vanished. If another request adds up the two accounts at that moment, it sees a total that never existed. PostgreSQL’s documentation puts the first problem in one sentence: it would certainly not do for a system failure to result in Bob receiving money that was not debited from Alice.
A transaction is the database’s answer. It bundles several steps into one unit: the steps are either all applied or none of them is, and the half-finished state is not shown to anyone else. The application marks the start, runs its statements, and then ends with COMMIT to keep the changes or ROLLBACK to throw them away.
Mental model. A transaction is a draft. Everything you write goes into the draft, and only
COMMITpublishes it. If anything goes wrong first, the draft is thrown away and the world looks as if you had never started.
The four letters
Section titled “The four letters”ACID is the usual name for what a transactional database promises. The same four words hide four different guarantees, and each one fails in a different way.
| Letter | The promise | What you see when it is missing |
|---|---|---|
| Atomicity | All the changes of a transaction happen, or none of them does | A transfer cut in half: money debited and never credited |
| Consistency | A transaction moves the data from one valid state to another | A balance below zero, an order for a product that does not exist |
| Isolation | Transactions running at the same time do not disturb each other | Two deposits at once, and one of them disappears |
| Durability | Once the database says “committed”, the change survives a crash | A confirmed payment that is gone after a restart |
Atomicity and isolation are the two that the rest of this module is about. Atomicity is about one transaction failing part way. Isolation is about two transactions running at once.
Durability has a plain definition in PostgreSQL’s documentation: the database logs the updates of a transaction in permanent storage before it reports the transaction complete. The details of how a given product does it depend on its settings and on the hardware. MySQL’s documentation lists, for its durability, a group of server settings and the behaviour of the storage devices, not a single feature.
What the C means
Section titled “What the C means”The C is the odd one out. The other three letters describe what the database does. Consistency describes what the database and the application achieve together.
The database can enforce the rules it knows: a column that cannot be empty, a balance that cannot go below zero if you declare that as a constraint, a reference to a row that must exist. A transaction that would break such a rule is rejected.
A rule that only the application knows cannot be enforced that way. “At least one doctor must be on call” is a rule about several rows at once, and the database does not know it unless you express it. Isolation is what lets the application keep such a rule: if each transaction sees a stable picture and checks the rule against it, the rule can hold. The next lessons show what happens when the picture is not stable.
The word is also used with other meanings, which is a source of confusion. MySQL’s documentation, for one, describes the consistency aspect of its ACID model as mainly internal processing that protects the data from crashes. This course uses the first meaning: the data obeys its rules before and after every transaction. A later module uses “consistency” for something else again, the guarantees a replicated system gives its readers.
A transfer, in code
Section titled “A transfer, in code”The program below is a tiny in-memory store with an undo log. Every write first records the value it replaces. Commit throws the log away, and Rollback replays it backwards. It is a teaching model of atomicity, not a real storage engine, and it never runs in your browser: the output below was produced when the site was built.
// A transaction on a tiny in-memory store: all of its writes happen, or none of them do.// Every write first records the value it replaces (an undo log).// Commit throws the log away. Rollback replays it backwards.
var bank = new InMemoryDb(new() { ["alice"] = 100, ["bob"] = 50 });Show("start", bank);
// A transfer is two writes: debit one account, credit the other.void Transfer(InMemoryDb.Transaction tx, string from, string to, int amount, bool crashAfterDebit = false){ tx.Write(from, tx.Read(from) - amount); if (crashAfterDebit) throw new InvalidOperationException("crash between the debit and the credit"); tx.Write(to, tx.Read(to) + amount);}
// 1. The transfer commits: money moves and the total stays 150.var tx = bank.Begin();Transfer(tx, "alice", "bob", 30);tx.Commit();Show("transfer 30, commit", bank);
// 2. A crash after the debit. The transaction rolls back, so the debit is undone.tx = bank.Begin();try{ Transfer(tx, "alice", "bob", 50, crashAfterDebit: true); tx.Commit();}catch (InvalidOperationException){ tx.Rollback();}Show("transfer 50, crash, rollback", bank);
// 3. The same crash with nobody to roll back: the debit stays and 50 has vanished.tx = bank.Begin();try{ Transfer(tx, "alice", "bob", 50, crashAfterDebit: true); tx.Commit();}catch (InvalidOperationException){ // nobody calls tx.Rollback()}Show("transfer 50, crash, no rollback", bank);
// 4. A lost update. Two transactions read the balance, then each writes its own result.var account = new InMemoryDb(new() { ["balance"] = 100 });var first = account.Begin();var second = account.Begin();var seenByFirst = first.Read("balance"); // 100var seenBySecond = second.Read("balance"); // 100: the first deposit is not written yetfirst.Write("balance", seenByFirst + 10);first.Commit();second.Write("balance", seenBySecond + 20); // computed from a stale read: the +10 is overwrittensecond.Commit();Show("deposits +10 and +20, interleaved", $"balance={account.Get("balance")} (should be 130)");
// One after the other, the same two deposits add up.account = new InMemoryDb(new() { ["balance"] = 100 });foreach (var amount in new[] { 10, 20 }){ var deposit = account.Begin(); deposit.Write("balance", deposit.Read("balance") + amount); deposit.Commit();}Show("deposits +10 and +20, one at a time", $"balance={account.Get("balance")}");
void Show(string label, object state) => Console.WriteLine($"{label,-37} {state}");
// Writes go straight to the rows. An undo log is only safe for one writer at a time:// real databases add locks or versions (MVCC) so that concurrent transactions are isolated.class InMemoryDb(Dictionary<string, int> rows){ public int Get(string key) => rows[key];
public Transaction Begin() => new(rows);
public override string ToString() => $"{string.Join(" ", rows.OrderBy(r => r.Key, StringComparer.Ordinal).Select(r => $"{r.Key}={r.Value}"))} (total {rows.Values.Sum()})";
public sealed class Transaction(Dictionary<string, int> data) { private readonly List<(string Key, int Before)> _undo = [];
public int Read(string key) => data[key];
public void Write(string key, int value) { _undo.Add((key, data[key])); // remember what this write replaces data[key] = value; }
public void Commit() => _undo.Clear();
public void Rollback() { for (var i = _undo.Count - 1; i >= 0; i--) data[_undo[i].Key] = _undo[i].Before; _undo.Clear(); } }}start alice=100 bob=50 (total 150)transfer 30, commit alice=70 bob=80 (total 150)transfer 50, crash, rollback alice=70 bob=80 (total 150)transfer 50, crash, no rollback alice=20 bob=80 (total 100)deposits +10 and +20, interleaved balance=120 (should be 130)deposits +10 and +20, one at a time balance=130This is the exact code that produced this output, run with the .NET SDK when the site was built. Nothing runs in your browser.
Read the output against the code:
- The start is Alice 100 and Bob 50, a total of 150.
- A transfer of 30 commits. Alice has 70, Bob has 80, and the total is still 150.
- A transfer of 50 crashes after the debit, and the program rolls back. The debit is undone, so Alice has 70, Bob has 80 and the total is 150.
- The same crash with nobody to roll back leaves Alice with 20 and Bob with 80. The total is 100, and 50 has vanished.
- The last two lines are about isolation, not atomicity. Two deposits of 10 and 20 into the same account, interleaved, leave 120 where the right answer is 130. Run one at a time, they give 130.
That last pair is the subject of the next lesson.
Test yourself
Section titled “Test yourself”Check your understanding: ACID
This quiz needs JavaScript to check your answers.
What happens if the crash comes between the debit and the credit?
Section titled “What happens if the crash comes between the debit and the credit?”With a transaction, the database throws the half-finished work away and the accounts are as before: 70 and 80, a total of 150. Without one, the total drops from 150 to 100, and nothing in the data says where the 50 went.
The same applies to a program that dies, to a connection that drops, and to an error in the second statement. Atomicity does not prevent the failure. It decides what the data looks like afterwards. An application that retries after such a failure needs atomicity too: it can run the whole transfer again only if the first attempt left nothing behind.
- A transaction bundles statements into one unit: all of them take effect, or none does, and other transactions do not see the half-finished state.
- Atomicity covers a transaction that fails part way. Isolation covers transactions that run at the same time. Durability covers a crash after the commit.
- The C of ACID means that the data obeys its rules before and after each transaction. The database enforces the rules it knows, and the application is responsible for the others.
- A rollback can be done with an undo log: remember the old value of each write, and put them back in reverse order.
- Isolation is the hard one, and the next lesson shows five ways it goes wrong.
Next: the five anomalies that two transactions can cause when they run at the same time.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.