Skip to main content
Albero Academy

Transactions, Isolation & Locking

Go beyond COMMIT/ROLLBACK — ACID guarantees, isolation levels, the anomalies they prevent, and how to avoid deadlocks.

Chapter 12MySQL16 min readBeginner friendly
  • #MySQL
  • #Transactions
  • #Concurrency

Chapter 4 introduced transactions as all-or-nothing. This chapter is what happens when many transactions run at once — the guarantees MySQL gives you, the ways concurrent access can go wrong, and the dials you turn to trade safety for speed.

ACID — the four guarantees

PropertyMeans
AtomicityAll statements commit together, or none do
ConsistencyA transaction moves the DB between valid states
IsolationConcurrent transactions don't corrupt each other
DurabilityOnce committed, it survives a crash

InnoDB (MySQL's default engine) is fully ACID; the older MyISAM engine is not — another reason to use InnoDB.

Concurrency anomalies

Without isolation, simultaneous transactions can see wrong data:

  • Dirty read — reading another transaction's uncommitted (possibly-rolled-back) change.
  • Non-repeatable read — a row you re-read has changed mid-transaction.
  • Phantom read — a re-run query returns new rows that appeared meanwhile.

Isolation levels

Higher levels prevent more anomalies but reduce concurrency. MySQL's InnoDB default is REPEATABLE READ:

LevelPrevents
READ UNCOMMITTEDnothing (allows dirty reads)
READ COMMITTEDdirty reads
REPEATABLE READdirty + non-repeatable reads (MySQL default)
SERIALIZABLEeverything (as if run one at a time)
setting the level
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
START TRANSACTION;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE; -- lock the row
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
COMMIT;

Locking & deadlocks

Practice

In two client sessions, start transactions and observe a lock: one SELECT … FOR UPDATE blocks the other until commit. Try READ COMMITTED vs REPEATABLE READ and watch whether a re-read sees a committed change. Describe one way to avoid a deadlock in your own code.

Key takeaways

  1. 01ACID = Atomicity, Consistency, Isolation, Durability; InnoDB provides all four.
  2. 02Concurrency anomalies: dirty reads, non-repeatable reads, phantom reads.
  3. 03Isolation levels trade safety for concurrency; MySQL InnoDB defaults to REPEATABLE READ.
  4. 04SELECT … FOR UPDATE locks rows so another transaction must wait.
  5. 05Deadlocks are detected and one transaction is rolled back — keep transactions short and lock in a consistent order.