All or nothing
Paying for something is two steps: money leaves your purse, and arrives in the till. If the till breaks halfway, you want your money back, not lost in between. Either both happen or neither does. And once the shop says "done", it stays done, even if the lights go out.
ACID
A transaction groups statements between BEGIN and COMMIT:
- Atomicity: all changes apply, or on
ROLLBACKor error, none do. - Consistency: constraints (keys, checks) hold before and after.
- Isolation: concurrent transactions don't see each other's half-done work (to a degree you choose).
- Durability: once committed, changes survive crashes, thanks to the write-ahead log.
In Spring, @Transactional on a service method opens a transaction and commits or rolls it back for you.
What other shoppers see
While you've got the last teddy in your basket but haven't paid, should other shoppers see the shelf as empty? Usually they see only what's been paid for. A stricter shop gives each shopper a photo of the shop as it was when they walked in, so their view never changes mid-visit.
Isolation levels
| Level | Prevents | Still allows |
|---|---|---|
| READ UNCOMMITTED | (almost nothing) | dirty reads |
| READ COMMITTED (Postgres, Oracle default) | dirty reads | non-repeatable reads, phantoms |
| REPEATABLE READ (MySQL default) | + non-repeatable reads | some anomalies (write skew) |
| SERIALIZABLE | everything | (may abort transactions to retry) |
Most databases use MVCC: writers create new row versions, and readers see a consistent snapshot without locking.
One teddy, two shoppers
Two shoppers see one teddy, both buy it, both write "none left". The shop sold two of one. The fix: say "take one, only if there's one left", or hold the shelf while you check.
Lost updates
Read-then-write in application code races even inside transactions at READ COMMITTED. Fixes:
- an atomic update:
UPDATE stock SET qty = qty - 1 WHERE id = ? AND qty > 0, then check the row count, - a pessimistic lock:
SELECT ... FOR UPDATEholds the row until commit, - optimistic locking: a
versioncolumn (JPA@Version), so a stale update affects 0 rows and is retried, - or SERIALIZABLE isolation with retries.