Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

ACID Transactions and Isolation Levels Explained

Understand ACID database transactions (atomicity, consistency, isolation, durability), read anomalies like dirty reads and phantoms, the four SQL isolation levels, locking vs MVCC and how to use transactions safely in code.

Sumit KumarUpdated Oct 11, 20264 min readSystem Design
ACID Transactions and Isolation Levels Explained

Imagine moving ₹500 from Asha's account to Ravi's. The debit succeeds, then the server crashes before the credit. Money has vanished. Transactions exist to make that impossible, and ACID describes the four guarantees they provide.

What is a transaction?#

A transaction is a group of operations that the database treats as a single unit of work: either all of them take effect, or none do.

ACID properties of database transactions: atomicity, consistency, isolation and durability, with a bank transfer example and isolation levels from read uncommitted to serializable
SQL
BEGIN;
UPDATE accounts SET balance = balance - 500 WHERE id = 'asha';
UPDATE accounts SET balance = balance + 500 WHERE id = 'ravi';
COMMIT;   -- both changes become permanent together
-- or ROLLBACK; to undo everything since BEGIN

The four ACID properties#

PropertyGuaranteeIn the bank exampleHow databases implement it
AtomicityAll or nothingNever debit without creditUndo logs, rollback
ConsistencyData moves from one valid state to anotherBalance never goes negative; totals still matchConstraints, foreign keys, triggers, plus correct app logic
IsolationConcurrent transactions don't interfereTwo transfers at once don't overwrite each otherLocks or MVCC snapshots
DurabilityCommitted data survives crashesAfter "transfer successful", a power cut doesn't undo itWrite-ahead log (WAL) flushed to disk, replication

Consistency through constraints#

SQL
ALTER TABLE accounts
  ADD CONSTRAINT balance_non_negative CHECK (balance >= 0);

BEGIN;
UPDATE accounts SET balance = balance - 5000 WHERE id = 'asha';
-- ERROR: violates check constraint "balance_non_negative"
ROLLBACK;  -- the whole transaction is aborted

Durability through the write-ahead log#

Before changing data pages, the database appends the change to a sequential write-ahead log and flushes it to disk. On restart after a crash, it replays committed log entries and discards uncommitted ones.

Isolation: the tricky one#

Perfect isolation (every transaction behaves as if it ran alone) is expensive. Databases therefore offer weaker isolation levels that allow certain anomalies in exchange for better concurrency.

Read anomalies#

AnomalyWhat happens
Dirty readT1 reads data T2 has written but not committed; T2 rolls back, so T1 saw data that never existed.
Non-repeatable readT1 reads a row twice and gets different values because T2 updated and committed it in between.
Phantom readT1 runs the same range query twice and gets new rows because T2 inserted matching rows.
Lost updateT1 and T2 both read a value, modify it and write it back; one write overwrites the other.
Write skewTwo transactions read overlapping data, make disjoint writes, and together break a rule neither broke alone.

A non-repeatable read, step by step#

Text
Time  T1 (report)                         T2 (transfer)
 1    BEGIN
 2    SELECT balance FROM accounts
      WHERE id='asha'      → 1000
 3                                        BEGIN
 4                                        UPDATE accounts SET balance=500
                                          WHERE id='asha'
 5                                        COMMIT
 6    SELECT balance FROM accounts
      WHERE id='asha'      → 500   (changed inside one transaction!)
 7    COMMIT

The four SQL isolation levels#

LevelDirty readNon-repeatable readPhantom read
Read UncommittedPossiblePossiblePossible
Read CommittedPreventedPossiblePossible
Repeatable ReadPreventedPreventedPossible*
SerializablePreventedPreventedPrevented

*PostgreSQL's Repeatable Read uses snapshot isolation and also prevents phantoms; MySQL InnoDB's Repeatable Read prevents most phantoms with gap locks.

Defaults matter

PostgreSQL, Oracle and SQL Server default to Read Committed. MySQL InnoDB defaults to Repeatable Read. Know your default before reasoning about concurrency bugs.

SQL
-- PostgreSQL / MySQL
BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE;
-- ...
COMMIT;

-- or for the session
SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL REPEATABLE READ;

How isolation is implemented: locks vs MVCC#

Two-phase locking (2PL)MVCC
IdeaReaders and writers take shared/exclusive locksKeep multiple versions of each row; readers see a snapshot
Readers block writers?YesNo
CostLock contention, deadlocksOld versions need cleanup (VACUUM / purge)
Used bySQL Server (default), serializable modesPostgreSQL, MySQL InnoDB, Oracle

Preventing lost updates#

1. Atomic update in SQL#

SQL
-- Good: the database does read-modify-write atomically
UPDATE products SET stock = stock - 1 WHERE id = 42 AND stock > 0;

2. Pessimistic locking#

SQL
BEGIN;
SELECT stock FROM products WHERE id = 42 FOR UPDATE;  -- locks the row
-- application logic decides
UPDATE products SET stock = 9 WHERE id = 42;
COMMIT;

3. Optimistic locking with a version column#

SQL
UPDATE products
SET stock = 9, version = version + 1
WHERE id = 42 AND version = 7;
-- 0 rows updated → someone else changed it; reload and retry

Transactions in application code#

Java
@Service
public class TransferService {

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void transfer(String from, String to, BigDecimal amount) {
        Account src = accounts.findByIdForUpdate(from);   // SELECT ... FOR UPDATE
        Account dst = accounts.findByIdForUpdate(to);
        if (src.getBalance().compareTo(amount) < 0) {
            throw new InsufficientFundsException();          // triggers rollback
        }
        src.debit(amount);
        dst.credit(amount);
    }   // commit happens here if no exception
}
Spring @Transactional gotchas

By default only unchecked exceptions trigger rollback; calling a @Transactional method from inside the same class bypasses the proxy, so no transaction starts. See the Spring Boot REST API guide and Java exception handling.

Best practices#

  • Keep transactions short: never wait for user input or call slow external APIs inside one.
  • Lock rows in a consistent order (for example by ID) to avoid deadlocks.
  • Be ready to retry on serialization failures and deadlocks.
  • Use the weakest isolation level that is still correct for each operation.
  • Across services there is no shared transaction; use sagas instead (see microservices vs monolith).

Compare how NoSQL systems relax these guarantees in SQL vs NoSQL databases.

Key takeaways#

  • A transaction is all-or-nothing: COMMIT makes every change permanent, ROLLBACK undoes them.
  • ACID means atomicity, consistency, isolation and durability.
  • Weaker isolation levels allow dirty reads, non-repeatable reads and phantoms in exchange for concurrency.
  • Most databases use MVCC so readers don't block writers.
  • Prevent lost updates with atomic SQL, SELECT ... FOR UPDATE or optimistic version checks, and keep transactions short.