Lesson · JDBC
Transactions: auto-commit, isolation levels and lost updates
16 min readTransactions
Auto-commit turns every statement into its own transaction, so a two-statement operation can half-commit. A transaction groups statements into one unit, and the isolation level decides what other transactions may see while it runs. Then the everyday race: two transactions, one row, one lost update.
The problem: two statements that must travel together
A transfer is two UPDATEs: debit one account, credit the other. If the process dies between them you have lost money, which is the dramatic version. The version that actually ships is quieter: auto-commit is on by default, every statement is its own transaction, and the credit fails while the debit has already committed. No crash required.
A transaction is the promise that fixes both cases: group the statements, and the database makes the group all-or-nothing. The boundary is not a block in your language. It is the Connection.
// auto-commit ON (the JDBC default): every statement commits on its own debit(conn, from, amount); // committed right here credit(conn, to, amount); // if this throws, the debit is already permanent
The unit of atomicity is the transaction, and you are the one defining it. With auto-commit on you defined it as one statement, whether you thought about it or not.
The mechanics: setAutoCommit(false), commit, rollback
Turn auto-commit off, do the work, commit on success, roll back in the catch path, then return the connection. In a pooled setup close returns it for reuse, which is exactly why the rollback has to happen before that: an open transaction handed back is everybody's problem.
Keep the transaction short. It holds locks for its whole duration, so it must never span user think-time, a call to another service if you can avoid it, or anything else measured in seconds. Work that needs many round trips belongs before or after the transaction, not inside it.
conn.setAutoCommit(false)marks the start of your unit on this connection.- Run the statements. Nothing is visible to other transactions yet.
conn.commit()makes the statements visible together;conn.rollback()throws them away when a step fails.- Restore auto-commit and return the connection (close, or the pool's equivalent).
The Connection is the transaction boundary. Every statement on it belongs to the same unit until you commit or roll back, and nobody blinks on your behalf.
ACID, one line each
The four letters are four different promises, and only one of them is negotiable at runtime:
- Atomicity: all statements commit or none do, so a failure in the middle leaves no partial work behind.
- Consistency: the database moves from one valid state to another, with constraints enforced at commit time.
- Isolation: concurrent transactions never see uncommitted work; the level decides how much committed change they may miss or re-see.
- Durability: once commit returns, the change survives a crash. The how is the storage engine's business.
Isolation is the only ACID letter with dials. The other three are promises you either have or do not; isolation is the trade you tune, which is why it gets the next two sections.
The three phenomena, each a two-connection story
Every isolation level is defined against the same three anomalies, and each one needs two transactions to tell:
- Dirty read: C1 writes a value and has not committed; C2 reads it. If C1 rolls back, C2 acted on data that never existed.
- Non-repeatable read: C2 reads a row; C1 updates and commits it; C2 reads the same row again and gets a different value. Same query, two answers inside one transaction.
- Phantom read: C2 runs a range query; C1 inserts a row that matches and commits; C2 re-runs the query and an extra row is there. The set changed, not just the values.
All three are the same shape: a read changing under you. Dirty involves uncommitted data, non-repeatable involves one row changing, phantom involves matching rows appearing.
Isolation levels: the dial
The four standard levels are a checklist against the three phenomena. Read the table in one direction: each level prevents its own row plus everything above it.
Defaults are worth knowing, because they are what you actually get: PostgreSQL and Oracle default to READ_COMMITTED, while MySQL's InnoDB defaults to REPEATABLE_READ. PostgreSQL's REPEATABLE_READ is snapshot isolation and also prevents phantoms; InnoDB's REPEATABLE_READ uses next-key locking that blocks most phantom inserts. The standard column in the table describes the specification; the engine you run is the reality.
Set the level before the work starts: Connection.setTransactionIsolation on the connection, ideally in the pool configuration so every borrowed connection inherits it. Raise it only when the logic needs the guarantee, because isolation is bought with concurrency: stricter levels hold more locks, or abort more transactions with serialization failures that your code must retry.
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| READ_UNCOMMITTED | Possible | Possible | Possible |
| READ_COMMITTED | Prevented | Possible | Possible |
| REPEATABLE_READ | Prevented | Prevented | Possible per the standard |
| SERIALIZABLE | Prevented | Prevented | Prevented |
Default first, raise on evidence. READ_COMMITTED is the common default for a reason; move to REPEATABLE_READ or SERIALIZABLE when an invariant spanning several statements genuinely demands it.
Lost update: the everyday race
The most common concurrency bug in database code needs no exotic schedule. Read a balance, compute a new value in the application, write it back. Two transactions do this at the same time under READ_COMMITTED, both read 100, both write 80, and one of the two debits evaporates. No error, no warning.
There are three fixes, and they differ in who blocks and who retries:
| Fix | Mechanism | Blocks other writers? | Fit and cost |
|---|---|---|---|
| Atomic SQL | UPDATE account SET balance = balance - ? WHERE id = ?: read and write in one statement | Only for the statement's duration | Best fit for arithmetic and counters; no retry code, no extra round trip |
| Optimistic locking | A version column: UPDATE ... WHERE id = ? AND version = ?; 0 rows affected means someone else won | No: conflicts are detected, not prevented | Low contention and retryable logic; costs a retry loop and wasted work when contention is high |
| Pessimistic locking | SELECT ... FOR UPDATE locks the row before you read it | Yes: writers queue for the row | High contention where retries are expensive; transactions must stay short or the queue becomes the bottleneck |
Two connections · READ_COMMITTED
account 1 · balance
100
not connected
not connected
Two connections, one row: account 1, balance 100. Both transactions run at READ_COMMITTED, the level stated in the header. Nothing is open yet.
Savepoints and deadlocks
A savepoint marks a point inside a transaction, so a later failure can undo one step and keep the rest. The transaction remains one unit; you have gained a partial undo inside it: rollback(savepoint) undoes everything after the mark, and releaseSavepoint discards the mark once that step has succeeded.
conn.setAutoCommit(false); // savepoints live inside a transaction Savepoint afterFirst = conn.setSavepoint("after-first"); try { runSecondStep(conn); // may fail for its own reasons } catch (SQLException e) { conn.rollback(afterFirst); // second step undone, first step kept } conn.commit(); // one unit of work, partially salvaged
- Deadlocks are detected, not prevented: two transactions each hold a lock the other wants, and the database kills one victim to break the cycle.
- The victim arrives as an exception: SQLState 40P01 on PostgreSQL, error 1213 on MySQL; JDBC usually surfaces it as a SQLTransactionRollbackException from the SQLTransient family.
- Handle it by retrying the unit: catch, roll back, and run the whole transaction again with backoff. Half-recovered transactions are not a thing.
- Reduce them by lock ordering: when every code path locks the same rows in the same sequence, the cycles stop forming.
Deadlocks are a scheduling accident; crashes are a design choice. Catch the rollback exception, retry the unit, and keep your lock order consistent.
READ_COMMITTED protects the write, not your read-modify-write
The default level stops dirty reads, which feels safe, and it still lets two transactions read the same value, compute from it, and overwrite each other's write. Your snapshot lasts for one statement. Any logic spanning read, compute and write needs an atomic statement, a version check or an explicit lock.
Interview angles
What does auto-commit do, and why is it a problem for multi-statement logic?+
With auto-commit on, every statement is its own transaction, so a two-statement operation can commit its first half and fail the second. Group the statements with setAutoCommit(false), commit on success, and roll back in the catch path.
What does READ_COMMITTED prevent, and what does it allow?+
It prevents dirty reads: uncommitted writes stay invisible. It allows non-repeatable reads and phantoms, because each statement gets a fresh view of committed data, so two identical reads inside one transaction can disagree.
Explain a lost update and its three fixes.+
Two transactions read the same value, both compute, both write, and one write overwrites the other. Fix it with an atomic statement (balance = balance - ?) where possible, an optimistic version check with retry, or SELECT ... FOR UPDATE to serialize writers, choosing by contention and by what happens between read and write.
What does raising isolation to SERIALIZABLE cost?+
Throughput and retries. Stricter levels hold more locks or abort conflicting transactions with serialization failures, so the application must be written to retry whole units. Move up when an invariant across statements genuinely requires it.
A transaction fails with a deadlock. What does your code do?+
Catch the rollback exception (SQLState 40P01 on PostgreSQL, error 1213 on MySQL; JDBC surfaces it in the SQLTransient family), roll back, and retry the whole unit with backoff. Keep lock order consistent across code paths so the cycles stay rare.
When is SELECT ... FOR UPDATE the right tool, and when is it a trap?+
Right when the logic between read and write cannot fit in one statement and contention is real: the row lock makes writers queue and removes the stale-read window. A trap when transactions are long, because everyone queues behind you, and when lock ordering varies, because that is how deadlocks are made.