Module 3 · Database designLesson 28 of 887 minIntermediate
Transactions and ACID
A transaction groups several changes so they all happen or none do, even if the server crashes halfway.
Run "No transaction" and watch $100 disappear. Then crash in the middle of a transaction, and finally run one to completion.
Many real actions need several changes: take money from one account and add it to another; create an order and reduce stock. If the server crashes between those changes, the data is left in a broken, half-done state.
A transaction wraps the changes:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 'alice';
UPDATE accounts SET balance = balance + 100 WHERE id = 'bob';
COMMIT;
If anything fails before COMMIT, the database rolls back everything.
ACID
- Atomicity: all the changes happen, or none do.
- Consistency: rules you've defined (like "balance can't go negative" or "every order has a customer") hold before and after.
- Isolation: transactions running at the same time don't see each other's half-finished work. How strictly is controlled by isolation levels, the next lesson.
- Durability: once committed, the data survives crashes and power cuts.
How durability works
Before changing the real data, the database appends the change to a write-ahead log on disk. After a crash, it replays the log: committed transactions are redone, unfinished ones are undone. That's why COMMIT waits for the log to reach disk.
Practical advice
- Keep transactions short. Don't call a slow external API in the middle of one; it holds locks the whole time.
- Expect retries. Under contention, the database may abort a transaction (deadlocks, serialization conflicts). Your code should retry it.
- Transactions stop at the database's edge. Changes across two databases or services need other tools, like the saga pattern in module 5.