πŸ’Ύ Database Transactions and Concurrency

πŸ’‘ What is a Transaction?

A transaction is a set of operations that perform a single logical task in a database.

πŸ” Real-World Example: Banking Transfer

Imagine you're using a banking app to transfer β‚Ή1000 from Account A to Account B.

This task involves:

1. BEGIN TRANSACTION
2. Deduct β‚Ή1000 from Account A
3. Add β‚Ή1000 to Account B
4. COMMIT TRANSACTION
        

This is one transaction. If any step fails, the whole operation should fail.

Banking transactions require all operations to succeed or fail together

🧱 What is an Operation in a Transaction?

In a transaction, an operation is a single step like reading, writing, updating, or committing data in the database.

Together, multiple operations complete the logical task.

βœ… Common Types of Operations

  • BEGIN TRANSACTION – Start the transaction
  • READ(X) – Read value of X
  • WRITE(X) – Update value of X
  • COMMIT – Save changes
  • ABORT – Cancel and rollback

πŸ“˜ Example: Transfer β‚Ή1000 from A to B (Step-by-step)

Transaction T1:

1. BEGIN TRANSACTION
2. READ(A)           -- Get balance of Account A
3. A = A - 1000      -- Deduct β‚Ή1000
4. WRITE(A)          -- Save new balance of A
5. READ(B)           -- Get balance of Account B
6. B = B + 1000      -- Add β‚Ή1000
7. WRITE(B)          -- Save new balance of B
8. COMMIT            -- Finalize the transaction
        

Each READ and WRITE is an operation. Together, they make one complete transaction.

βœ… ACID Properties (Very Important for Interviews)

ACID properties are a set of rules that ensure database transactions are processed reliably, even in case of failures or concurrent access.

πŸ”„ Atomicity

All operations in a transaction are treated as a single unit – either all succeed or none at all.

πŸ’‘ Real-World Example:

When transferring β‚Ή1000 from Account A to B, if deduction from A fails, the amount must not be added to B.

BEGIN TRANSACTION
   Deduct β‚Ή1000 from A
   Add β‚Ή1000 to B
COMMIT
-- If any step fails, rollback both
                

βš–οΈ Consistency

The database must always remain in a valid state before and after the transaction.

πŸ’‘ Real-World Example:

Total money in the system should be the same before and after a transfer.

Before Transaction:
   A = β‚Ή5000, B = β‚Ή3000 β†’ Total = β‚Ή8000

After Transaction (β‚Ή1000 A to B):
   A = β‚Ή4000, B = β‚Ή4000 β†’ Total = β‚Ή8000 βœ…
                

πŸ”’ Isolation

Each transaction runs independently. Partial results of one transaction are not visible to others.

πŸ’‘ Real-World Example:

Two users transferring money simultaneously won’t interfere with each other’s balances.

User 1: Transfer β‚Ή500 A β†’ B
User 2: Transfer β‚Ή1000 C β†’ D

-- Isolation ensures these run safely in parallel without data conflict
                

πŸ’Ύ Durability

Once a transaction is committed, the changes are permanent – even if the system crashes.

πŸ’‘ Real-World Example:

If a user completes a payment and the app crashes, the payment still goes through.

COMMIT

-- Data saved in log or backup
-- After power failure: data is restored from logs βœ…
                

ACID properties ensure database reliability, correctness, and integrity during all transactions.

🀝 Concurrent Execution

When multiple transactions run at the same time, it's called concurrent execution.

Why Concurrency? To improve performance and user experience.

🎬 Movie Ticket Booking Example

Imagine many users are booking movie tickets online at the same time. The system processes many transactions in parallel, but must ensure that no one gets the same seat.

Transaction 1: User A books Seat 5A
Transaction 2: User B books Seat 7C  
Transaction 3: User C books Seat 5A ← Should be blocked!

Multiple users booking tickets simultaneously - perfect example of concurrency

πŸ”„ Transaction States

In a DBMS, a transaction moves through several states to ensure safe and correct execution. The diagram below shows the complete life cycle:

Transaction States in DBMS

Visual flow of transaction states including commit, abort, and rollback.

🧭 Explanation of Each State

State Meaning Transition Example
Active Transaction is currently executing (doing read/write) β†’ Partially Committed (if successful) or β†’ Failed (if error) User clicks "Recharge β‚Ή100"
Partially Committed Final step executed; about to save changes β†’ Committed (if successful) or β†’ Failed (if error) Recharge sent to operator, waiting for response
Committed All changes made permanent in the database β†’ Terminated "Recharge Successful" message shown
Failed Error occurred during transaction β†’ Aborted Network failure or recharge error
Aborted Transaction rolled back (undone) β†’ Terminated Recharge failed and money returned
Terminated Transaction completed successfully or aborted safely End of transaction Recharge is either complete or failed, system ready for new transaction

πŸ“˜ Real-World Example in <pre> format

Recharge Transaction Flow

1. BEGIN TRANSACTION
2. READ(wallet_balance)
3. wallet_balance = wallet_balance - β‚Ή100
4. WRITE(wallet_balance)
5. Send recharge request

If success:
6. COMMIT β†’ Move to COMMITTED β†’ TERMINATED

If failure:
6. FAIL β†’ Move to FAILED β†’ ROLLBACK β†’ ABORTED β†’ TERMINATED
    

πŸ“… What is a Schedule?

A Schedule is the order in which operations (like read, write) from multiple transactions are executed.

Types of Schedules:

πŸ”„ Serial Schedule
T1: read(A) β†’ write(A) β†’ commit
T2: read(B) β†’ write(B) β†’ commit

One transaction at a time

πŸ”€ Concurrent Schedule (parallel schedules)
T1: read(A)
T2: read(B)
T1: write(A)
T2: write(B)

Multiple transactions interleaved

Database scheduling manages the order of transaction execution

⚠️ Problems in Concurrency

Jab multiple transactions ek hi samay par execute karte hain bina proper control ke, to data galat ho sakta hai. Yeh problem ko kehte hain: Concurrency Issues.

πŸ’₯ Dirty Read (Uncommitted Read)

Definition: Jab ek transaction (T2) kisi doosre transaction (T1) ke uncommitted data ko read kar leta hai, to agar T1 fail ho jaye, T2 galat data ke basis pe kaam kar chuka hota hai.

πŸ›οΈ Real-World Example: Aapka friend T1 aapke account se β‚Ή500 nikalta hai, aur aap T2 me balance check karke β‚Ή1500 dekh lete ho. Par T1 fail ho jata hai aur rollback ho jata hai. Aapne jo balance dekha wo galat tha.

Dirty Read Problem Table

Image: Timeline of Dirty Read Problem between T1 and T2

🧠 Step-by-Step Explanation:
  • t1–t3 (T1): T1 reads A, deducts β‚Ή500, and writes new value. But it has not committed yet.
  • t4–t5 (T2): T2 reads A’s new (uncommitted) value and adds β‚Ή100. This is the dirty read.
  • t6 (T1): T1 fails due to some issue.
  • t7 (T1): T1 rolls back. That means its update is cancelled.
  • t7 (T2): But T2 already used that uncommitted value and wrote it. Now the database is inconsistent.
πŸ”΄ T2 ne galat data use kar liya jo kabhi commit nahi hua. Isko hi Dirty Read kehte hain.

πŸ“ Lost Update

Definition: Jab do transactions same data ko read karte hain aur update karte hain bina synchronization ke, to ek transaction ka update dusre ke update se chhup jata hai. Isse kehte hain Lost Update.

πŸ›οΈ Real-World Example: Alice aur Bob ek product ki quantity update kar rahe hain. Dono ne same original value (7) read ki. Par Bob ne jab last me commit kiya, to Alice ka update (quantity = 6) chhup gaya aur final value ban gayi quantity = 10.

Lost Update Example - Alice and Bob

Image: Lost Update between Alice and Bob

🧠 Step-by-Step Explanation:
  • Step 1: Alice transaction start karti hai aur product ki quantity read karti hai (value: 7).
  • Step 2: Bob bhi transaction start karta hai aur same quantity read karta hai (value: 7).
  • Step 3: Alice quantity ko 6 set karta hai aur commit karta hai.
  • Step 4: Bob quantity ko 10 set karta hai (based on old value 7) aur commit karta hai.
  • Result: Alice ka update (6) overwrite ho gaya. Final quantity = 10.
πŸ”΄ Bob ne Alice ke update ko ignore kar diya β€” yeh hota hai Lost Update Problem.

πŸ”„ Read-Write Conflict (Unrepeatable Write)

Definition: Jab ek transaction data ko read karke uspar operation karta hai, aur beech me doosra transaction usi data ko overwrite kar deta hai, to pehle transaction ka update dusre ko ignore kar deta hai.

πŸ›οΈ Real-World Example: Do log ek hi account balance X par kaam kar rahe hain. A ne X ko +15 kiya, par write nahi kiya tha. B ne X ko read kiya, -25 kiya, aur write bhi kar diya. Jab A ne apna write kiya, to B ka change chhup gaya.

Read Write Conflict Example

Image: Read-Write Conflict – Final value of X becomes 115, B’s update is lost.

🧠 Step-by-Step Explanation:
  • Step 1: Transaction A reads X = 100 and prepares to update X = 115
  • Step 2: Before A writes, Transaction B reads X = 100, subtracts 25 β†’ X = 75, and writes it
  • Step 3: Transaction A now writes its old planned value: X = 115
  • Final Result: B’s change (X = 75) is overwritten β€” data conflict occurs
πŸ”΄ B ne X = 75 likha tha, lekin A ne bina B ke write ka dhyan rakhe apna X = 115 overwrite kar diya. Isse kehte hain Read-Write Conflict ya Lost Effect of Write.

πŸ” Recoverable vs Irrecoverable Schedule

Jab multiple transactions ek hi data ke sath kaam karte hain, to hume dekhna padta hai ki koi transaction galat data pe commit to nahi kar raha. Iske liye schedule ka type define kiya jata hai.

βœ… Recoverable Schedule

Definition: Ek transaction T2 tabhi commit kare jab usne jo data read kiya hai, wo T1 pehle se commit kar chuka ho.

πŸ›οΈ Real-World Example: T1 updates salary and commits, fir T2 reads that salary and commits. Agar T1 fail hota to T2 ne kuch commit nahi kiya hota β€” so safe.

  • T1: WRITE salary = β‚Ή80,000 β†’ COMMIT
  • T2: READ salary β†’ COMMIT
βœ… Safe Schedule: T2 waits until T1 commits. Rollback possible.

❌ Irrecoverable Schedule

Definition: Ek transaction T2 read kar leta hai uncommitted data (dirty read), aur commit bhi kar deta hai. Agar T1 fail hua to rollback impossible ho jata hai.

πŸ›οΈ Real-World Example: Loan approve hua salary β‚Ή80,000 ke basis pe, par later pata chala T1 ne wo salary rollback ki thi.

  • T1: WRITE salary = β‚Ή80,000
  • T2: READ salary β†’ COMMIT
  • T1: ROLLBACK
❌ Dangerous Schedule: T2 committed on uncommitted data of T1. Now rollback is impossible.

πŸ”„ Cascading vs Cascadeless Schedule

When multiple transactions interact with shared data, their commit order and read/write timing decides if the system can recover properly or not.

βœ… Cascadeless Schedule

Definition: Ek transaction tabhi kisi aur ka data read karta hai jab wo pehle commit ho chuka ho.

πŸ“Œ Advantage: No cascading rollback, safe, and consistent.

Cascadeless Schedule

All transactions (T2, T3) only read after T1 commits β€” No cascading rollback possible.

  • T1: Reads/Writes A β†’ Commits
  • T2: Reads A (after T1 commits), Writes A β†’ Commits
  • T3: Reads A (after T2 commits), Writes A β†’ Commits
βœ… Safe: Even if T1 fails, T2 and T3 would never read its uncommitted data.

⚠️ Cascading Schedule (Recoverable)

Definition: Jab ek transaction dusre ka uncommitted data read karta hai, to agar pehla transaction fail ho gaya, to baaki sab rollback karne padte hain.

πŸ“Œ Problem: Chain of rollbacks = cascading abort

Cascading Schedule

T2, T3, T4 all read A before T1 commits β€” If T1 fails, they must rollback.

  • T1: Reads/Writes A, but fails
  • T2: Reads A (before T1 commits), Writes A β†’ Must rollback
  • T3: Reads A (before T2 commits), Writes A β†’ Must rollback
  • T4: Reads A (before T3 commits), Writes A β†’ Must rollback
❌ Risky: Failure of T1 causes T2, T3, T4 to rollback β€” cascading failure.

πŸ” Deadlock in Concurrency

A deadlock occurs when two or more transactions wait indefinitely for each other to release resources.

πŸ”„ Deadlock Example

Transaction 1: 
- Locks Account A
- Waits for Account B

Transaction 2:
- Locks Account B  
- Waits for Account A

Result: Both transactions wait forever!
Deadlock Prevention: Use timeout mechanisms, resource ordering, or deadlock detection algorithms to prevent and resolve deadlocks.

🧠 Real-World Summary

πŸ’³ UPI Payment

Perfect example of a Transaction with ACID properties

πŸ”„ All-or-Nothing

Demonstrates Atomicity - complete success or complete failure

🎬 Movie Booking

Shows Isolation - two users can't book same seat

πŸ’Ύ Crash Recovery

Illustrates Durability - refund processed even after crash

πŸ‘οΈ Wrong Balance

Example of Dirty Read - seeing incomplete transaction

πŸ“ Profile Update

Shows Lost Update - two edits overwrite each other

🎯 Interview Tips

  • Always explain ACID with real examples - banking transfers, e-commerce orders
  • Know the difference between serial and concurrent schedules
  • Understand common concurrency problems - dirty read, lost update, phantom read
  • Explain deadlock with practical scenarios - two users trying to transfer money
  • Practice drawing transaction state diagrams

πŸ”— Quick Reference

Concept Key Point Real-World Example
Transaction Logical unit of work Bank transfer, online purchase
Atomicity All or nothing Payment succeeds completely or fails completely
Consistency Database remains valid Account balances always correct
Isolation Transactions don't interfere Multiple users can't book same seat
Durability Changes persist Transaction survives system crash
Concurrency Multiple transactions simultaneously Many users using ATM at same time
Deadlock Circular wait condition Two users waiting for each other's resources