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.
Chapter mnemonic
ACID transaction guarantees
Two stamps, balanced books, a private booth, a fireproof receipt.
A committed transfer disappears after a restart. Which guarantee failed?
Durability. A committed result should survive a crash.
Video lesson · Chapter 1 of 5
A transfer has two halves and one promise
ACID in 75 seconds
1:15Reel coming soon
Theory
Read or listen first. About 2 min.
What it is
A transaction is a group of reads and writes that a database treats as one unit. It either commits, and everything in it counts, or it rolls back, and it is as if nothing happened.
ACID names four promises about transactions. Atomicity: all or nothing. Consistency: the rules of the data hold before and after. Isolation: transactions that run together do not disturb each other. Durability: what was committed stays, even after a crash.
Two of them, atomicity and durability, are about failures. Databases keep both with one idea: write down what you are going to do, on stable storage, before you do it. That record is the write-ahead log.
Why it exists
Machines stop at any moment, also between two lines of your program. If a transfer takes money from one account and the machine stops before adding it to the other, the money has vanished.
Without transactions every program would need its own repair code for every possible place to stop. With them the database does it once, and the program only says where the unit begins and ends.
A short history
1973
IBM's Information Management System supports transactions with these properties, according to Gray and Reuter. The name ACID comes later.
1981
Jim Gray's paper The Transaction Concept describes a transaction by atomicity, consistency and durability.
1983
Theo Haerder and Andreas Reuter coin the word ACID, adding isolation.
1992
C. Mohan and colleagues publish ARIES, a recovery method built on write-ahead logging with redo and undo.
Words to know
- Commit
- The moment after which the transaction counts and stays.
- Rollback
- Undo everything the transaction did.
- Write-ahead log (WAL)
- A file of changes that reaches disk before the data files do.
- fsync
- A call that asks the system to force a file to stable storage.
- LSN
- Log sequence number: the position of a record in the log.
- Checkpoint
- A mark that says from where recovery must start reading.
- Constraint
- A rule the database checks, such as a foreign key or balance >= 0.
- Outbox
- A table for messages, written in the same transaction as the data.
How it works
Step through the idea, or press Play.
Begin. Everything from here is one unit
Understand it
Start here
Swapping stickers with a notebook
Asha and Lee want to swap stickers. Neither wants to end up with none. So they agree on a rule: write the swap in a notebook first, and tick it only when both stickers have moved.
The tick is the important moment. Before it, undo. After it, redo.
The idea
Four letters, four promises
Atomicity
All or nothing. A failed part undoes the whole.
Consistency
The rules hold before and after. Database and application share the work.
Isolation
Transactions at the same time do not disturb each other. A topic of its own: isolation levels.
Durability
Committed data survives a crash.
The life of a transaction
The two endings
| COMMIT | ROLLBACK |
|---|---|
| Every operation worked | Something went wrong, or you changed your mind |
| Changes become permanent | All changes are undone |
| Locks are released | Locks are released |
| Others may see the changes | As if it had never started |
Without it
Three disasters
| Disaster | What happened | What prevents it |
|---|---|---|
| Vanishing money | Alice goes from 900, crash, Bob stays at 100 is gone | Atomicity |
| Phantom order | Card charged $299, stock 5 to 4, crash: no order, no email | A local transaction, plus an outbox and a repeatable charge |
| Double booking | Two people see seat 14A free and both book it | Isolation, or a unique constraint on the seat |
One transaction
- BEGIN
- Take $100 from Alice
- Crash here: rolled back, Alice has $1,000
- Give $100 to Bob
- COMMIT: both or neither
Two separate statements
- Take $100 from Alice
- This is already committed
- Crash here: $100 lost
- Give $100 to Bob never runs
Atomicity
How the database can undo
A light switch is on or off, never half on. To behave like that, a database must be able to return to the old state until the moment of commit. There are three common ways.
| Way | How | On failure |
|---|---|---|
| Undo log or rollback journal | Write the original values aside first | Copy them back |
| Shadow paging | Change a copy of the page, then swap one pointer | Throw the copy away |
| Row versions | Write a new version of the row and keep the old one | The new version never becomes visible |
Durability
Log first, data later
The write path on one machine
- 1
Write to the log
A record such as: account 1, from 1000 to 900.
- 2
Flush the log
fsyncmakes sure it is on stable storage. - 3
Acknowledge the commit
Only now the client hears that it worked.
- 4
Update the data files later
A background process writes the changed pages.
Why is this faster than writing the data itself? A transaction may change pages in ten different places, which means ten scattered writes. The log is one file that grows at its end, so one sequential write is enough.
One log record
| Field | Example | Used for |
|---|---|---|
| LSN | 12345 | Position in the log |
| Transaction | 42 | Who did it |
| Type | UPDATE | Also INSERT, DELETE, COMMIT |
| Table and page | accounts, 789 | Where |
| Old value | 1000 | Undo |
| New value | 900 | Redo |
| Previous LSN | 12340 | The same transaction's record before this one |
What a flush costs, and group commit
Recovery
After the crash
Redo, then undo
How long recovery takes
A checkpoint writes changed pages to the data files and notes how far they have caught up. Recovery starts there and not at the beginning of time. Unfinished transactions may reach back further, so undo can need older records.
Consistency
Who keeps the rules?
| Constraint | Rule | Example |
|---|---|---|
| Primary key | One row per identifier | user_id is unique |
| Foreign key | The other row must exist | An order needs its user |
| NOT NULL | A value is required | email is present |
| CHECK | A condition on the row | balance >= 0 |
| UNIQUE | No duplicates | One account per email |
| Trigger | Your code at a change | Set the time of the update |
Taking 100 fails the CHECK, and the statement is rejected. A rule such as "the sum of all balances stays the same" spans many rows, and an ordinary CHECK cannot say that. The transaction that moves the money must keep it, at a suitable isolation level.
The database enforces
- Primary and foreign keys
- NOT NULL, UNIQUE, CHECK
- Triggers and stored procedures
- Data types
The application must
- Express complex business rules
- Keep rules that span many rows
- Agree with outside services
- Know what the data means
Code
Transactions in a program
from contextlib import contextmanager@contextmanagerdef transaction(conn): cur = conn.cursor() try: yield cur conn.commit() except Exception: conn.rollback() raise finally: cur.close()def transfer(conn, src, dst, amount): if amount <= 0 or src == dst: raise ValueError("bad transfer") with transaction(conn) as cur: cur.execute( "UPDATE accounts SET balance = balance - %s" " WHERE id = %s AND balance >= %s", (amount, src, amount)) if cur.rowcount != 1: raise ValueError("insufficient funds") cur.execute( "UPDATE accounts SET balance = balance + %s WHERE id = %s", (amount, dst)) if cur.rowcount != 1: raise ValueError("no such account") cur.execute( "INSERT INTO transfers (src, dst, amount) VALUES (%s, %s, %s)", (src, dst, amount))A savepoint marks a place inside a transaction. Rolling back to it undoes the later part only. It is useful when an optional step may fail. It is not a commit: if the transaction fails afterwards, everything goes.
Beyond one
When two systems must agree
A shop must save an order and publish a message. If it commits and then crashes, the message is missing. If it publishes first and the commit fails, the message lies.
The outbox
The relay crashes, and nothing is lost
| Way | Gives | Costs |
|---|---|---|
| Outbox | The message follows the data for certain | A relay, and possible repeats |
| Two-phase commit | All databases or none | Everyone waits if the coordinator fails at a bad time |
| Saga | Local transactions with steps that undo them | Others see the states in between |
How much transaction do I need?
Trade-offs
The price of the promises
Durability is a dial
| Setting | Reply comes | Can lose |
|---|---|---|
| Asynchronous commit | Before the flush | The last moments before a crash |
| Local flush | After the log is on this disk | Committed data if this disk dies |
| Synchronous standby | After a second machine has the log | Data only if both are lost |
Summary
The whole topic in one minute.
A transaction is all or nothing. Databases achieve that by keeping enough information to undo unfinished work, and by treating one COMMIT record as the single moment when everything counts.
Durability comes from writing the log to stable storage before answering. The data files follow later, and after a crash the log repairs them. One transaction covers one database: for two systems, use a local transaction with an outbox and steps that can be repeated safely.
- Atomicity: all or nothing. Consistency: rules hold. Isolation: no interference. Durability: committed stays.
- Log first, data later. The COMMIT record on disk is the moment that counts.
- After a crash: redo what committed, undo or ignore what did not.
- A log on one disk does not survive losing the disk.
- Check the row count of every update.
- One transaction covers one database. Across systems use an outbox and safe repeats.