Transactions & Concurrency

Transactions & Concurrency in MySQL: In financial, e-commerce, and healthcare systems, individual operations frequently require multiple sequential SQL…

In financial, e-commerce, and healthcare systems, individual operations frequently require multiple sequential SQL commands. If money is deducted from Account A, but the server crashes before it is added to Account B, money is literally destroyed.

A Transaction groups multiple SQL statements into a single, indivisible logical unit of work that is guaranteed to either succeed completely or fail completely with zero side-effects.


1. The ACID Guarantees Explained

All relational transactions are governed by the four ACID properties:

PropertyMeaningHow MySQL InnoDB Enforces It
Atomicity"All or nothing." If query 4 of 5 fails, the first 3 queries are completely undone.Undo Logs: Records inverse operations to cleanly rollback uncommitted changes.
ConsistencyThe database transitions from one valid state to another without violating schema constraints.Schema Constraints: Engine rejects changes violating Foreign Keys, Unique Keys, or Checks.
IsolationConcurrent transactions executing in parallel cannot see each other's intermediate state.MVCC & Locks: Multi-Version Concurrency Control with row-level locks and snapshots.
DurabilityOnce committed, changes survive even catastrophic sudden power loss.Redo Logs (WAL): Flushes write-ahead logs to physical disk before updating data pages.

2. Managing Transactions in SQL

MySQL controls transactions using four core commands:

-- 1. Begin the atomic transaction block
START TRANSACTION;

-- Step A: Deduct $500 from Alice's account
UPDATE bank_accounts 
SET balance = balance - 500.00 
WHERE account_id = 101 AND balance >= 500.00;

-- Step B: Credit $500 to Bob's account
UPDATE bank_accounts 
SET balance = balance + 500.00 
WHERE account_id = 202;

-- Step C: Record audit ledger entry
INSERT INTO transfer_ledger (from_acc, to_acc, amount) 
VALUES (101, 202, 500.00);

-- 2. If everything succeeded, permanently write changes to disk:
COMMIT;

-- (If any error occurred during the steps above, run ROLLBACK instead:)
-- ROLLBACK;

Savepoints: Partial Rollbacks

Savepoints allow you to rollback a portion of a complex transaction without discarding the entire session:

START TRANSACTION;
INSERT INTO orders (id, customer_id) VALUES (1, 100);
SAVEPOINT order_created;

-- Try applying promotional voucher
INSERT INTO order_vouchers (order_id, code) VALUES (1, 'EXPIRED_CODE');
-- Voucher failed? Roll back to savepoint while keeping the order!
ROLLBACK TO SAVEPOINT order_created;

COMMIT;

3. Transaction Isolation Levels & Concurrency Phenomena

When hundreds of database threads run transactions concurrently, subtle isolation issues can emerge:

Concurrency Phenomena:

  • Dirty Read: Transaction B reads uncommitted data written by Transaction A (which A might later rollback!).
  • Non-Repeatable Read: Transaction A reads a row, Transaction B updates that row and commits; Transaction A re-reads the row and sees changed data.
  • Phantom Read: Transaction A queries a range (WHERE age > 30), Transaction B inserts a new row matching that range and commits; Transaction A re-runs the range query and sees an extra "phantom" row.

The Four ANSI SQL Isolation Levels in MySQL:

Isolation LevelDirty Reads?Non-Repeatable Reads?Phantom Reads?Performance
READ UNCOMMITTEDPermittedPermittedPermittedHighest
READ COMMITTEDPreventedPermittedPermittedHigh
REPEATABLE READ (MySQL Default)PreventedPreventedPrevented (via Next-Key Locks)Balanced
SERIALIZABLEPreventedPreventedPreventedLowest (Serial locks)
-- Check current session isolation level
SELECT @@transaction_isolation;

-- Change isolation level for the next transaction
SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

4. Concurrency, Locks & Deadlocks

InnoDB utilizes sophisticated row-level locking:

Explicit Row Locking:

-- Exclusive Lock (FOR UPDATE): Prevents others from reading (with lock) or modifying these rows
SELECT * FROM inventory WHERE item_id = 42 FOR UPDATE;

-- Shared Lock (FOR SHARE): Allows others to read, but blocks them from modifying
SELECT * FROM users WHERE id = 10 FOR SHARE;

Deadlocks: What They Are & How to Handle Them

A Deadlock occurs when Transaction 1 holds a lock on Row A and requests Row B, while Transaction 2 holds a lock on Row B and requests Row A. Neither can proceed:

Tx 1: Holds Lock on Row A ──(Waiting for)──► Needs Lock on Row B
                                                  ▲
                                                  │ (Held by)
Tx 2: Needs Lock on Row A ◄──(Waiting for)── Holds Lock on Row B

How MySQL Handles Deadlocks: InnoDB's background thread automatically detects lock wait cycles, selects the transaction that has modified fewer rows (the cheaper rollback), and terminates it with error: ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction

Application Best Practices:

  1. Access tables and rows in consistent order across all queries in your application (e.g. always lock user before locking order).
  2. Keep transactions short—never perform slow third-party API calls or send emails inside an open database transaction!
  3. Implement automatic retry logic with exponential backoff in application code when catching deadlock exceptions.