A transaction groups several reads and writes into one unit. The database promises that the unit behaves well, even when the server crashes or thousands of other transactions run at the same time. Those promises are called ACID. Interviews go deep on the "I": which isolation level, which bug each level allows, and how to avoid the bugs. This lesson covers ACID, the isolation levels, how databases implement them, and the practical fixes. Distributed transactions across services have their own lesson.
1. ACID in One View
- Atomicity: all of the transaction happens, or none of it. If it fails halfway, the database undoes the first half.
- Consistency: the transaction moves the data from one valid state to another. The database enforces the rules you declare (primary keys, foreign keys,
UNIQUE,CHECK). The business rules are your job. This is not the same "consistency" as in the CAP theorem (see the consistency lesson). - Isolation: concurrent transactions do not see each other's half-finished work. How strictly is a setting, and it is the main topic of this lesson.
- Durability: after
COMMITreturns, the data survives a crash. The database writes the change to the write-ahead log and calls fsync before it answers (see the indexes and storage engines lesson).
A money transfer shows atomicity. Without a transaction, a crash between the two updates destroys 100 units:
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;
- Autocommit: outside a
BEGIN, each statement is its own transaction. JDBC connections start in this mode. In Spring,@Transactionalopens and commits the transaction for you. - Rollback in Spring: by default it happens only for unchecked exceptions. A checked exception still commits unless you set
rollbackFor. - Durability across machines: a commit that reached only the primary is lost if the primary dies before an asynchronous replica copies it (see the replication lesson).
2. The Problem: Concurrent Transactions
Running transactions one after another would be safe but slow. Databases run them at the same time, and that can produce anomalies:
- Dirty read: you read data another transaction has not committed. It may be rolled back, so you acted on data that never existed.
- Non-repeatable read: you read a row twice in one transaction and get different values, because another transaction committed a change in between.
- Phantom read: you run the same range query twice and get a different set of rows, because another transaction inserted or deleted a matching row.
- Lost update: two transactions read the same value, both change it and both write back. One change is lost. Two buyers each read stock 10 and each write 9. Two units sold, stock down by one.
- Write skew: two transactions read the same data, then write to different rows, and together they break a rule that each one checked on its own. The worked example in section 5 shows this.
3. Isolation Levels
The SQL standard defines four levels. A higher level allows fewer anomalies and costs more (more waiting, or more aborted transactions).
| Level | Dirty read | Non-repeatable read | Phantom read | Write skew |
|---|---|---|---|---|
| Read Uncommitted | Possible | Possible | Possible | Possible |
| Read Committed | No | Possible | Possible | Possible |
| Repeatable Read | No | No | Possible in the standard | Possible |
| Serializable | No | No | No | No |
Serializable means the result is the same as if the transactions had run one at a time, in some order. That is the only level that makes concurrency invisible.
The real databases differ from the table:
- PostgreSQL: the default is Read Committed. Its Repeatable Read is snapshot isolation: the transaction sees one fixed snapshot, so phantoms do not happen either. If two transactions change the same row, one fails with a serialization error. This stops lost updates. Write skew is still possible, because the two transactions write different rows, so this check never sees a conflict. Its Serializable level detects dangerous patterns and aborts one transaction.
- MySQL InnoDB: the default is Repeatable Read, with a fixed snapshot for plain reads and locks on the gaps between rows for locking reads. A read followed by a write in application code can still lose an update.
- Oracle and SQL Server default to Read Committed.
- Read Uncommitted is seldom useful. PostgreSQL treats it as Read Committed.
3.1 Choosing a Level
- Read Committed is a good default for ordinary web requests. Each statement sees the data committed before it started. Combine it with atomic updates or row locks where a read-then-write matters.
- Repeatable Read (a snapshot) suits reports and exports that run several queries and need one consistent view, for example totals and details that must add up.
- Serializable suits rules that span several rows, such as "at least one doctor on call" or "the sum of all budgets stays under the limit". The application must retry aborted transactions, and throughput drops under heavy conflicts.
- Say the reason. "Read Committed with an atomic stock update" is a stronger answer than "Serializable, to be safe". Why? It shows you know the exact problem (two buyers, one row) and the cheapest fix for it. An atomic update takes a lock on one row for a moment, so it costs almost nothing. "Serializable, to be safe" hides that you have not found the anomaly, and it adds aborts and retries for every transaction.
4. How Databases Enforce Isolation
- Locks (two-phase locking): a transaction locks what it reads and writes and holds the locks until it ends. It is safe, but readers and writers block each other, and transactions can deadlock.
- MVCC (multi-version concurrency control): a write creates a new version of the row and keeps the old one. Each transaction reads the version that was current at its snapshot, so readers do not block writers and writers do not block readers. Old versions are removed later (PostgreSQL vacuum, InnoDB purge of the undo log). Most modern databases use MVCC for reads and locks for writes.
- Serializable snapshot isolation: MVCC plus tracking of read-write conflicts. It lets transactions run in parallel and aborts one only if a dangerous pattern appears.
- Deadlock: transaction A waits for a lock held by B, and B waits for one held by A. The database finds the cycle and aborts one of them. PostgreSQL checks after a delay (1 second by default), and InnoDB checks right away.
Keep long-running transactions short. An old transaction keeps old row versions alive, so tables grow and queries slow down.
5. Worked Example: Doctors on Call
A hospital rule says at least one doctor must be on call each night. Alice and Bob are both on call. Each sends a request to go off call. Each transaction first counts the doctors on call, sees 2, decides that one leaving is fine, and updates its own row.
sequenceDiagram
participant A as Alice's transaction
participant DB as Database
participant B as Bob's transaction
A->>DB: 1. BEGIN, count doctors on call
DB-->>A: 2
B->>DB: 2. BEGIN, count doctors on call
DB-->>B: 2
A->>DB: 3. Alice goes off call (2 is enough)
B->>DB: 3. Bob goes off call (2 is enough)
A->>DB: 4. COMMIT
B->>DB: 4. COMMIT
Note over DB: Zero doctors on call
Each transaction wrote a different row, so there is no lost update, and Repeatable Read does not stop it. This is write skew. Three ways to fix it:
- Serializable. The database sees that the two transactions read data the other one changed, and aborts one. The application retries it, and on the retry the count is 1, so the request is refused.
- Lock the rows that were read. Read the on-call doctors with
SELECT ... FOR UPDATEand count them in the application. The second transaction waits until the first one finishes, then sees the new count. - Put the rule in the database. A constraint or a single counter row that every transaction must update turns the conflict into a visible one.
BEGIN;
SELECT id FROM doctors
WHERE shift = 'night' AND on_call = true
FOR UPDATE; -- other transactions wait here
-- the application counts the rows returned and continues only if there are 2 or more
UPDATE doctors SET on_call = false WHERE id = 7;
COMMIT;
6. Fixing Anomalies in Practice
| Problem | Fix |
|---|---|
| Lost update | An atomic update (SET stock = stock - 1), a row lock (SELECT ... FOR UPDATE), or optimistic locking with a version column |
| Write skew | Serializable, or lock the rows that were read, or a constraint |
| Phantom | Serializable, or a unique constraint that blocks the duplicate row |
| Deadlock | Lock rows in the same order everywhere, keep transactions short, and retry the aborted one |
| Serialization failure | Retry the whole transaction (error code 40001 in PostgreSQL) |
Background note: Why the atomic update is safeTake
UPDATE item SET stock = stock - 1 WHERE id = ? AND stock > 0with stock = 1 and two threads.
- Thread A locks the row, sees
stock > 0, sets stock to 0 and commits.- Thread B finds the same row and waits for the lock.
- When A commits, B checks the
WHEREclause again against the new value. Stock is 0, so B changes 0 rows.Your code treats "1 row changed" as sold and "0 rows changed" as sold out. The check and the change are one statement under one lock, so no other thread can slip in between. A read-then-write (
SELECT stock, thenUPDATE) fails because both threads read 1 before either one writes. The lock lasts until the transaction ends, so keep it short. In PostgreSQL Repeatable Read, B gets a serialization error instead and must retry.
6.1 Optimistic Locking in Java
Optimistic locking assumes conflicts are uncommon. It adds a version number to the row, and the update succeeds only if the version has not changed:
@Entity
public class Product {
@Id private Long id;
private int stock;
@Version private long version; // JPA adds "AND version = ?" to every update
// getters and setters omitted
}
@Service
public class StockService {
private final ProductRepository repo;
public StockService(ProductRepository repo) { this.repo = repo; }
@Transactional
public void reserve(long productId, int qty) {
Product p = repo.findById(productId).orElseThrow();
if (p.getStock() < qty) throw new OutOfStockException();
p.setStock(p.getStock() - qty); // at commit: UPDATE ... WHERE id = ? AND version = ?
}
}
// the caller retries, because the loser gets ObjectOptimisticLockingFailureException
public void reserveWithRetry(long id, int qty) {
for (int attempt = 1; ; attempt++) {
try {
stockService.reserve(id, qty); // each call is one new transaction
return;
} catch (ObjectOptimisticLockingFailureException e) {
if (attempt == 3) throw e; // give up after 3 tries
}
}
}
- Optimistic (version column) suits rows that are seldom contested. Conflicts cost a retry.
- Pessimistic (
FOR UPDATE) suits hot rows, where conflicts are common and retries would pile up. Waiting is cheaper than failing. - The retry must run the whole transaction again, including the reads, and must live outside the transaction method.
6.2 Locks Limit Throughput
A row that is locked can serve only one transaction at a time. Say a sale product gets 240,000 purchase attempts a day, about 2.8 a second. In a flash sale the rate is 20 times higher, about 56 a second. If each transaction holds the stock row lock for 10 ms, the row handles 1 ÷ 0.010 = 100 transactions a second, and it keeps up. If the transaction also calls a payment service inside the lock and holds it for 50 ms, the limit drops to 20 a second. Requests queue up and time out. Do the slow work outside the transaction, and keep the locked part to a single quick update.
This is the difference between concurrency and contention. More servers add concurrency, but writers to the same row still go one at a time, so a hot row caps at about 1 ÷ lock time updates a second. Prefer one atomic statement to read, check, write. In a test with 20 clients each withdrawing 100 from 1,000 at READ COMMITTED, read-then-write approved 20 withdrawals and left 600. UPDATE ... SET balance = balance - 100 WHERE id = ? AND balance >= 100 approved exactly 10 and left 0.
7. Beyond One Database
- ACID covers one database node, or one shard. Across several services or databases there is no shared transaction. Use sagas and the outbox pattern, or two-phase commit when you must (see the distributed transactions lesson).
- Many NoSQL stores give atomic writes for one item or one partition only, and some offer limited multi-item transactions (see the NoSQL lesson).
- Sharding turns a single-node transaction into a cross-shard one unless you pick the shard key so related rows stay together (see the sharding lesson).
8. Common Pitfalls
- Assuming Repeatable Read prevents everything. Write skew still happens.
- Read, change, write in the application without a lock or a version check, which loses updates.
- Calling another service inside a transaction. Locks and a connection are held while you wait on the network.
- Long transactions, which hold locks, block others, keep old versions alive and drain the connection pool.
- Not retrying deadlocks and serialization failures. They are normal events, not bugs.
- Inconsistent lock order, so deadlocks appear under load.
- Spring traps: a checked exception does not roll back, and calling a
@Transactionalmethod from another method of the same class skips the transaction (the proxy is bypassed). - Using Serializable everywhere without handling its aborts and its cost.
9. Interview Questions This Lesson Prepares You For
- What does ACID mean? Atomicity (all or nothing), consistency (valid state to valid state, with your rules and the declared constraints), isolation (concurrent transactions do not interfere) and durability (committed data survives a crash, through the write-ahead log).
- Name the isolation levels and the anomaly each one prevents. Read Uncommitted allows dirty reads. Read Committed stops dirty reads. Repeatable Read also stops non-repeatable reads, and in PostgreSQL phantoms too. Serializable stops everything, including write skew. Then name the defaults: PostgreSQL uses Read Committed and MySQL InnoDB uses Repeatable Read.
- What is the difference between a lost update and write skew? In a lost update two transactions write the same row and one overwrites the other. In write skew they write different rows after reading the same data, and together they break a rule. Lost updates are fixed with atomic updates, locks or version checks. Write skew needs Serializable, locking the rows that were read, or a constraint.
- How does MVCC work, and why is it popular? Each write makes a new row version. Each transaction reads from its own snapshot, so readers and writers do not block each other. The cost is storage for old versions and the cleanup work.
- Optimistic or pessimistic locking? Optimistic (a version column and a retry) when conflicts are seldom. Pessimistic (
SELECT ... FOR UPDATE) when a few hot rows are contested and retries would pile up. - Two users buy the last item at the same time. How do you stop overselling? Make the stock check and decrement one atomic statement (
UPDATE ... SET stock = stock - 1 WHERE id = ? AND stock > 0) and check that one row changed. Or lock the row, or use a version column. Keep the transaction short and make no network calls inside it. - How do you handle a deadlock? The database aborts one transaction. Retry it. To prevent deadlocks, lock rows in a fixed order and keep transactions short.