ACID Transactions and Isolation Levels Explained
Understand ACID database transactions (atomicity, consistency, isolation, durability), read anomalies like dirty reads and phantoms, the four SQL isolation levels, locking vs MVCC and how to use transactions safely in code.
Imagine moving ₹500 from Asha's account to Ravi's. The debit succeeds, then the server crashes before the credit. Money has vanished. Transactions exist to make that impossible, and ACID describes the four guarantees they provide.
What is a transaction?#
A transaction is a group of operations that the database treats as a single unit of work: either all of them take effect, or none do.
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 'asha';
UPDATE accounts SET balance = balance + 500 WHERE id = 'ravi';
COMMIT; -- both changes become permanent together
-- or ROLLBACK; to undo everything since BEGINThe four ACID properties#
| Property | Guarantee | In the bank example | How databases implement it |
|---|---|---|---|
| Atomicity | All or nothing | Never debit without credit | Undo logs, rollback |
| Consistency | Data moves from one valid state to another | Balance never goes negative; totals still match | Constraints, foreign keys, triggers, plus correct app logic |
| Isolation | Concurrent transactions don't interfere | Two transfers at once don't overwrite each other | Locks or MVCC snapshots |
| Durability | Committed data survives crashes | After "transfer successful", a power cut doesn't undo it | Write-ahead log (WAL) flushed to disk, replication |
Consistency through constraints#
ALTER TABLE accounts
ADD CONSTRAINT balance_non_negative CHECK (balance >= 0);
BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE id = 'asha';
-- ERROR: violates check constraint "balance_non_negative"
ROLLBACK; -- the whole transaction is abortedDurability through the write-ahead log#
Before changing data pages, the database appends the change to a sequential write-ahead log and flushes it to disk. On restart after a crash, it replays committed log entries and discards uncommitted ones.
Isolation: the tricky one#
Perfect isolation (every transaction behaves as if it ran alone) is expensive. Databases therefore offer weaker isolation levels that allow certain anomalies in exchange for better concurrency.
Read anomalies#
| Anomaly | What happens |
|---|---|
| Dirty read | T1 reads data T2 has written but not committed; T2 rolls back, so T1 saw data that never existed. |
| Non-repeatable read | T1 reads a row twice and gets different values because T2 updated and committed it in between. |
| Phantom read | T1 runs the same range query twice and gets new rows because T2 inserted matching rows. |
| Lost update | T1 and T2 both read a value, modify it and write it back; one write overwrites the other. |
| Write skew | Two transactions read overlapping data, make disjoint writes, and together break a rule neither broke alone. |
A non-repeatable read, step by step#
Time T1 (report) T2 (transfer)
1 BEGIN
2 SELECT balance FROM accounts
WHERE id='asha' → 1000
3 BEGIN
4 UPDATE accounts SET balance=500
WHERE id='asha'
5 COMMIT
6 SELECT balance FROM accounts
WHERE id='asha' → 500 (changed inside one transaction!)
7 COMMITThe four SQL isolation levels#
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible |
| Read Committed | Prevented | Possible | Possible |
| Repeatable Read | Prevented | Prevented | Possible* |
| Serializable | Prevented | Prevented | Prevented |
*PostgreSQL's Repeatable Read uses snapshot isolation and also prevents phantoms; MySQL InnoDB's Repeatable Read prevents most phantoms with gap locks.
PostgreSQL, Oracle and SQL Server default to Read Committed. MySQL InnoDB defaults to Repeatable Read. Know your default before reasoning about concurrency bugs.
-- PostgreSQL / MySQL
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- ...
COMMIT;
-- or for the session
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ;How isolation is implemented: locks vs MVCC#
| Two-phase locking (2PL) | MVCC | |
|---|---|---|
| Idea | Readers and writers take shared/exclusive locks | Keep multiple versions of each row; readers see a snapshot |
| Readers block writers? | Yes | No |
| Cost | Lock contention, deadlocks | Old versions need cleanup (VACUUM / purge) |
| Used by | SQL Server (default), serializable modes | PostgreSQL, MySQL InnoDB, Oracle |
Preventing lost updates#
1. Atomic update in SQL#
-- Good: the database does read-modify-write atomically
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock > 0;2. Pessimistic locking#
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE; -- locks the row
-- application logic decides
UPDATE products SET stock = 9 WHERE id = 42;
COMMIT;3. Optimistic locking with a version column#
UPDATE products
SET stock = 9, version = version + 1
WHERE id = 42 AND version = 7;
-- 0 rows updated → someone else changed it; reload and retryTransactions in application code#
@Service
public class TransferService {
@Transactional(isolation = Isolation.READ_COMMITTED)
public void transfer(String from, String to, BigDecimal amount) {
Account src = accounts.findByIdForUpdate(from); // SELECT ... FOR UPDATE
Account dst = accounts.findByIdForUpdate(to);
if (src.getBalance().compareTo(amount) < 0) {
throw new InsufficientFundsException(); // triggers rollback
}
src.debit(amount);
dst.credit(amount);
} // commit happens here if no exception
}By default only unchecked exceptions trigger rollback; calling a @Transactional method from inside the same class bypasses the proxy, so no transaction starts. See the Spring Boot REST API guide and Java exception handling.
Best practices#
- Keep transactions short: never wait for user input or call slow external APIs inside one.
- Lock rows in a consistent order (for example by ID) to avoid deadlocks.
- Be ready to retry on serialization failures and deadlocks.
- Use the weakest isolation level that is still correct for each operation.
- Across services there is no shared transaction; use sagas instead (see microservices vs monolith).
Compare how NoSQL systems relax these guarantees in SQL vs NoSQL databases.
Key takeaways#
- A transaction is all-or-nothing: COMMIT makes every change permanent, ROLLBACK undoes them.
- ACID means atomicity, consistency, isolation and durability.
- Weaker isolation levels allow dirty reads, non-repeatable reads and phantoms in exchange for concurrency.
- Most databases use MVCC so readers don't block writers.
- Prevent lost updates with atomic SQL, SELECT ... FOR UPDATE or optimistic version checks, and keep transactions short.