Database Management SystemUnit 56 min read
Transactions, Locks, Isolation, Deadlocks & Recovery
Unit 5 of Database Management System explores how databases maintain data integrity during concurrent operations, covering ACID properties, transaction states, locking mechanisms, concurrency control, deadlock handling, and recovery techniques with real-world examples from banking, e-commerce, and telecom systems.
What is a Transaction?
A transaction is a sequence of one or more database operations (SQL queries) that must be executed atomically—either all succeed or none do. Think of it as a single logical unit of work, like transferring money between two bank accounts or placing an order on Daraz.
ACID Properties
Transactions follow four key properties:
| Property | Definition | Example |
|---|---|---|
| Atomicity | All operations in a transaction succeed or none do. | If a bank transfer fails midway, both accounts revert to their original state. |
| Consistency | A transaction brings the database from one valid state to another. | A Daraz order must not leave inventory inconsistent. |
| Isolation | Concurrent transactions do not interfere with each other. | Two users booking the same Pathao ride should not see conflicting seat availability. |
| Durability | Once committed, changes persist even after system failures. | A committed Ncell recharge must not disappear after a server crash. |
stateDiagram-v2
[*] --> Active: Transaction starts
Active --> Partially_committed: Last operation executed
Partially_committed --> Committed: Commit succeeds
Partially_committed --> Aborted: Rollback triggered
Committed --> [*]
Aborted --> [*]In the Real World
- Khalti Payments: When you transfer money via Khalti, the system ensures atomicity—either the sender’s balance decreases and the receiver’s increases, or neither changes. If the transfer fails midway, both accounts remain unchanged.
- Ncell Top-Up: A top-up transaction must be durable. Even if the server crashes after processing your request, the minutes should still be added to your account upon recovery.
- Daraz Order Processing: When you place an order, Daraz locks the inventory items (locking mechanism) to prevent overselling while processing payment. If payment fails, the lock is released (rollback).
Transaction States and Life Cycle
A transaction passes through several states:
- Active: Executing SQL operations.
- Partially Committed: Last operation executed, but commit not yet written to disk.
- Committed: Changes are permanent.
- Failed: Transaction cannot proceed (e.g., deadlock).
- Aborted: Rollback triggered; changes discarded.
sequenceDiagram
participant User
participant DBMS
User->>DBMS: BEGIN TRANSACTION
User->>DBMS: UPDATE account_balance SET balance = balance - 1000 WHERE user_id = 1
User->>DBMS: UPDATE account_balance SET balance = balance + 1000 WHERE user_id = 2
User->>DBMS: COMMIT
DBMS-->>User: Success (or Rollback on failure)Concurrency Control
Concurrency control manages simultaneous transactions to ensure isolation and consistency. Without it, two users might read and modify the same data incorrectly (e.g., double-booking a Pathao ride).
Locking Mechanisms
Locks prevent conflicting operations on the same data:
| Lock Type | Description | Example |
|---|---|---|
| Shared (Read) Lock | Allows multiple readers but no writers. | Multiple users checking their Ncell balance simultaneously. |
| Exclusive (Write) Lock | Granted only to one transaction; blocks all others. | A user updating their Khalti profile picture. |
| Intent Locks | Indicates intention to acquire a lock (e.g., IX for shared, SIX for exclusive). |
Used in hierarchical locking (e.g., locking a city before locking a district). |
graph LR
A["Transaction T1: READS Account A"] -->|"Acquires Shared Lock"| B["Account A"]
C["Transaction T2: WRITES Account A"] -->|"Waits for Exclusive Lock"| B
D["Transaction T3: READS Account B"] -->|"Acquires Shared Lock"| E["Account B"]Deadlocks
A deadlock occurs when two or more transactions wait indefinitely for locks held by each other. Example:
- T1 locks
Account_Xand waits forAccount_Y. - T2 locks
Account_Yand waits forAccount_X.
Deadlock Prevention Strategies
| Strategy | Description | Example |
|---|---|---|
| Lock Timeout | Release locks if not acquired within a time limit. | Daraz releases inventory locks if payment processing takes too long. |
| Wait-Die Scheme | Younger transaction waits; older one dies (rolls back). | Used in NEPSE trading to resolve conflicts in stock orders. |
| Deadlock Detection | Periodically check for cycles in the wait-for graph. | Banks detect deadlocks in loan processing systems. |
graph TD
A["T1 holds Lock X, waits for Lock Y"] --> B["T2 holds Lock Y, waits for Lock X"]Recovery Techniques
If a transaction fails or the system crashes, recovery mechanisms restore consistency:
Deferred Update (Write-Ahead Logging):
- Changes are written to a log before the database.
- Example: Ncell writes recharge records to a log before updating the user’s balance.
Immediate Update:
- Changes are applied to the database immediately, but a redo log ensures durability.
- Example: Khalti commits payment updates to the database and logs them for recovery.
Checkpointing:
- Periodically saves the database state to disk.
- Example: Banks perform checkpoints every hour to minimize data loss during crashes.
sequenceDiagram
participant Transaction
participant Log
participant Database
Transaction->>Log: Write operation to log
Transaction->>Database: Apply changes
Database-->>Log: Acknowledge
Log->>Database: Recover on crashExam Tip
- ACID Properties: Always explain atomicity (all-or-nothing) and isolation (no interference) with examples like bank transfers or e-commerce orders.
- Locking: Differentiate between shared (read) and exclusive (write) locks. Use real scenarios (e.g., Pathao ride booking).
- Deadlocks: Draw a wait-for graph and explain timeout or rollback as solutions.
- Recovery: Compare deferred update (log-first) vs. immediate update (database-first) with examples like Khalti or Ncell.
- SQL Keywords: Know
BEGIN TRANSACTION,COMMIT,ROLLBACK, andSAVEPOINTfor practical questions.
A graph illustrating two transactions waiting for each other’s locks. (Image: Kkaaii, CC BY-SA 4.0, via Wikimedia Commons)
Based on the TU BIM syllabus for Database Management System (IT220), unit 5.
Discussion
Loading…