MODULE 04
TRANSACTIONS & CONCURRENCY
01
Unit 18 · 3 hrs

Transaction Processing

Intro, System Concepts, States, Logging

Definition

A transaction is a logical unit of work — one or more DB operations that must execute atomically and leave the DB in a consistent state.

read(X) — read data item X into memory  |  write(X) — write variable back to DB
Transaction State Machine
START ACTIVE PARTIALLY COMMITTED FAILED COMMITTED ABORTED TERMINATED all ops done error/conflict commit ok write fails rollback
State Descriptions
StateWhat's Happening
ActiveOperations executing normally
Partially CommittedLast op done; data still in memory buffer (not disk yet)
CommittedAll changes written permanently to disk ✅
FailedError / constraint violation / deadlock — can't continue
AbortedRolled back; DB restored to pre-transaction state
TerminatedTransaction lifecycle complete (committed or aborted)
System Log (Transaction Log) ▼ expand
Write-Ahead Logging (WAL): Log entry MUST be written to disk before actual data is modified. This ensures recovery is always possible.
Log EntryMeaning
[start_transaction, T]T has begun
[write_item, T, X, old, new]T wrote X; old→new value
[read_item, T, X]T read data item X
[commit, T]T committed successfully
[abort, T]T was aborted / rolled back
Exam Tip

WAL = write LOG first, then DB. "Partially Committed" ≠ "Committed" — data still in buffer, not disk.

02
Unit 19 · 1 hr

ACID Properties

A — Atomicity
All or Nothing. Either all ops commit or none do.
Enforced by: Recovery manager (undo log)
Bank transfer: crash after debit → debit is rolled back. No money lost.
C — Consistency
Valid State → Valid State. All constraints hold before and after.
Enforced by: App logic + constraint checking
Transfer ₹2000: Total money in system stays same (₹15K → ₹15K)
I — Isolation
No Interference. Each T runs as if it's the only one.
Enforced by: Concurrency control manager (locking)
T2 sees account balance BEFORE or AFTER T1's transfer — never mid-state
D — Durability
Committed = Permanent. Survives crashes.
Enforced by: WAL + disk storage before ACK
Ticket booked & server crashes → reservation still exists after recovery
Memory Trick

All or nothing  ·  Constraints hold  ·  Isolated from others  ·  Disk survives crash

03
Unit 20 · 2 hrs

Schedules, Serializability & Recoverability

Core Definitions
Schedule — an ordering of ops from multiple transactions where each T's ops keep their original order.
Serial Schedule — transactions run one after another (no interleaving). Always correct. Low performance.
Serializable Schedule — concurrent but equivalent in effect to some serial schedule. ✅ Correct AND faster.
Conflict Serializability
Two operations conflict if ALL three hold:
Different transactions
Same data item
At least one is WRITE
PairConflicts?
Read – Read❌ NO — safe
Read – Write✅ YES
Write – Read✅ YES
Write – Write✅ YES
Precedence Graph (Serializability Test)
  1. Create a node for each transaction
  2. Draw edge T1 → T2 if any op of T1 conflicts with a later op of T2
  3. If graph has NO cycle → Conflict Serializable ✅
  4. If graph has a cycle → NOT serializable ❌
T1 T2 T1→T2 only ✅ No cycle = Serializable
T1 T2 T1→T2 & T2→T1 ❌ Cycle = NOT Serializable
Schedule Types Hierarchy (most → least restrictive)
SERIAL
STRICT
No read/write until writer commits OR aborts
CASCADELESS
Read only AFTER writer commits (prevents cascading rollback)
RECOVERABLE
T2 commits AFTER T1 (if T2 read T1's data)
SERIALIZABLE
Schedule Types — Quick Reference
TypeRuleAvoids
SerialNo interleavingEverything — always correct
StrictNo R/W until writer commits/abortsDirty R/W, cascading rollback, easiest recovery
CascadelessRead only after writer commitsDirty reads, cascading rollback
RecoverableT2 commits after T1 (if T2 read T1's data)Committed dirty reads
SerializableEquivalent to some serial scheduleIncorrect concurrent results
Exam Tip

Every Serial schedule is Strict. Every Strict is Cascadeless. Every Cascadeless is Recoverable. But NOT vice versa!

Dirty Read = reading uncommitted data. Cascading Rollback = chain rollback of multiple Ts that read each other's dirty data.

04
Unit 21 · 1 hr

Transaction Support in SQL

SQL Transaction Commands
CommandWhat It Does
BEGIN / START TRANSACTIONMarks start of transaction
COMMITSave all changes permanently; release locks
ROLLBACKUndo ALL changes since BEGIN
SAVEPOINT nameSet named checkpoint for partial rollback
ROLLBACK TO SAVEPOINT nameUndo only to savepoint (keep rest)
RELEASE SAVEPOINT nameRemove a savepoint
Savepoint Example — Bank Transfer
START TRANSACTION;

UPDATE ACCOUNT SET Balance = Balance - 5000 WHERE Acc_No = 'A101';

SAVEPOINT after_debit;          -- checkpoint here

UPDATE ACCOUNT SET Balance = Balance + 5000 WHERE Acc_No = 'B202';

-- if credit fails:
ROLLBACK TO SAVEPOINT after_debit;   -- undo credit only

-- if all ok:
COMMIT;
Isolation Levels & Anomalies
Higher isolation = more correct, lower concurrency
Isolation LevelDirty ReadNon-Repeatable ReadPhantom Read
READ UNCOMMITTED✅ Possible✅ Possible✅ Possible
READ COMMITTED❌ Prevented✅ Possible✅ Possible
REPEATABLE READ❌ Prevented❌ Prevented✅ Possible
SERIALIZABLE❌ Prevented❌ Prevented❌ Prevented
Dirty Read
Read data written by an uncommitted transaction. Writer rolls back → you read invalid data.
Non-Repeatable Read
Same row read twice → different values because another T committed between your reads.
Phantom Read
Same query run twice → different set of rows (another T inserted/deleted matching rows).
Exam Tip

Dirty Read prevented at READ COMMITTED. Non-Repeatable prevented at REPEATABLE READ. Phantom prevented only at SERIALIZABLE.

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
05
Unit 22 · 3 hrs

Concurrency Control — 2PL

Concurrency Problems (without control)
Lost Update: T1 and T2 both read X (=1000). T1 writes 1500, T2 writes 1200. T1's update is lost. Should be 1700.
Dirty Read (Temporary Update): T1 writes X, then aborts. T2 already read the modified (dirty) value.
Incorrect Summary: T1 computes SUM while T2 transfers money mid-way. T1 reads inconsistent state.
Lock Types
S
Shared Lock
For READ. Multiple Ts can hold simultaneously.
X
Exclusive Lock
For WRITE. Only ONE T can hold at a time.
Lock Compatibility Matrix
Held ↓ / Requested →S (Read)X (Write)
S (Read)✓ Compatible✗ Block
X (Write)✗ Block✗ Block
Two-Phase Locking (2PL)
Guarantees conflict serializability. Transactions acquire and release locks in exactly two phases.
GROWING PHASE Acquire locks only Cannot release SHRINKING PHASE Release locks only Cannot acquire LOCK POINT Last lock acquired here
2PL Variants
VariantWhen ReleasedKey Property
Basic 2PLDuring execution (shrinking phase)Serializable; cascading rollbacks possible
Conservative 2PLAll locks acquired BEFORE startDeadlock-free; low concurrency
Strict 2PL ⭐X-locks held until commit/abortMost widely used; prevents dirty reads
Rigorous 2PLALL locks held until commit/abortStrictest; serializes by commit time
⭐ Strict 2PL = most used in practice (MySQL InnoDB default)
06
Unit 22 cont.

Deadlock & Timestamp Ordering

Deadlock — Definition
Deadlock = Two or more Ts each waiting for the other to release a lock. Circular wait — none can proceed.
1) Why They Wait (Lock-Level View)
T1 T2 Lock A on X Lock B on Y held by T1 held by T2 T1 requests B (wait) T2 requests A (wait)
2) Wait-for Graph Cycle + Resolution
T1 T2 T1 -> T2 T2 -> T1 Cycle present => DEADLOCK After resolution: abort victim (say T2) -> Lock B released -> T1 acquires B -> continues
Detection rule: In a wait-for graph, node = transaction and edge Ti->Tj means Ti is waiting for Tj. If a cycle exists, deadlock exists.
Deadlock Prevention Schemes
Both use timestamps. Older transaction = smaller TS = higher priority.
Wait-Die
If requester is older: it WAITS.
If requester is younger: it DIES (rollback + restart later).
Rule focus: younger requester gets rolled back.
Wound-Wait
If requester is older: it WOUNDS younger holder (abort holder).
If requester is younger: it WAITS.
Rule focus: older requester never waits behind younger.
Quick example: TS(T1)=5 (older), TS(T2)=20 (younger), and T2 holds a lock needed by T1.
Wait-Die: T1 waits.
Wound-Wait: T1 aborts T2 immediately.
SchemeOlder requests younger's lockYounger requests older's lock
Wait-DieWAITDIE
Wound-WaitWOUND (abort younger)WAIT
Memory trick: Wait-Die = requester may die. Wound-Wait = holder may be wounded.
Timestamp-Based Concurrency Control
Alternative to locking. Each T gets unique timestamp TS(T) at start. Conflicts resolved by comparing timestamps — no deadlocks!
Each data item X tracks:
RTS(X)
Latest TS that READ X
WTS(X)
Latest TS that WROTE X
Thomas's Write Rule: If T tries to write X but WTS(X) > TS(T), the write is obsolete — safely IGNORE it instead of rolling back. Improves performance.
2PL vs Timestamp Ordering
Aspect2PL (Locking)Timestamp Ordering
MechanismAcquire/release locksTS comparison on each op
DeadlockPossible ❌Impossible ✅
RollbacksLess frequentMore frequent ❌
SerializabilityGuaranteed ✅Guaranteed ✅
OverheadLock managementTimestamp management
FC
Study Mode

Flashcards

Tap to flip • All key exam concepts

Quick Reference

Master Cheatsheet

Everything in One Table
TopicKey Formula / Rule
ACID-AAll or Nothing → undo log
ACID-CValid state → Valid state → constraints
ACID-INo interference → locking
ACID-DCommitted = permanent → WAL + disk
ConflictDiff T + Same item + ≥1 Write = CONFLICT
Serializable?Precedence graph — NO cycle = YES
WALLog BEFORE data write
S lockRead; many can share
X lockWrite; exclusive — no sharing
2PLGrowing phase (acquire) → Lock Point → Shrinking phase (release)
Strict 2PLHold X-locks until commit/abort (most common)
Wait-DieOlder waits; Younger dies
Wound-WaitOlder wounds younger; Younger waits
Deadlock detectWait-for graph → cycle → abort victim
Thomas Write RuleObsolete write → IGNORE (don't abort)
Dirty ReadPrevented at READ COMMITTED+
Non-RepeatablePrevented at REPEATABLE READ+
Phantom ReadPrevented at SERIALIZABLE only
G
Quick Terms

Glossary of Shorthands

Fast meaning lookup for symbols and abbreviations used in this module.

Common Symbols
Short FormMeaningExample / Context
TTransactionT1, T2 are two concurrent transactions
TS(T)Timestamp of transaction TSmaller TS means older transaction
RTS(X)Read Timestamp of item XLatest TS of any transaction that read X
WTS(X)Write Timestamp of item XLatest TS of any transaction that wrote X
R(X)Read operation on item XRead item X from DB/buffer
W(X)Write operation on item XWrite updated value of X to DB
S-lockShared lock (read lock)Multiple transactions may hold it together
X-lockExclusive lock (write lock)Only one transaction can hold it
2PLTwo-Phase LockingGrowing phase then shrinking phase
WALWrite-Ahead LoggingWrite log record before writing data item
WFGWait-For GraphCycle in WFG indicates deadlock
ACIDAtomicity, Consistency, Isolation, DurabilityCore transaction correctness properties
DBMS / RDBMSDatabase Management System / Relational DBMSSoftware that stores and manages structured data
Memory Tip

T = transaction, TS = transaction age/order, RTS/WTS = latest read/write time on a data item.