Topic 7.2
Transactions / ACID
In one line
Atomicity, Consistency, Isolation, Durability — the contract that makes bank transfers safe and your LLD's ledger correct.
Think of it like this
Transferring cash from one envelope to another. You must take money OUT of envelope A and put it IN envelope B as a single, uninterruptible action — if you get interrupted after taking it out but before putting it in, the money should never just vanish.
Key ideas
- 01
Atomicity: all or nothing — a transfer debits AND credits, or neither happens (WAL + undo).
- 02
Consistency: the DB never moves between valid states (constraints/triggers enforce business rules).
- 03
Isolation: concurrent transactions behave as if serialized (or as much as you configured).
- 04
Durability: once committed, survives crashes (WAL flushed + replicas).
- 05
Postgres/MySQL implement durability via the write-ahead log — fsync the log before replying 'committed'.
- 06
The interview habit: when a flow touches two tables, say '@Transactional' and name what rollback protects.
Java / Spring map
- →
@Transactional on Spring services; @Transactional(readOnly=true) for query paths.
Code & diagrams
The atomic bank transfer — why the annotation is not optional.
@Service
public class TransferService {
private final AccountRepo accounts;
@Transactional // atomic: both rows or none
public void transfer(long fromId, long toId, long cents) {
Account from = accounts.lockById(fromId); // SELECT ... FOR UPDATE
Account to = accounts.lockById(toId);
if (from.balanceCents() < cents) throw new InsufficientFunds();
from.debit(cents);
to.credit(cents);
accounts.save(from);
accounts.save(to);
// A crash between these two saves? The WAL rolls BOTH back. That is ACID.
// (Lock order caveat: to avoid deadlocks, lock by ascending account id.)
}
}Explain without notes
What exactly does the write-ahead log have to do with durability?
Practice
List three operations from your LLDs that MUST be transactional and three that should NOT be.
Trade-offs
- ↔
Long transactions hold locks → contention. Keep transactions small; move slow work out of them.
Run it in production
You've designed it. Now build, operate, and break the same idea hands-on in the DevOps courses:
Completion checklist
I can explain each ACID letter and point at the mechanism (WAL) for one.