Transactions & ACID

What a transaction is, the four ACID properties and how databases implement each, commit and rollback, savepoints, and using transactions correctly from application code.

Intermediate 3 min readLesson 9 of 14 Interview Q&A

A transaction groups several operations into a single logical unit: either all of them take effect, or none do. Without transactions, a crash or a concurrent user could leave data half-updated — money debited but never credited.

SQL
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;          -- both changes become permanent together
-- or ROLLBACK;  -- undo everything since BEGIN

ACID

PropertyPromiseImplemented with
AtomicityAll or nothing, even if the server crashes mid-transactionUndo information (undo logs, or MVCC versions) + WAL
ConsistencyEach transaction moves the database from one valid state to another: constraints, foreign keys and invariants holdConstraints and triggers in the DB, plus correct application logic
IsolationConcurrent transactions don't see each other's partial work; the result is as if they ran in some order (to a configurable degree)Locks and/or MVCC (Isolation levels)
DurabilityOnce committed, data survives crashes and power lossWAL fsynced at commit; replication for machine failures

How atomicity and durability work

AppDatabaseWAL on diskData filesBEGIN; UPDATE …; UPDATE …modify pages in the buffer pool; append log recordsCOMMITappend commit record + fsyncOK (now durable)later: checkpoint writes dirty pages

After a crash, recovery redoes committed work from the WAL and undoes (or ignores, under MVCC) anything uncommitted. See Storage engines.

Savepoints

Partial rollback inside a transaction:

SQL
BEGIN;
INSERT INTO orders (...) VALUES (...);
SAVEPOINT before_items;
INSERT INTO order_items (...) VALUES (...);   -- fails a constraint
ROLLBACK TO SAVEPOINT before_items;          -- keep the order, retry the items
COMMIT;

Transactions in application code

// Spring: declarative transactions
@Transactional
public void transfer(long from, long to, BigDecimal amount) {
    Account a = repo.findByIdForUpdate(from);       // SELECT ... FOR UPDATE
    Account b = repo.findByIdForUpdate(to);
    if (a.getBalance().compareTo(amount) < 0) throw new InsufficientFunds();
    a.debit(amount);
    b.credit(amount);
}   // commit on return; rollback on RuntimeException

// Plain JDBC
conn.setAutoCommit(false);
try {
    // ... statements ...
    conn.commit();
} catch (SQLException e) {
    conn.rollback();
    throw e;
}

Best practices

  • Keep transactions short. Long transactions hold locks, block vacuum/purge (bloat), and increase conflicts. Never wait for user input or call slow external APIs inside one.
  • Don't mix external side effects (sending email, charging a card) with a database transaction: a rollback can't unsend an email. Use the transactional outbox pattern — write an "event to send" row in the same transaction, and have a separate process deliver it.
  • Retry on serialisation failures and deadlocks — they're normal under concurrency. Make the transaction body idempotent so a retry is safe.
  • Know your framework's defaults: autocommit mode, transaction propagation (@Transactional on self-calls in Spring is silently ignored), and the default isolation level.

Beyond one database

ACID transactions are easy within a single database node. Across services or shards, you need distributed protocols (two-phase commit) or patterns like sagas with compensating actions — see Distributed transactions.

Key takeaways
  • A transaction is all-or-nothing: BEGIN … COMMIT / ROLLBACK.
  • Atomicity and durability come from the WAL (+ undo); isolation from locks/MVCC; consistency from constraints plus correct logic.
  • Durability depends on fsync settings and honest hardware.
  • Keep transactions short, retry on conflicts, and never mix in irreversible external side effects (use an outbox).
Interview questions
QExplain ACID with a bank transfer example.easy

Atomicity: debit and credit both happen or neither does. Consistency: balances can't go negative and money isn't created or destroyed. Isolation: a concurrent report never sees the money missing from both accounts mid-transfer. Durability: once the transfer is confirmed, a crash won't undo it.