Isolation and transaction boundaries
What you will learn
A transaction is a unit of work with a commit or rollback boundary. Isolation specifies what concurrent transactions can observe; it is not the same as atomicity. Start with one invariant, choose a database-specific isolation level, and verify state from a separate transaction.
- Compare ACID and PostgreSQL isolation levels.
- Separate physical transactions from Spring proxy boundaries.
- Detect a stale write using a version predicate.
Plain Java examples: save as Main.java in a fresh directory, then run javac --release 21 Main.java and java Main. PostgreSQL and Spring examples require the companion lab or configured infrastructure. Their predicted results are not execution evidence.
Stage both changes before publishing
public class Main { record State(int stock,int reservations) {} static State reserve(State s,int n){ if(n<=0||n>s.stock())throw new IllegalArgumentException("quantity"); return new State(s.stock()-n,s.reservations()+1); } public static void main(String[] args) {var before=new State(5,0); var proposed=reserve(before,2); System.out.println(before); System.out.println(proposed); }}Expected output:
State[stock=5, reservations=0]State[stock=3, reservations=1]The original immutable state is unchanged until the caller chooses the new state. This models atomic publication only; no database or durability.
ACID and isolation
Atomicity means all participating writes commit together or none do; consistency means constraints and application invariants hold; isolation governs concurrent observations; durability depends on database configuration and guarantees after commit. PostgreSQL 17 treats READ UNCOMMITTED as READ COMMITTED. READ COMMITTED takes a fresh snapshot for each statement, so successive reads can differ. REPEATABLE READ uses a transaction snapshot and rejects certain concurrent updates, but can permit serialization anomalies. SERIALIZABLE detects unsafe dependency cycles and can abort transactions; retry the entire unit on SQLSTATE 40001. A row lock can serialize access to known rows, but lock order matters. SQL isolation is not Java synchronized.
Service boundaries and rollback
The caller enters a Spring-managed proxy, the interceptor begins or joins a transaction, the service invokes repositories, and the interceptor commits or rolls back before returning to the caller. Default rollback is for unchecked exceptions and Error, not checked exceptions unless configured (or a different global default is selected). rollbackFor explicitly covers a checked IOException. Self-invocation in default proxy mode bypasses interception. REQUIRED shares a transaction; REQUIRES_NEW suspends it and obtains independent resources; NESTED typically uses savepoints with compatible transaction managers, not an independent commit. A remote HTTP request is not undone by a database rollback. A JPA flush sends changes, but commit can still fail.
Reject a stale update
public class Main { record Row(int stock,long version) {} static java.util.Optional<Row> update(Row r,long expected,int qty){ if(qty<=0||qty>r.stock()||expected!=r.version())return java.util.Optional.empty(); return java.util.Optional.of(new Row(r.stock()-qty,r.version()+1)); } public static void main(String[] args) {var current=new Row(5,0); current=update(current,0,2).orElseThrow(); System.out.println(current); System.out.println(update(current,0,1).isEmpty()); }}Expected output:
Row[stock=3, version=1]trueA database equivalent requires an atomic UPDATE with version and stock predicates and checking the row count. Two separate SELECT/UPDATE statements are not equivalent.
Two-session isolation experiment
Source-reviewed, NOT RUN. File lab-fixtures/database-architecture-v43/isolation.md; use the companion lab README.
# Two-session PostgreSQL 17 experiment — NOT RUNStart from fresh V1 data. Open two psql sessions, A and B, on the same disposable database. Set `statement_timeout='5s'` and `lock_timeout='2s'` in both. No timing sleeps are required: execute the steps in the exact listed order.
1. A: `BEGIN ISOLATION LEVEL READ COMMITTED; SELECT stock FROM inventory WHERE sku='B1';` predicts 5.2. B: `BEGIN; UPDATE inventory SET stock=4 WHERE sku='B1'; COMMIT;`3. A: same SELECT predicts 4; COMMIT.4. Reset stock to 5 in autocommit. Repeat steps 1–3 with A using REPEATABLE READ; A's second SELECT predicts 5. PostgreSQL takes the snapshot at the first non-transaction-control statement, not merely BEGIN.5. Reset again. A and B each BEGIN ISOLATION LEVEL SERIALIZABLE; each SELECT sum(stock) FROM inventory; A updates B1 to 4; B updates B2 to 7; A commits, then B commits (or one statement/commit may fail earlier). Expect one transaction to abort with 40001; do not assume a particular victim. Check that exactly one change committed. Roll back any failed transaction.6. Reset again. A begins, changes B1 to 4, and rolls back. A fresh session SELECT predicts 5. Test stale version separately: update with WHERE version=0, increment version; repeat with version=0 and expect UPDATE 0. Roll back test changes.
These are predictions, not measured PostgreSQL behavior. Close both sessions. Never perform this experiment against shared or production data.Predicted behavior: READ COMMITTED sees B’s committed change on the second read; REPEATABLE READ retains its snapshot; SERIALIZABLE may abort one transaction.
Manual sequence with explicit session coordination, not executed.
Checked exception rollback
Source-reviewed, NOT RUN. File lab-fixtures/database-architecture-v43/CheckedWriter.java; use the companion lab README.
// Illustrative Spring service, not standalone; NOT RUN.package example.tx;import java.io.IOException;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;@Servicepublic class CheckedWriter { private final JdbcTemplate jdbc; public CheckedWriter(JdbcTemplate jdbc) { this.jdbc = jdbc; } @Transactional(rollbackFor = IOException.class) public void reserveThenFail(String sku) throws IOException { int changed = jdbc.update("UPDATE inventory SET stock=stock-1 WHERE sku=? AND stock>0", sku); if (changed != 1) throw new IllegalStateException("not available"); throw new IOException("synthetic failure"); }}Predicted behavior: A managed invocation should roll back the stock update when IOException escapes.
Requires real Spring transaction interception and a configured PostgreSQL datasource.
Common mistakes
Do not catch and suppress a rollback-triggering failure then return success. Do not use REQUIRES_NEW to make an inner audit write appear atomic with an outer transaction; its commit can survive outer rollback.
Practice
For a starting stock of 7/version 3, accept reservation 4 with expected version 3, then reject a second request with stale version 3. Print stock/version and whether the stale request was rejected.
Expected output:
3/4trueCompare with the manual review criteria.
Official reading: Isolation · Locks · Spring · Propagation · JDBC. PostgreSQL and Spring execution and independent review remain pending.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Isolation and transaction boundaries — knowledge check
Database transaction and data architecture reasoning.
In PostgreSQL READ COMMITTED, can two SELECT statements in one transaction see different committed values?
What is the correct response to a serialization failure?
A checked IOException should trigger Spring rollback. What explicitly configures that?
What does a version-predicate UPDATE returning zero rows indicate?
What normally happens on self-invocation in proxy transaction mode?