ACID and isolation levels
What a transaction really guarantees, which concurrency bugs each isolation level still allows, and how to stop lost updates and write skew.
The problem
A wallet service stores each balance as a row. Moving 100 from one account to another is two updates: subtract from the first, add to the second. Two different things can go wrong.
A crash in the middle. The server subtracts 100, then loses power before it adds. The money has vanished. Nothing on disk says that half an operation happened.
Two requests at once. Two withdrawals read the same balance of 100. Each works out its own result and writes it back. One overwrites the other, and the account has paid out more than the balance shows.
Early applications handled this by hand. They took one global lock so that only one request ran at a time, which is safe and slow, and they wrote their own recovery code to run after a crash. Jim Gray and colleagues at IBM formalised the alternative in the 1970s: the transaction, a group of operations that the database treats as one unit. In 1983 Theo Härder and Andreas Reuter gave its guarantees the name ACID.
What each letter means
- Atomicity. All the writes in a transaction take effect, or none do. If the transaction aborts or the server crashes, partial work is undone. Atomicity is about failure, not about concurrency.
- Consistency. A transaction moves the database from one valid state to another. “Valid” means the constraints you declared (unique keys, foreign keys, checks) plus rules your code maintains. This is the one property that is mostly the application’s job. It is also not the C in CAP, which is about replicas agreeing (see consistency models).
- Isolation. Transactions that run at the same time do not interfere. The ideal is serializable: the outcome equals some order of running them one at a time. Most databases default to something weaker, which is what the rest of this lesson is about.
- Durability. Once a commit is acknowledged, the data survives a crash.
The write-ahead log
Atomicity and durability both rest on one mechanism. Before the database acknowledges a commit, it appends a record of the changes to the write-ahead log (WAL) and flushes it to disk. The data pages are changed in memory and written out later. After a crash, the database replays the log: committed transactions are redone, and incomplete ones are discarded.
An append is a sequential write, and many transactions can share one flush, so this is far cheaper than writing every changed page at commit. The same log feeds replication.
Durability has limits. A flushed log does not survive the loss of the disk, so real systems also replicate. And it is configurable: PostgreSQL’s synchronous_commit = off and MySQL’s innodb_flush_log_at_trx_commit = 2 acknowledge commits before the flush, and can lose up to about a second of recent commits in a crash. Both default to the safe setting.
The anomalies
Weaker isolation is defined by what it lets go wrong.
- Dirty read. You read another transaction’s uncommitted write, which may later be rolled back.
- Non-repeatable read. You read a row twice in one transaction and get different values, because another transaction committed in between.
- Phantom. You run the same range query twice and get different rows, because another transaction inserted or deleted a matching row.
- Lost update. Two transactions read a value, both compute a new one, and the second write overwrites the first.
Step 1 of 8
An account holds 100. Two withdrawals arrive at almost the same moment, one for 30 and one for 50. Run one after the other, they would leave a balance of 20.
Read the steps as text
- An account holds 100. Two withdrawals arrive at almost the same moment, one for 30 and one for 50. Run one after the other, they would leave a balance of 20.
- Request A starts a transaction and reads the balance. It sees 100 and works out in application code that the new balance should be 70.
- Before A writes, request B reads the same row. A has not committed anything, so B also sees 100 and works out a new balance of 50. Neither read is dirty. Both saw committed data.
- Request A writes 70 and commits. So far everything is correct.
- Request B writes 50 and commits. Its value was computed from a balance that is no longer true. Under read committed isolation the database accepts the write without complaint.
- The account shows 50, but 80 has been paid out of 100. Request A's update has vanished and no error was raised anywhere. This is a lost update, and it is the most common concurrency bug in application code.
- The simplest fix is to let the database do the arithmetic. A single statement that sets the balance to the balance minus 50, on condition that it is at least 50, locks the row and computes from the current value. Request B would then see 70 and leave 20.
- When the application must read before it writes, there are two choices. Lock the row at read time with SELECT FOR UPDATE, so that B waits for A. Or store a version number and write only if it has not changed, so that B's write matches no rows and B retries.
- Write skew. Two transactions read the same rows, each make a decision from what they read, and each write a different row. No row is overwritten, and a rule that spans the rows is broken.
Step 1 of 8
Two doctors, Alice and Bob, are on call for tonight's shift. The hospital's rule is that at least one doctor must stay on call. Both feel unwell and both press the button to go off call at the same moment.
Read the steps as text
- Two doctors, Alice and Bob, are on call for tonight's shift. The hospital's rule is that at least one doctor must stay on call. Both feel unwell and both press the button to go off call at the same moment.
- Alice's transaction checks the rule first. It counts the doctors on call for the shift and reads both rows. Under snapshot isolation it reads from a snapshot taken when the transaction began. The count is 2, so it is safe for one to leave.
- Bob's transaction runs the same check at the same time. Alice has not committed, so Bob's snapshot also shows 2 doctors on call. Each transaction has now decided, correctly from what it can see, that it may go ahead.
- Alice's transaction updates her own row to off call and commits.
- Bob's transaction updates his own row and commits. The two transactions wrote different rows, so there is no lock to wait for and no write conflict for snapshot isolation to detect. Both commits succeed.
- Nobody is on call. Each transaction was correct on its own, and together they broke the rule. This is write skew. Unlike a lost update, no row was overwritten. Each transaction read data that the other one then made out of date.
- Serializable isolation prevents it. The database notices that each transaction read something the other wrote, and aborts one of them with a serialization failure. The application retries that transaction, which now counts 1 doctor on call and refuses.
- Without serializable isolation, make the conflict explicit. Lock the rows the decision depends on with SELECT FOR UPDATE, so the second transaction waits and then sees the new count. Whenever a check across several rows guards a write to one of them, think of write skew.
The SQL standard levels
The SQL standard defines four levels by the first three anomalies.
| Level | Dirty read | Non-repeatable read | Phantom |
|---|---|---|---|
| Read uncommitted | Possible | Possible | Possible |
| Read committed | Prevented | Possible | Possible |
| Repeatable read | Prevented | Prevented | Possible |
| Serializable | Prevented | Prevented | Prevented |
The standard does not mention lost updates or write skew. A 1995 paper, “A Critique of ANSI SQL Isolation Levels”, pointed out the gaps and described a level the standard had missed, snapshot isolation. As a result the level names do not mean the same thing in every database.
MVCC and snapshot isolation
Older databases isolated transactions with locks alone, so a long read blocked writers. Most modern databases use multi-version concurrency control (MVCC). A write does not overwrite a row. It creates a new version, marked with the transaction that wrote it. Each reader sees a snapshot: only the versions committed before a point in time. Readers do not block writers, and writers do not block readers. Two writers to the same row still wait for each other.
The cost is cleaning up old versions (VACUUM in PostgreSQL, the purge of the undo log in InnoDB). One long-running transaction can hold that cleanup back for the whole database.
Snapshot isolation means a whole transaction reads from one snapshot. It prevents dirty reads, non-repeatable reads and phantoms in what you read. It does not prevent write skew, because each transaction decides from a snapshot that the other is about to make stale.
Optimistic and pessimistic locking
For a lost update, try these in order.
- An atomic statement. Let the database do the arithmetic, and check how many rows changed.
UPDATE accounts SET balance = balance - 30
WHERE id = 1 AND balance >= 30;
- Pessimistic locking.
SELECT ... FOR UPDATElocks the rows until commit, and other transactions wait. Choose it when conflicts are frequent and the work is short. Keep the lock brief, never hold it across a remote call, and take locks in a fixed order to avoid deadlocks. - Optimistic locking. Store a version number, and write only if it is unchanged.
UPDATE products SET stock = 4, version = 8
WHERE id = 7 AND version = 7;
If no row changed, somebody else got there first: read again and retry. Nothing is locked, so this works across separate HTTP requests. Choose it when conflicts are rare. Under heavy contention the retries waste work.
For write skew, use serializable isolation, or lock the rows the decision reads with FOR UPDATE. When the check is that no row exists, as with a free booking slot, there is nothing to lock. Use a unique or exclusion constraint, or lock a parent row such as the room.
When to choose each level, and when not to
- Read committed plus targeted fixes is the usual choice for transactional services. It is cheap, and it requires you to spot every read-then-write.
- Repeatable read or snapshot isolation suits reports, exports and any transaction that needs one consistent view across several queries.
- Serializable suits ledgers, bookings and rules that span rows, where a wrong answer costs more than a retry. Do not choose it without retry logic, or for long transactions on contended data, where aborts multiply.
A database transaction covers one database. Across services you need different tools: see distributed transactions and sagas.
In the interview
Raise isolation whenever your design reads shared state and then writes it: a balance, a stock count, a seat, a username, a quota. Say the race out loud, name the anomaly, and pick the mechanism.
A strong answer takes under a minute: “Two buyers can both see the last seat as free. That is a lost update. I would claim the seat with one conditional update, setting it to sold where it is still free, and check that one row changed. The limit of four tickets per user is different, because it spans rows: that is write skew. I would lock the user’s row first, or run that transaction at serializable and retry on failure.”
Key takeaways
- Atomicity is about aborts and crashes, isolation is about concurrency, and durability rests on flushing a write-ahead log before acknowledging a commit.
- Most databases do not run at serializable by default, so some concurrency anomalies are allowed unless you act.
- A lost update is two read-modify-write cycles on one row. Fix it with an atomic statement, a row lock or a version check.
- Write skew is two transactions that read the same rows and write different ones. Only serializable isolation, an explicit lock on what was read, or a constraint prevents it.
- MVCC lets readers and writers work without blocking each other by keeping several versions of each row.
- Isolation level names do not mean the same thing everywhere. PostgreSQL defaults to read committed and MySQL InnoDB to repeatable read, and they behave differently.
Check yourself
0 of 5 answered
Flashcards
These 6 cards are in your review deck. Tap a card to see the answer.
What does each letter of ACID mean, in a phrase?
Atomicity, all or nothing on abort or crash. Consistency, declared rules hold before and after. Isolation, concurrent transactions do not interfere. Durability, committed data survives a crash.
How does a write-ahead log give durability?
A record of the change is appended to the log and flushed to disk before the commit is acknowledged. Data pages are written later, and after a crash the log is replayed.
What is a lost update?
Two transactions read the same value, each compute a new one, and both write. The second write overwrites the first without having seen it.
What is write skew?
Two transactions read the same set of rows, each make a decision from what they read, and write to different rows. Each is valid alone, and together they break an invariant.
What is MVCC?
Multi-version concurrency control. Each write creates a new version of a row and readers see a consistent snapshot of committed versions, so readers and writers do not block each other.
Optimistic versus pessimistic locking?
Pessimistic locks the row before working (SELECT FOR UPDATE), so others wait. Optimistic takes no lock, checks a version at write time, and retries on conflict. Use pessimistic under high contention.