Transactions, ACID & isolation levels
What a transaction really guarantees. Atomicity through durability, MVCC in Postgres, the read anomalies (dirty, non-repeatable, phantom, lost update, write skew) and which isolation level prevents each.
ACID
| Letter | Guarantee | Example in your projects |
|---|---|---|
| Atomicity | All or nothing | Posting a journal saves the entry, all lines and the audit row together, or none of them |
| Consistency | Constraints hold after every commit | CHECK (current_occupancy <= capacity) is never violated |
| Isolation | Concurrent transactions don’t see each other’s partial work | Two approvals of the same room |
| Durability | Committed data survives a crash | Postgres WAL is fsynced before commit returns |
MVCC: how Postgres isolates
Postgres uses Multi-Version Concurrency Control. An UPDATE writes a new row version rather than overwriting the old one. Each transaction reads from a snapshot, so:
- Readers never block writers, and writers never block readers.
- Writers do block writers on the same row: the second waits for the first to commit or roll back.
- Old versions are cleaned up by VACUUM, and long-running transactions stop that cleanup, which causes bloat.
Anomalies and isolation levels
| Anomaly | What happens |
|---|---|
| Dirty read | You see another transaction’s uncommitted changes |
| Non-repeatable read | You read a row twice and get different values |
| Phantom read | You re-run a query and new rows appear |
| Lost update | Two transactions read, modify and write; one write silently overwrites the other |
| Write skew | Two transactions read overlapping data and each writes something that is valid alone but invalid together |
| Level (Postgres) | Dirty | Non-repeatable | Phantom | Lost update | Write skew |
|---|---|---|---|---|---|
| Read Committed (default) | ✅ prevented | ❌ | ❌ | ❌ | ❌ |
| Repeatable Read (snapshot) | ✅ | ✅ | ✅ (in PG) | ✅ (aborts with a serialization error) | ❌ |
| Serializable (SSI) | ✅ | ✅ | ✅ | ✅ | ✅ (aborts one) |
Postgres has no Read Uncommitted; asking for it gives Read Committed.
The classic lost update
T1: SELECT current_occupancy FROM rooms WHERE id=R -> 3
T2: SELECT current_occupancy FROM rooms WHERE id=R -> 3
T1: UPDATE rooms SET current_occupancy = 4 ... (capacity 4)
T2: UPDATE rooms SET current_occupancy = 4 ... <- should be 5, i.e. overbooked, but the update is lost
Fixes, all covered in the locking lesson:
- An atomic update:
SET current_occupancy = current_occupancy + 1 WHERE current_occupancy < capacity. - A pessimistic lock:
SELECT ... FOR UPDATE. - An optimistic lock:
@Version. - Serializable isolation with retry.
In your projects
BookingService.approveBooking()Hostel runs at Read Committed and locks explicitly (findByIdForUpdate) before re-checking capacity. Even if that check were missed, the CHECK constraint would still stop overbooking. This is defence in depth.
DefaultPostingEngine (@Transactional) · pg_advisory_xact_lockPosting runs in one transaction with a per-company advisory lock, so journal numbers stay gap-free and balances are consistent. The lock is tied to the transaction (_xact_), so commit or rollback releases it automatically.
WalletRepository.findByUserIdForUpdate · LedgerServiceWallet debits lock the wallet row with PESSIMISTIC_WRITE, then write balanced ledger postings in the same transaction. Money paths always use explicit locking or atomic SQL.
Related concepts you must know
- Deadlocks. T1 locks A then B, while T2 locks B then A. Postgres detects this and aborts one of them. Prevent it by always locking in a consistent order (e.g. by id).
- Keep transactions short. Never call HTTP APIs (Stripe, Paystack, email) inside a DB transaction, because you hold locks and a pooled connection while the network stalls. Your projects publish events after commit instead (Module 5).
- Savepoints. These are partial rollbacks; JPA exposes them with
NESTEDpropagation. - Distributed transactions. ACID stops at one database. Across services you need sagas or the outbox pattern (bonus module).