Transaction Management
Database Management Systems • UG Study Notes
Visual notes • Worked examples • Question bank with answers
www.edukosal.com
Table of Contents (Book Plan)
- Chapter 1 – Transactions, ACID Properties and Schedules
- Chapter 2 – Concurrent Execution, Serializability and Recoverability
- Chapter 3 – Lock-Based Concurrency Control, Two-Phase Locking (2PL), Lock Management and Performance of Locking
- Chapter 4 – Dealing with Deadlocks
- Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery; Final Revision, References
Inside Chapter 1: 1.1 Introduction • 1.2 Transaction and its operations • 1.3 Transaction states • 1.4 ACID properties • 1.5 Real-life examples • 1.6 Transactions and schedules • 1.7 Applications, advantages, limitations • Important points • Question bank • Practice test • Summary
Transactions, ACID Properties and Schedules
1.1 Introduction
Whenever you pay using UPI, book a train ticket or withdraw cash from an ATM, several database changes must happen together. Money must leave one account and reach another. A seat must be marked booked and a ticket must be issued. If only half of these steps succeed, the data becomes wrong and people lose money or seats.
A DBMS solves this problem with the idea of a transaction. It also lets thousands of users work at the same time without disturbing one another, and it protects completed work even if the system crashes. These guarantees are the foundation of banking, railway, e-commerce and every other serious database application. That is why Transaction Management is a core topic in every university DBMS course.
1.2 Meaning, Definition and Operations of a Transaction
Basic operations
| Operation | Meaning |
|---|---|
READ(X) | Copy data item X from the database (disk) into a program variable in main memory. |
WRITE(X) | Write the program variable back to X in the database. |
COMMIT | Declare the transaction successful; all its changes must become permanent. |
ABORT / ROLLBACK | Declare the transaction unsuccessful; all its changes must be undone. |
Note: the DBMS only “sees” reads and writes. Calculations such as A = A - 500 happen in the program’s memory and are invisible to the DBMS. Because of this, the DBMS cannot know what a transaction means; it only controls the order of reads and writes.
Working process: funds transfer transaction
1.3 Transaction States
A transaction passes through well-defined states from its start to its end. The DBMS tracks the state to decide whether to keep or undo its work.
| State | Description |
|---|---|
| Active | Initial state. The transaction is executing its read/write operations. |
| Partially committed | The final statement has executed, but the changes may still sit in memory buffers and are not yet guaranteed safe on disk. |
| Committed | Successful completion. The changes are permanent (recorded safely in the log) and will survive a crash. |
| Failed | Normal execution cannot continue because of an error, a crash, or a decision of the DBMS. |
| Aborted | The transaction has been rolled back and the database is restored to its state before the transaction began. The transaction can then be restarted (if the failure was not a logical error) or killed. |
1.4 ACID Properties
To keep data correct, every DBMS transaction must satisfy four properties, remembered by the word ACID.
A – Atomicity
If a transaction fails midway, the DBMS must undo the partial changes already made. The DBMS keeps a log of every write so that it can restore old values. Atomicity is the responsibility of the recovery manager.
Example: Debiting A and crediting B. If the system crashes after debiting A, atomicity demands that A’s debit is undone.
C – Consistency
Consistency is mainly the user’s (application programmer’s) responsibility, supported by the DBMS through integrity constraints. For example, in a transfer, the total balance A + B must stay the same before and after. The DBMS can enforce declared constraints such as balance >= 0 but cannot know your unwritten business rules.
I – Isolation
Isolation is ensured by the concurrency control component (for example, the lock manager). The usual meaning is that the final result must equal the result of some serial execution of the transactions. This idea, called serializability, is studied in Chapter 2. Note that the DBMS does not promise which serial order is used.
D – Durability
The DBMS records the changes in a log on stable storage before declaring the commit successful (this is the write-ahead logging idea, introduced in Chapter 5). After a crash, the recovery manager redoes committed work that had not yet reached the disk.
Summary table
| Property | Question it answers | Threatened by | Ensured by |
|---|---|---|---|
| Atomicity | Did all steps happen or none? | Failure/abort midway | Log + undo (recovery manager) |
| Consistency | Are all rules still satisfied? | Faulty transaction logic, rule violations | Programmer, integrity constraints |
| Isolation | Do concurrent users disturb each other? | Interleaved execution | Locking / concurrency control |
| Durability | Will committed data survive a crash? | Crash before data reaches disk | Log + redo (recovery manager) |
1.5 Real-Life Examples
| Level | Situation | How the concept works |
|---|---|---|
| Everyday | Buying tea at a stall: you hand over ₹20 and the seller hands over tea. | Either both exchanges happen or neither (atomicity). If the seller has no tea, you take your money back (rollback). |
| Industry | E-commerce order: reduce stock, create order record, charge payment. | All three updates form one transaction. If payment fails, stock reduction is undone. Two buyers of the last item are kept apart by isolation. |
| Indian | UPI payment from your bank account to a shopkeeper’s account; IRCTC Tatkal ticket booking. | Debit and credit are atomic. Once “payment successful” appears, it is durable even if servers restart. For IRCTC, isolation stops two users from getting the same last seat. |
Example 1: Basic Example
Problem / Situation: Account A has ₹5,000 and account B has ₹3,000. Transaction T transfers ₹500 from A to B.Explanation: T reads both balances, changes them in memory and writes them back.
Step-by-step solution:
- READ(A): A = 5000
- A = A − 500 = 4500
- WRITE(A)
- READ(B): B = 3000
- B = B + 500 = 3500
- WRITE(B)
- COMMIT
Example 2: Real-Life Application
Real-world situation: A cinema booking site shows one seat left. Two users click “Book” at the same moment.How the concept is applied: Each booking is a transaction. Isolation makes the DBMS process them as if one came after the other, so only the first succeeds; the second sees the seat as taken. Atomicity makes sure that seat marking, payment and ticket creation succeed together.
Learning outcome: Isolation prevents double booking, atomicity prevents half-finished bookings.
Example 3: Practical / Case Study
Background: A bank’s server crashes at the exact moment it is processing a customer’s transfer of ₹10,000.Problem: After restart, the customer’s account shows ₹10,000 less, but the beneficiary has not received it.
Application of the concept: The recovery manager reads the log. It finds that the transfer transaction has no commit record, so it is treated as a failed transaction and its debit is undone (atomicity). Another transfer that had committed just before the crash, but whose data was still only in memory, is redone from the log (durability).
Result: Both accounts are in a correct state after recovery.
Conclusion: The log makes atomicity and durability possible together.
1.6 Transactions and Schedules
A real DBMS runs many transactions at once. To study their behaviour we use the idea of a schedule.
Notation
Ri(X) = transaction Ti reads X. Wi(X) = Ti writes X. Commiti and Aborti end Ti.
Types of schedules
| Type | Meaning | Example |
|---|---|---|
| Serial schedule | Actions of different transactions are not interleaved; each transaction runs completely before the next starts. | R1(A) W1(A) C1 R2(A) W2(A) C2 |
| Non-serial (interleaved / concurrent) schedule | Actions of different transactions are mixed in time. | R1(A) R2(A) W1(A) W2(A) C1 C2 |
| Complete schedule | Contains a commit or an abort for every transaction listed in it. | Any schedule above that ends with C1, C2 (or Ai). |
Number of serial schedules
For n transactions there are n! possible serial schedules (for 2 transactions: 2; for 3: 6; for 4: 24). The number of possible interleaved schedules is much larger, so a DBMS needs a rule to decide which ones are safe.
Worked Example: Two serial schedules, two correct results
Situation: A = 1000, B = 1000.T1: transfer ₹100 from A to B (A = A − 100; B = B + 100).
T2: add 10% interest to both accounts (A = A × 1.1; B = B × 1.1).
| Serial order | Calculation | Final A | Final B | A + B |
|---|---|---|---|---|
| T1 then T2 | (900, 1100) then × 1.1 | 990 | 1210 | 2200 |
| T2 then T1 | (1100, 1100) then transfer | 1000 | 1200 | 2200 |
1.7 Applications, Advantages and Limitations
Applications
- Banking and payments: NEFT, UPI, ATM withdrawals, loan processing.
- Transport and travel: railway and airline seat reservation.
- E-commerce and business: order placement, inventory, billing.
- Education: university admission and result systems where thousands of students use the portal together.
- Healthcare and government: patient records, Aadhaar-linked services, tax filing.
| Advantages of the transaction concept | Limitations |
|---|---|
| Data stays correct despite failures. Many users can work at once safely. Committed work is never lost. Simplifies application programming: programmers think about one transaction at a time. | Logging and locking add overhead and reduce speed. Long transactions can block others. Strict isolation can reduce concurrency. Failures may force a transaction to be restarted. |
Important Points for Revision
Difference Between Important Concepts
| Basis | Atomicity | Durability |
|---|---|---|
| Concerns | Uncommitted / failed transactions | Committed transactions |
| Mechanism | UNDO using log | REDO using log |
| Guarantee | No partial effects | No loss of committed effects |
| Basis | Serial schedule | Non-serial schedule |
|---|---|---|
| Interleaving | None | Present |
| Performance | Poor (no concurrency) | Better (CPU and disk used well) |
| Correctness | Always correct | Correct only if equivalent to a serial schedule |
| Basis | COMMIT | ROLLBACK |
|---|---|---|
| Effect | Makes changes permanent | Undoes all changes |
| Final state | Committed | Aborted |
Important formulas: Number of serial schedules of n transactions = n!.
Chapter 1: Questions with Answers
A. Multiple Choice Questions (20)
B. Very Short Answer Questions (10)
C. Short Answer Questions (10)
D. Long Answer Questions (5)
Atomicity means that all actions of a transaction are done or none are. In a transfer of ₹500 from A to B, the debit and credit must both occur. If a crash occurs in between, the DBMS undoes the partial debit using the log.
Consistency means that a transaction run alone leaves the database consistent. In the same transfer, the sum A + B must stay unchanged and constraints such as non-negative balance must hold. The programmer is mainly responsible, assisted by integrity constraints.
Isolation means that every transaction appears to run alone although the DBMS interleaves them. If two users book the last cinema seat together, isolation ensures only one succeeds. It is implemented by concurrency control such as locking, and the usual correctness target is serializability.
Durability means that committed changes survive crashes. The DBMS writes log records to stable storage before reporting commit, and after a crash it redoes committed changes if needed.
Responsible components: the recovery manager supports atomicity (undo) and durability (redo); concurrency control supports isolation; the programmer plus constraints support consistency (see Figure 1.3).
Conclusion. Together, the four properties make banking, reservation and e-commerce systems reliable.
1. Active: the initial state; the transaction executes its reads and writes.
2. Partially committed: entered after the final statement executes. The changes may still be only in memory buffers.
3. Committed: entered after the DBMS has safely recorded the changes (log forced to stable storage). The effects are permanent, and this is a terminal state.
4. Failed: entered when normal execution cannot go on, because of a logical error, system crash, deadlock or a failure while writing. A transaction can fail from the active or the partially committed state.
5. Aborted: entered after the DBMS has rolled back the transaction and restored the database to its state before the transaction. This is also a terminal state. After this, the system may either restart the transaction (if the cause was a hardware or software failure, not a logical error) or kill it.
Transitions: Active → Partially committed (last statement done); Partially committed → Committed (changes made safe); Active/Partially committed → Failed (error); Failed → Aborted (rollback).
Example: In a UPI payment, the payment is Active during the debit/credit, Partially committed after the last write, and Committed when the bank confirms. If the network fails earlier, it becomes Failed and then Aborted, and the money is returned.
Notation. Ri(X), Wi(X), Ci, Ai.
Serial schedule. Transactions run one after another with no interleaving. Example: R1(A) W1(A) C1 R2(A) W2(A) C2. It is always correct but gives poor throughput because the CPU idles during I/O waits.
Non-serial (interleaved) schedule. Actions of different transactions are mixed. Example: R1(A) R2(A) W1(A) W2(A) C1 C2. It improves utilisation and response time, but may violate isolation unless it is equivalent to a serial schedule.
Complete schedule. A schedule that has a commit or an abort for every transaction in it.
Number of serial schedules. n transactions have n! serial schedules; for 3 transactions there are 6.
Example of different correct serial results. With A = B = 1000, T1 = transfer 100 from A to B and T2 = add 10% interest to both: T1;T2 gives (990, 1210) and T2;T1 gives (1000, 1200). Both are correct, since the total is 2200 in both cases.
Conclusion. Schedules are the tool to study concurrent execution. Chapter 2 explains how to decide which non-serial schedules are safe.
1. Atomicity and durability: log and recovery manager. Each change is recorded in a log on stable storage, containing identification of the transaction and the old and new values. If a transaction fails or the system crashes before commit, the recovery manager undoes its changes using old values. After commit, the log is forced to stable storage first, so the recovery manager can redo any committed change that did not reach the data pages.
2. Isolation: concurrency control. The lock manager gives a transaction a lock on a data item before it reads or writes it. Conflicting requests must wait. Protocols such as Two-Phase Locking (Chapter 3) ensure that the final result equals a serial execution. Deadlocks that may result are detected and resolved (Chapter 4).
3. Consistency: constraints and programmer. The DBMS enforces declared integrity constraints (primary key, foreign key, CHECK) at the end of statements or transactions and aborts violators. The programmer writes transactions that, when run alone, preserve the application’s rules. Atomicity and isolation then ensure that the rules are preserved even with failures and concurrency.
Summary. Log + recovery for A and D, locking for I, constraints + programmer for C.
Without atomicity. If the system fails after WRITE(A) but before WRITE(B), A = 4,500 and B = 3,000, so ₹500 vanishes. Total becomes 7,500 instead of 8,000.
Without consistency. If the program mistakenly adds 5,000 instead of 500 to B, the data may satisfy no business rule; the total is wrong although every step ran.
Without isolation. Suppose T2 reads A and B for an audit between T1’s two writes. It sees A = 4,500 and B = 3,000 and reports a total of 7,500, an incorrect report. Or two simultaneous withdrawals from A could both read 5,000 and both write back, causing a lost update.
Without durability. If the bank confirms the transfer and crashes before the data reaches disk, the transfer disappears after restart, although the customer has already been informed.
With ACID. The transfer is all-or-nothing, preserves the total, is invisible to other transactions until complete, and survives failures.
Conclusion. ACID turns a risky sequence of reads and writes into a reliable business operation.
E. Application-Based Questions (5)
Chapter 1 Assessment (Total 30 marks)
Section A: MCQs (10 × 1 = 10 marks)
2. Which is a final state of a transaction? (A) Active (B) Failed (C) Committed (D) Partially committed
3. The number of serial schedules for 5 transactions is: (A) 25 (B) 60 (C) 120 (D) 5
4. Which component enforces isolation? (A) Lock manager (B) Log (C) Parser (D) Disk
5. The DBMS “sees” a transaction as a sequence of: (A) SQL joins (B) Reads and writes (C) Indexes (D) Views
6. A schedule with actions of T1 and T2 mixed is: (A) Serial (B) Interleaved (C) Empty (D) Invalid
7. Which command undoes the current transaction? (A) COMMIT (B) ROLLBACK (C) SAVE (D) INSERT
8. UNDO is mainly used for: (A) Isolation (B) Durability (C) Atomicity (D) Indexing
9. REDO is mainly used for: (A) Durability (B) Isolation (C) Parsing (D) Sorting
10. Order of actions inside a transaction in a schedule is: (A) Reversed (B) Preserved (C) Random (D) Deleted
Section B: Short answers (3 × 3 = 9 marks)
12. What is the difference between a serial and an interleaved schedule?
13. Explain the failed and aborted states.
Section C: Descriptive (2 × 5.5 = 11 marks)
15. Draw and explain the transaction state diagram. (5.5)
Answer Key
Q11: A transaction is a logical unit of work of reads and writes that is done fully or not at all. Properties: Atomicity, Consistency, Isolation, Durability.
Q12: In a serial schedule, transactions run one after another with no mixing. In an interleaved schedule, their actions are mixed; it gives better throughput but must be equivalent to a serial schedule to be correct.
Q13: Failed: normal execution cannot continue (error, crash, deadlock). Aborted: the transaction has been rolled back and the database restored to its earlier state; the transaction may be restarted or killed.
Q14: See L1 (definition of each property, transfer example, responsible component). Award marks: 1 per property with example, 1.5 for diagram/component table.
Q15: See L2 and Figure 1.2 (five states, transitions, example). Award 2 marks for correct diagram, 3.5 for explanation.
Quick Revision: Chapter 1
- A transaction is a logical unit of work: all steps or none; it ends with commit or abort.
- States: Active → Partially committed → Committed, or Active/Partially committed → Failed → Aborted.
- ACID = Atomicity, Consistency, Isolation, Durability.
- Atomicity and durability: recovery manager with log (undo and redo). Isolation: concurrency control. Consistency: programmer and constraints.
- A schedule is an ordered list of actions of several transactions; order inside each transaction is preserved.
- Serial: no interleaving. Non-serial: interleaved. Complete: every transaction has commit or abort.
- n transactions have n! serial schedules; different serial orders may give different but correct results.
2. Draw and explain the transaction state diagram.
3. Define schedule; differentiate serial and non-serial schedules.
4. How does a DBMS ensure atomicity and durability?
5. Show with an example what can go wrong without isolation or atomicity.
Next: Chapter 2 – Concurrent Execution, Serializability and Recoverability
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.
Transaction Management
Database Management Systems • UG Study Notes
www.edukosal.com
Book Plan
- Chapter 1 – Transactions, ACID Properties and Schedules
- Chapter 2 – Concurrent Execution, Serializability and Recoverability (this post)
- Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management, Performance of Locking
- Chapter 4 – Dealing with Deadlocks
- Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery
Inside Chapter 2: 2.1 Concurrent execution • 2.2 Anomalies (WR, RW, WW) • 2.3 Conflicts and conflict equivalence • 2.4 Serializability and precedence graph • 2.5 View serializability (introduction) • 2.6 Recoverability • 2.7 Applications, advantages, limitations • Important points • Question bank • Practice test • Summary
Concurrent Execution, Serializability and Recoverability
2.1 Concurrent Execution of Transactions
In Chapter 1 you saw that running transactions one by one (a serial schedule) is always correct but slow. A bank server may receive thousands of requests every second. If each had to wait for the previous one to finish, customers would queue endlessly. So a DBMS lets transactions overlap in time. This is called concurrent execution, and the resulting schedule is an interleaved (non-serial) schedule.
Why concurrency?
- Better throughput and resource use: A transaction spends much time waiting for disk I/O. While it waits, the CPU can run another transaction, so more transactions are finished per second.
- Lower average response time: A short transaction (checking a balance) need not wait behind a long one (monthly interest calculation).
Everyday analogy: A single cashier at a railway counter serving one passenger from start to end is a serial schedule. Several counters serving different passengers while sharing one ticket register is concurrency; it is faster, but the shared register must be updated carefully.
2.2 Anomalies Due to Interleaved Execution
Problems arise only when two transactions touch the same data item and at least one of them writes. Three standard patterns of conflict are named by the order of the two actions.
| Conflict | Anomaly name | What goes wrong | Everyday example |
|---|---|---|---|
| WR (write then read) | Dirty read (reading uncommitted data) | T2 reads a value written by T1 that may later be rolled back. | You see a “credited” SMS balance that the bank later reverses. |
| RW (read then write) | Unrepeatable read | T1 reads A twice and finds that its value changed in between. | A shopping page shows 10 items in stock, but 9 at checkout. |
| WW (write then write) | Overwriting uncommitted data / lost update | T2 overwrites a value of T1 before T1 commits, losing T1’s update. | Two clerks edit the same Excel cell; the later save wins. |
Example 1: Basic Example (Lost Update)
Problem / Situation: Stock of an item A = 100. T1 adds 50 units; T2 adds 20 units. Correct final stock: 170.Explanation: Both transactions read the old value before either writes.
Step-by-step solution:
| Step | T1 | T2 | A in DB |
|---|---|---|---|
| 1 | R(A) → 100 | 100 | |
| 2 | R(A) → 100 | 100 | |
| 3 | W(A) = 100 + 50 = 150, Commit | 150 | |
| 4 | W(A) = 100 + 20 = 120, Commit | 120 |
Example 2: Real-Life Application (Dirty Read)
Real-world situation: A = 1000, B = 1000. T1 transfers ₹100 from A to B. T2 credits 6% interest to both accounts.How the concept is applied: Schedule S: R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) C2 R1(B) W1(B) C1. T2 reads A after T1 has written it but before T1 commits (WR conflict), and T1 reads B after T2 has written it (another WR).
| Execution | Final A | Final B | A + B |
|---|---|---|---|
| Serial T1; T2 | 954 | 1166 | 2120 |
| Serial T2; T1 | 960 | 1160 | 2120 |
| Interleaved S | 954 | 1160 | 2114 |
Learning outcome: The interleaved result (954, 1160) equals neither serial result; ₹6 of interest has been lost. S is therefore not serializable.
2.3 Conflicts and Conflict Equivalence
| Pair | Conflict? | Reason |
|---|---|---|
| R1(A), R2(A) | No | Both only read; order does not matter. |
| R1(A), W2(A) | Yes (RW) | Order changes what T1 reads. |
| W1(A), R2(A) | Yes (WR) | Order changes what T2 reads. |
| W1(A), W2(A) | Yes (WW) | Order decides the final value of A. |
| W1(A), W2(B) | No | Different data items. |
| R1(A), W1(A) | No | Same transaction. |
2.4 Serializability
When we judge a schedule, we consider only the committed transactions; aborted transactions are treated as if they never occurred (their effects are undone).
Working process: testing with a precedence graph
- Draw one node for each (committed) transaction.
- For every pair of conflicting actions where Ti’s action comes first and Tj’s later, draw a directed edge Ti → Tj.
- If the graph has a cycle, the schedule is not conflict serializable.
- If the graph is acyclic, the schedule is conflict serializable. A topological order of the nodes gives an equivalent serial schedule.
Example 3: Practical / Case Study (Precedence graph)
Background: Three transactions run on items X and Y with schedule S3: R1(X) W2(X) R3(Y) W1(Y) R3(X) Commit all.Problem: Is S3 conflict serializable? If so, give an equivalent serial order.
Application of the concept: List conflicting pairs.
- On X: R1(X) before W2(X) gives T1 → T2. W2(X) before R3(X) gives T2 → T3.
- On Y: R3(Y) before W1(Y) gives T3 → T1.
Result: The graph has a cycle.
Conclusion: S3 is not conflict serializable. If R3(Y) had come after W1(Y), the edge T3 → T1 would become T1 → T3 and the graph would be acyclic, giving serial order T1, T2, T3.
2.5 View Serializability (Introduction)
Conflict serializability is sufficient but sometimes too strict. View serializability is a weaker (more general) condition. Two schedules are view equivalent if (1) each transaction reads the same values (from the same writer, or the initial value) in both, and (2) the final write on each data item is by the same transaction. A schedule is view serializable if it is view equivalent to some serial schedule.
| Basis | Conflict serializability | View serializability |
|---|---|---|
| Scope | Narrower | Broader (includes all conflict serializable schedules) |
| Testing | Easy: cycle test on the precedence graph | Hard (testing is NP-complete) |
| Use in DBMS | Used in practice | Mainly theoretical; allows “blind writes” |
2.6 Recoverability
Serializability considers only schedules where all transactions commit. But transactions can also abort. If T2 has used values written by T1 and then T1 aborts, T2’s work is based on data that never officially existed. The schedule must be arranged so that failures can be handled safely. This is the study of recoverability.
Classes of schedules
| Class | Definition | Example |
|---|---|---|
| Recoverable | Each transaction commits only after all transactions it has read from have committed. | W1(A) R2(A) C1 C2 |
| Non-recoverable | A transaction commits before a transaction it read from. If the latter aborts, the commit cannot be undone. | W1(A) R2(A) C2 Abort1 |
| Avoids cascading aborts (ACA / cascadeless) | Transactions read only values written by committed transactions. No dirty reads. | W1(A) C1 R2(A) C2 |
| Strict | No transaction reads or overwrites an item written by another transaction until that transaction commits or aborts. | W1(A) C1 W2(A) C2 |
Cascading rollback
If T2 has read an uncommitted value of T1 and T1 aborts, T2 must also be aborted. If T3 read from T2, then T3 must be aborted too, and so on. This chain of aborts is a cascading rollback. It wastes work, so DBMSs prefer cascadeless or strict schedules.
Worked Example: Classify schedules
| Schedule | Analysis | Class |
|---|---|---|
| S4: W1(A) R2(A) C2 Abort1 | T2 read from T1 and committed before T1 ended. T1 aborts, but T2’s commit cannot be undone. | Non-recoverable |
| S5: W1(A) R2(A) C1 C2 | T2 commits after T1. But T2 read uncommitted data; if T1 had aborted, T2 would also have to abort. | Recoverable, not cascadeless |
| S6: W1(A) C1 R2(A) W2(A) C2 | T2 reads and writes A only after T1 has committed, so there is no dirty read and no overwrite of uncommitted data. | Strict |
| S7: W1(A) W2(A) C1 C2 | T2 overwrites A before T1 commits (no reads, so cascadeless), but not strict. | Cascadeless, not strict |
2.7 Applications, Advantages and Limitations
Applications
- Banking and payments: thousands of UPI and ATM transactions run concurrently while every balance stays correct.
- Railway/airline booking: concurrent users, but one seat is sold once.
- E-commerce: stock counts are updated by many buyers at once without lost updates.
- Database design and testing: serializability tests are used by researchers and DBMS designers to prove that a concurrency protocol is correct.
| Advantages | Limitations |
|---|---|
| Concurrency raises throughput and lowers response time. Serializability gives a clear, mathematical correctness rule. Recoverability makes safe handling of aborts possible. The precedence-graph test is simple. | Testing a finished schedule is not practical in real time; DBMSs enforce protocols (locking) instead. Strict schedules reduce concurrency. Cascading rollbacks waste work. View serializability is hard to test. |
Important Points for Revision
Difference Between Important Concepts
| Basis | Recoverable | Cascadeless | Strict |
|---|---|---|---|
| Dirty reads | Allowed if commit order is right | Not allowed | Not allowed |
| Overwrite of uncommitted data | Allowed | Allowed | Not allowed |
| Cascading aborts | Possible | None | None |
| Undo during rollback | Complex | Complex | Simple (restore before-image) |
| Basis | Serial schedule | Serializable schedule |
|---|---|---|
| Interleaving | None | Present |
| Equivalent to a serial schedule | It is one | Yes |
| Concurrency | None | High |
Chapter 2: Questions with Answers
A. Multiple Choice Questions (20)
B. Very Short Answer Questions (10)
C. Short Answer Questions (10)
D. Long Answer Questions (5)
1. WR conflict (dirty read). T1 writes A, and T2 reads A before T1 commits. If T1 later aborts, T2 has used invalid data. Example: with A = B = 1000, T1 transfers 100 from A to B and T2 adds 6% interest to both. In the schedule R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) C2 R1(B) W1(B) C1, the final state is A = 954, B = 1160, which differs from both serial results (954, 1166) and (960, 1160). Interest of ₹6 is lost.
2. RW conflict (unrepeatable read). T1 reads A, T2 modifies A and commits, T1 reads A again and sees a different value. Example: stock changes from 10 to 9 between two reads.
3. WW conflict (lost update / overwriting uncommitted data). Two transactions read A = 100; T1 writes 150 and T2 writes 120. The final value 120 loses T1’s +50.
Consequences. Wrong results, inconsistent totals and possible cascading aborts.
Conclusion. Concurrency control must prevent these interleavings so that the final effect equals a serial execution.
Conflict equivalence. Two schedules are conflict equivalent if they contain the same actions and order each conflicting pair identically. A schedule is conflict serializable if it is conflict equivalent to some serial schedule.
Test. (1) Make a node for each committed transaction. (2) For each conflicting pair with Ti first and Tj later, draw an edge Ti → Tj. (3) If the graph has a cycle, the schedule is not conflict serializable; otherwise it is, and a topological sort gives an equivalent serial order.
Example. S1: R1(A) W1(A) R2(A) W2(A) R1(B) W1(B) R2(B) W2(B). On A, T1’s actions precede T2’s conflicting actions, so T1 → T2. On B, again T1 → T2. The graph has one edge and no cycle, so S1 is conflict serializable and equivalent to T1;T2.
Now S2: R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) R1(B) W1(B). On A: T1 → T2. On B: T2’s actions precede T1’s, so T2 → T1. The cycle T1 → T2 → T1 shows S2 is not conflict serializable (Figure 2.2).
Conclusion. The test is easy, and conflict serializability is the correctness criterion used by real DBMSs.
Recoverable. Every transaction commits only after all transactions it read from have committed. Example: W1(A) R2(A) C1 C2 (recoverable); W1(A) R2(A) C2 Abort1 (non-recoverable, since T2 has committed on rolled-back data).
Avoiding cascading aborts (cascadeless). Transactions read only committed values. Example: W1(A) C1 R2(A) C2. In W1(A) R2(A) C1 C2, if T1 aborted, T2 would have to abort too; that is a cascading rollback, so this schedule is recoverable but not cascadeless.
Strict. No transaction reads or overwrites an item until the last writer has committed or aborted. Example: W1(A) C1 W2(A) C2. Compare W1(A) W2(A) C1 C2, which is cascadeless but not strict. Strict schedules allow simple rollback by restoring before-images.
Relationship. Strict ⊂ Cascadeless ⊂ Recoverable ⊂ All schedules (Figure 2.3).
Conclusion. A DBMS should produce schedules that are serializable and, preferably, strict. Strict Two-Phase Locking achieves this.
Serial executions. T1;T2: A = 900 × 1.06 = 954, B = 1100 × 1.06 = 1166, total 2120. T2;T1: A = 1060 − 100 = 960, B = 1060 + 100 = 1160, total 2120. Both are valid.
Interleaved schedule S. R1(A) W1(A) R2(A) W2(A) R2(B) W2(B) C2 R1(B) W1(B) C1. T1 writes A = 900. T2 reads A = 900 and writes 954. T2 reads B = 1000 and writes 1060, and commits. T1 reads B = 1060 and writes 1160. Final: A = 954, B = 1160, total 2114.
Analysis. The result matches neither serial result, and ₹6 of interest has been lost. In the precedence graph, A gives T1 → T2 and B gives T2 → T1: a cycle.
Conclusion. A non-serializable schedule violates isolation and can corrupt data, so the DBMS must prevent it, for example by locking.
Recoverability deals with the safety of aborts and commits: no transaction may commit on data that is later rolled back. It supports Atomicity and Durability by making recovery possible.
Independence. A schedule can be serializable but non-recoverable, e.g. W1(A) R2(A) C2 Abort1, whose committed projection (only T2) is trivially serializable, yet T2 committed on data from the aborted T1. A schedule can also be recoverable but not serializable, e.g. R1(A) R2(A) W1(A) W2(A) C1 C2: there is no reads-from, so it is recoverable, but the edges T1 → T2 and T2 → T1 form a cycle.
Table.
| Basis | Serializability | Recoverability |
|---|---|---|
| Concerns | Order of conflicting actions | Order of commits vs reads-from |
| Failure when violated | Wrong results | Unrecoverable commits, cascading aborts |
| Test | Precedence graph | Check commit order |
E. Application-Based Questions (5)
Chapter 2 Assessment (Total 30 marks)
Section A: MCQs (10 × 1 = 10 marks)
2. Which pair conflicts? (A) R1(A), R2(B) (B) R1(A), R2(A) (C) W1(B), R2(B) (D) W1(A), W1(B)
3. A cycle in the precedence graph means: (A) Serializable (B) Not conflict serializable (C) Strict (D) Serial
4. A recoverable schedule needs commit after: (A) Reads-from transactions commit (B) System restart (C) Log flush only (D) Any abort
5. Strict ⊂ ? ⊂ Recoverable. The missing class is: (A) Serial (B) Cascadeless (C) View (D) Lock
6. Edges T1 → T2, T2 → T3. A serial order is: (A) T3, T2, T1 (B) T2, T1, T3 (C) T1, T2, T3 (D) T3, T1, T2
7. Lost update corresponds to: (A) WW (B) RR (C) WR only (D) No conflict
8. A cascadeless schedule never has: (A) Commits (B) Writes (C) Dirty reads (D) Reads
9. Testing view serializability is: (A) Trivial (B) NP-complete (C) Linear (D) Impossible
10. Which gives strict schedules? (A) Strict 2PL (B) No protocol (C) Dirty reads (D) Random order
Section B: Short answers (3 × 3 = 9 marks)
12. What is a cascading rollback? Give a schedule.
13. State the difference between a cascadeless and a strict schedule.
Section C: Descriptive (2 × 5.5 = 11 marks)
15. Explain recoverable, cascadeless and strict schedules with one example each. (5.5)
Answer Key
Q11: Different transactions; same data item; at least one is a write.
Q12: When an abort of one transaction forces others that read its data to abort. Example: W1(A) R2(A) W2(B) R3(B) Abort1 → T2 aborts, then T3 aborts.
Q13: Cascadeless forbids reading uncommitted data. Strict also forbids overwriting uncommitted data.
Q14: Conflicts on A: R1(A) before W2(A): T1 → T2. R2(A) before W1(A): T2 → T1. This is already a cycle, so S is not conflict serializable. (Also W2(A) before W1(A): T2 → T1; W1(A) before R3(A) and W3(A): T1 → T3; T2 → T3.) Award 3 marks for correct edges and graph, 2.5 for conclusion with cycle.
Q15: See L3: recoverable W1(A) R2(A) C1 C2; cascadeless W1(A) C1 R2(A) C2; strict W1(A) C1 W2(A) C2. Award 1 mark per definition+example, 2.5 for relationship and discussion.
Quick Revision: Chapter 2
- Concurrency improves throughput and response time but can cause anomalies: dirty read (WR), unrepeatable read (RW), lost update (WW).
- Conflict: different transactions, same item, at least one write.
- Conflict serializable: conflict equivalent to some serial schedule; test: precedence graph has no cycle; topological order gives the serial schedule.
- View serializability is broader but hard to test; every conflict serializable schedule is view serializable.
- Recoverable: commit only after reads-from transactions commit. Cascadeless: read only committed data. Strict: no read or overwrite of uncommitted data.
- Strict ⊂ Cascadeless ⊂ Recoverable. Serializability and recoverability are independent; a DBMS needs both.
2. Define conflict serializability and explain the precedence-graph test.
3. Explain recoverable, cascadeless and strict schedules and their relationship.
4. Differentiate conflict and view serializability.
5. Test a given schedule for conflict serializability and recoverability.
Next: Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.
Transaction Management
Database Management Systems • UG Study Notes
www.edukosal.com
Book Plan
- Chapter 1 – Transactions, ACID Properties and Schedules
- Chapter 2 – Concurrent Execution, Serializability and Recoverability
- Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking (this post)
- Chapter 4 – Dealing with Deadlocks
- Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery
Inside Chapter 3: 3.1 Lock-based concurrency control • 3.2 Strict 2PL • 3.3 Two-Phase Locking (2PL) • 3.4 Introduction to lock management • 3.5 Performance of locking • 3.6 Applications, advantages, limitations • Important points • Question bank • Practice test • Summary
Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking
3.1 Lock-Based Concurrency Control
In Chapter 2 you learned that interleaved schedules must be conflict serializable and recoverable. But a DBMS cannot wait to check a schedule after it has happened; it must prevent bad schedules while transactions run. The most widely used method is locking.
Everyday analogy: When you use a library reading room, you may share a book with others who only want to read it, but if someone wants to write notes in a master copy, nobody else may touch it until the writer finishes. A lock works like this “permission token” on a data item.
Types of locks
| Lock | Also called | Allows | Taken for |
|---|---|---|---|
| Shared lock (S) | Read lock | Reading the object. Many transactions may hold S on the same object together. | READ(A) |
| Exclusive lock (X) | Write lock | Reading and writing. Only one transaction can hold X, and no other lock can coexist with it. | WRITE(A) |
Lock compatibility matrix
| Held by T1 ↓ / Requested by T2 → | S | X |
|---|---|---|
| S | Granted | Wait |
| X | Wait | Wait |
This table mirrors the idea of conflicts from Chapter 2: two reads do not conflict, but a write conflicts with both reads and writes. A transaction whose request cannot be granted is blocked (put in a queue) until the conflicting lock is released.
Example 1: Basic Example
Problem / Situation: T1 and T2 only read item A; T3 wants to update A.Explanation: S locks are compatible with each other but not with X.
Step-by-step solution:
| Step | Action | Lock table for A |
|---|---|---|
| 1 | T1 requests S(A), granted, reads A | Held: S by T1 |
| 2 | T2 requests S(A), granted, reads A | Held: S by T1, T2 |
| 3 | T3 requests X(A): conflicts with S locks, so T3 waits | Held: S by T1, T2; Queue: T3 (X) |
| 4 | T1 and T2 commit and release their locks | Held: none |
| 5 | T3 gets X(A), writes A, commits | Held: X by T3 |
3.2 Strict Two-Phase Locking (Strict 2PL)
Rule 2: All locks held by a transaction are released only when the transaction completes (commits or aborts).
Note: Some books call the variant in which all locks (S and X) are held until the end rigorous 2PL, and use the name “strict 2PL” for the variant in which only X locks are held until the end. The notes here follow the first definition (all locks held to the end), which is common in DBMS textbooks; always check which definition your syllabus uses.
Why Strict 2PL works
- Conflict serializable: Because locks are kept until the end, a transaction that conflicts with an earlier one has to wait until it has finished; this gives a serial-like order.
- Strict (hence cascadeless and recoverable): No other transaction can read or overwrite an item written by T until T commits or aborts, so there are no dirty reads and no cascading aborts.
- Simple: Easy to implement, and used in most commercial systems.
3.3 Two-Phase Locking (2PL)
The lock point is the moment at which the transaction holds its last lock (the end of the growing phase). The order of lock points of transactions gives an equivalent serial order, which is why 2PL guarantees conflict serializability.
Why every 2PL schedule is conflict serializable (idea)
Suppose Ti and Tj have conflicting actions on A, and Ti acts first. Ti must hold a lock on A that Tj cannot obtain until Ti releases it, and by the 2PL rule Ti has already acquired all its locks at that point (it releases only in the shrinking phase). So Ti’s lock point comes before Tj’s. Hence every edge Ti → Tj of the precedence graph goes from an earlier lock point to a later one, so the graph can have no cycle.
Variants of 2PL
| Variant | Rule | Effect |
|---|---|---|
| Basic 2PL | Growing phase, then shrinking phase. | Conflict serializable; may have cascading aborts (locks released before commit); deadlock possible. |
| Strict 2PL | All locks held until commit/abort. | Conflict serializable and strict; deadlock possible. |
| Conservative (static) 2PL | Lock all required items before the transaction starts; wait if any is unavailable. | Deadlock-free; but the items needed must be known in advance and concurrency is lower. |
Example 2: Real-Life Application
Real-world situation: Two passengers try to book the last seat 14A on a train.How the concept is applied: Booking transaction T1 takes an X lock on the seat record and marks it booked. T2’s X request is blocked. When T1 commits (Strict 2PL: lock released only at commit), T2 gets the lock, sees that the seat is already booked, and tells the passenger.
Learning outcome: Locking enforces isolation, which prevents double booking.
Example 3: Practical / Case Study (What goes wrong without 2PL)
Background: A = B = 1000. T1 transfers ₹100 from A to B. T2 adds 6% interest to A and B. Suppose each transaction locks and unlocks each item immediately after use (not 2PL).Problem: Consider: X1(A) R1(A) W1(A) U1(A); X2(A) R2(A) W2(A) U2(A); X2(B) R2(B) W2(B) U2(B) C2; X1(B) R1(B) W1(B) U1(B) C1. Every request was legal in the lock table, yet T1 locks B after unlocking A.
Application of the concept:
- Without 2PL: A = 900 × 1.06 = 954; B = 1000 × 1.06 = 1060, then T1 adds 100 to give 1160. Result (954, 1160); this equals neither serial result, (954, 1166) for T1;T2 or (960, 1160) for T2;T1.
- With 2PL: T1 would keep X(A) until it has also obtained X(B). T2’s request X(A) would wait until T1 finishes, so the execution is equivalent to T1;T2 and gives (954, 1166).
Conclusion: Merely taking locks is not enough; the two-phase rule is what guarantees serializability.
3.4 Introduction to Lock Management
The part of the DBMS that handles lock and unlock requests is the lock manager. Transactions send it requests; it grants, queues or refuses them.
Main parts and ideas
| Item | Explanation |
|---|---|
| Lock table | A hash table keyed by object identifier. Each entry records the number of holders, the lock mode (S or X) and a pointer to the queue of waiting requests. |
| Transaction table | For each transaction, a list of the locks it holds. It lets the lock manager release all locks quickly at commit or abort. |
| Request queue | A request that cannot be granted waits in a queue, usually in first-come-first-served order to avoid starvation (a transaction waiting forever). |
| Atomic operations | Lock and unlock requests must themselves be handled as indivisible actions, so that two transactions cannot both be granted a conflicting lock. |
| Lock upgrade / downgrade | Upgrade: a transaction holding S asks for X on the same object (e.g. it read a row and now decides to update it); granted only if no other transaction holds a lock on it. Downgrade: X is converted to S, allowing other readers sooner. Two transactions both upgrading the same object can deadlock, so some systems use an update (U) lock when a transaction reads with the intention to write. |
| Lock granularity | Locks can be placed on the whole database, a table, a page or a single record. Fine granularity (records) allows more concurrency but needs more lock overhead; coarse granularity (tables) is cheap but allows less concurrency. Systems that mix granularities use special intention locks on the higher levels. |
| Latches vs locks | A latch is a very short-duration, low-cost lock used to protect the physical consistency of in-memory structures (for example, a page being read or written). A lock protects logical database objects for the whole transaction. |
3.5 Performance of Locking
Locking is safe, but it has a cost. Lock-based schemes resolve conflicts by two mechanisms: blocking (making a transaction wait) and aborting (and restarting) a transaction. Both lower performance.
- Blocking: Waiting transactions hold their locks, which causes others to wait too, forming chains of blocked transactions. Time is wasted.
- Aborts (restarts): When a deadlock is resolved, a victim transaction is rolled back and restarted. The work it has done is wasted. Aborts are fewer than blocks in most systems, so blocking is generally the main cost.
Throughput and thrashing
When the number of active transactions grows from small, throughput (transactions completed per unit time) first increases because more work overlaps. But more transactions also mean more conflicts. Beyond a point, adding more transactions makes more of them blocked, and throughput drops. This is called thrashing. Experience shows that thrashing begins when roughly 30% of the active transactions are blocked.
How to improve locking performance
| Technique | How it helps |
|---|---|
| Lock the smallest sensible object | A record lock blocks far fewer transactions than a table lock. |
| Reduce the time locks are held | Keep transactions short; do user interaction or slow computation outside the transaction; take X locks as late as possible. |
| Avoid hot spots | Items touched by many transactions (a global counter) cause queues; redesign to spread updates or delay them to the end of the transaction. |
| Use shared locks wherever possible | Readers do not block each other. |
| Limit the number of active transactions | Admission control keeps the system below the thrashing point. |
| Run long reports in off-peak hours | Long transactions hold many locks for a long time. |
| Use lower isolation levels where acceptable | Fewer or shorter locks (see Chapter 5). |
3.6 Applications, Advantages and Limitations
Applications
- Banking: account updates by multiple tellers, ATMs and UPI at once.
- Reservation systems: exclusive locks on seat or room records.
- E-commerce: locking stock rows during order placement.
- Enterprise systems (ERP, hospital, university portals): thousands of concurrent users updating shared records.
| Advantages of locking (Strict 2PL) | Limitations |
|---|---|
| Guarantees conflict serializability and recoverability. Simple rules; widely supported. Prevents lost updates and dirty reads. Strict 2PL avoids cascading aborts. | Blocking reduces concurrency; thrashing at high load. Deadlocks are possible and must be handled. Lock management has overhead (memory and CPU). Long transactions can block many others. |
Important Points for Revision
Difference Between Important Concepts
| Basis | 2PL | Strict 2PL |
|---|---|---|
| Release of locks | Gradually in the shrinking phase | All at commit/abort |
| Serializable | Yes (conflict) | Yes (conflict) |
| Cascading aborts | Possible | None |
| Deadlock | Possible | Possible |
| Basis | Shared lock | Exclusive lock |
|---|---|---|
| Purpose | Read | Read and write |
| Holders at a time | Many | One |
| Compatible with S? | Yes | No |
| Basis | Lock | Latch |
|---|---|---|
| Protects | Logical database objects | Physical in-memory structures |
| Duration | Until transaction end (or earlier under 2PL) | Very short |
| Cost | Higher (lock manager) | Low |
Chapter 3: Questions with Answers
A. Multiple Choice Questions (20)
B. Very Short Answer Questions (10)
C. Short Answer Questions (10)
D. Long Answer Questions (5)
Lock modes. A shared lock (S) allows reading and can be held by many transactions. An exclusive lock (X) allows reading and writing and is held by only one transaction. Compatibility: only S–S is compatible; otherwise the requester waits in a queue.
Strict 2PL rules. (1) A transaction must hold S to read and X to write. (2) All locks are held until the transaction commits or aborts.
Why it works. If Ti and Tj conflict on an object, whichever transaction first obtains the lock keeps it until it finishes, so the other waits. The effect is the same as a serial execution in which the first transaction goes first, so the schedule is conflict serializable. Since nobody can read or overwrite an item written by an uncommitted transaction, schedules are strict: there are no dirty reads and no cascading aborts, and rollback is simple.
Example. Two passengers booking the last seat: the first takes X on the seat record; the second waits, then finds the seat booked after the first commits.
Limitations. It can cause deadlocks and reduces concurrency through blocking.
Conclusion. Strict 2PL is simple and safe, and is the basis of most commercial DBMSs.
Argument for serializability. Let Ti and Tj have conflicting actions on A with Ti first. Tj can lock A only after Ti releases its lock. Under 2PL, Ti releases only in its shrinking phase, so all of Ti’s locks, including its last one, were acquired before that release, and the lock point of Ti precedes the moment Tj gets the lock on A, which is before the lock point of Tj. Hence every edge Ti → Tj in the precedence graph goes from an earlier lock point to a later one. A cycle would require a lock point to precede itself, which is impossible. So the graph is acyclic and the schedule is conflict serializable; ordering transactions by lock point gives the equivalent serial schedule.
Variants. Strict 2PL holds all locks until commit/abort, giving strict schedules (no cascading aborts). Conservative 2PL acquires all locks before starting and is deadlock-free but needs advance knowledge.
Limitations. Basic 2PL permits cascading aborts and all variants except conservative can deadlock.
Lock table. A hash table on object identifiers. An entry records the number of transactions holding a lock, the lock mode and a pointer to the queue of waiting requests.
Transaction table. Each transaction has a list of the locks it holds, so that all can be released at commit or abort.
Processing a request. If the request is compatible with the locks currently held (and, for fairness, no earlier request is waiting), it is granted and the lock table is updated. Otherwise the transaction is queued and suspended. On release, the manager removes the lock and examines the queue to grant waiting requests, usually first-come-first-served, which prevents starvation.
Atomicity. Lock and unlock operations are executed atomically so that two transactions cannot both obtain conflicting locks.
Upgrades. A request to upgrade S to X is granted only when the requester is the sole holder; two simultaneous upgraders deadlock, which is why update locks may be used.
Latches. Short-duration latches protect the lock table and buffer pages physically, whereas locks protect logical objects.
Granularity. Locks may be at database, table, page or record level, trading concurrency against overhead.
Conclusion. An efficient lock manager is central to the correctness and speed of the DBMS.
Throughput curve. With few transactions, throughput rises as work overlaps. As the number of active transactions grows, so do conflicts. Beyond a point, more transactions only increase the blocked fraction, and throughput falls. This is thrashing, observed when about 30% of the active transactions are blocked (Figure 3.3).
Improvements.
- Lock the smallest suitable objects (record rather than table).
- Keep transactions short and hold locks for the minimum time; take X locks late.
- Avoid hot spots (heavily updated items) by redesigning updates.
- Prefer shared locks for reads and downgrade X to S when possible.
- Limit the number of active transactions by admission control.
- Run long reporting transactions in off-peak hours.
- Use lower isolation levels when the application can tolerate them.
Valid results. T1;T2 gives A = 900 × 1.06 = 954 and B = 1100 × 1.06 = 1166. T2;T1 gives A = 1060 − 100 = 960 and B = 1060 + 100 = 1160.
Non-2PL execution. Each transaction locks an item, uses it and unlocks it immediately. The order is: X1(A) R1(A) W1(A) U1(A); X2(A) R2(A) W2(A) U2(A); X2(B) R2(B) W2(B) U2(B) C2; X1(B) R1(B) W1(B) U1(B) C1. All lock requests are compatible, so the lock manager allows them. T1 writes A = 900; T2 reads 900 and writes 954; T2 reads B = 1000 and writes 1060; T1 reads 1060 and writes 1160. Result: (954, 1160). It equals neither valid result, so the schedule is not serializable. The precedence graph has T1 → T2 (on A) and T2 → T1 (on B).
With 2PL. T1 may not release X(A) before it acquires X(B). T2’s request for X(A) is blocked until T1 completes, giving the serial order T1;T2 and the result (954, 1166).
Conclusion. The two-phase rule, not merely the use of locks, guarantees serializability.
E. Application-Based Questions (5)
Chapter 3 Assessment (Total 30 marks)
Section A: MCQs (10 × 1 = 10 marks)
2. Compatible pair: (A) S–X (B) X–X (C) S–S (D) X–S
3. In 2PL, which is forbidden? (A) Locking in the growing phase (B) Acquiring a lock after releasing one (C) Releasing at the end (D) Reading under S
4. Strict 2PL avoids: (A) Cascading aborts (B) All deadlocks (C) All blocking (D) Logging
5. The lock manager stores waiting requests in: (A) A log (B) A queue (C) A page (D) An index
6. A deadlock-free 2PL variant is: (A) Basic (B) Strict (C) Conservative (D) Rigorous
7. Thrashing means: (A) Idle CPU (B) Falling throughput due to blocking (C) Disk failure (D) Log overflow
8. Record-level locking compared with table-level locking gives: (A) Less concurrency (B) More concurrency (C) No locks (D) No overhead
9. Short-duration lock for physical consistency is called: (A) Latch (B) X lock (C) Log (D) Index
10. The end of the growing phase is the: (A) Commit (B) Lock point (C) Abort (D) Checkpoint
Section B: Short answers (3 × 3 = 9 marks)
12. State the difference between 2PL and Strict 2PL.
13. What is a lock upgrade? Why can it cause trouble?
Section C: Descriptive (2 × 5.5 = 11 marks)
15. Explain the structure and working of a lock manager. (5.5)
Answer Key
Q11: S held / S requested: granted; S held / X requested: wait; X held / S requested: wait; X held / X requested: wait.
Q12: 2PL releases locks gradually in the shrinking phase and may cause cascading aborts; Strict 2PL holds all locks until commit/abort, so schedules are strict. Both are conflict serializable.
Q13: Converting S to X on an object already read. If two transactions holding S both request upgrade, each waits for the other: deadlock.
Q14: See L2 (lock point argument). Award 2 marks for the phases, 3.5 for the argument.
Q15: See L3 (lock table, transaction table, queue, atomicity, upgrade). Award 1 mark per component up to 5, 0.5 for diagram.
Quick Revision: Chapter 3
- Locks: S for read, X for write; only S–S is compatible; incompatible requests wait in a queue.
- Strict 2PL: S before read, X before write; all locks held until commit/abort → conflict serializable and strict.
- 2PL: growing then shrinking phase; no lock after the first release; lock point gives the serial order.
- Conservative 2PL: all locks upfront, deadlock-free but impractical for unknown access sets.
- Lock manager: lock table (hash on object, holders, mode, queue), transaction table, atomic requests, upgrades, latches, granularity.
- Performance: costs are blocking and aborts; thrashing at roughly 30% blocked; remedies include finer granularity, shorter transactions, fewer hot spots and limits on active transactions.
2. Explain 2PL and its role in serializability.
3. Describe the working of a lock manager.
4. Explain thrashing and how to improve locking performance.
5. Compare lock modes, 2PL variants and locks versus latches.
Next: Chapter 4 – Dealing with Deadlocks
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.
Transaction Management
Database Management Systems • UG Study Notes
www.edukosal.com
Book Plan
- Chapter 1 – Transactions, ACID Properties and Schedules
- Chapter 2 – Concurrent Execution, Serializability and Recoverability
- Chapter 3 – Lock-Based Concurrency Control, 2PL, Lock Management and Performance of Locking
- Chapter 4 – Dealing with Deadlocks (this post)
- Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery
Inside Chapter 4: 4.1 What is a deadlock • 4.2 Conditions for deadlock • 4.3 Wait-for graph and deadlock detection • 4.4 Recovery: victim selection and rollback • 4.5 Timeouts • 4.6 Deadlock prevention (lock ordering, conservative 2PL, wait-die, wound-wait) • 4.7 Starvation and livelock • 4.8 Comparison, applications, advantages, limitations • Question bank • Practice test • Summary
Dealing with Deadlocks
4.1 What Is a Deadlock?
In Chapter 3 you saw that locking makes a transaction wait when another transaction holds a conflicting lock. Usually the holder finishes and the waiter proceeds. But sometimes transactions wait for each other in a circle, and none can ever proceed.
Everyday analogy: Two vehicles meet on a narrow bridge from opposite ends. Each is waiting for the other to back up. Neither moves. They are in a deadlock.
Example 1: Basic Example
Problem / Situation: T1 needs X locks on A and then B. T2 needs X locks on B and then A.Explanation: Each transaction gets its first lock, then requests the second one that the other holds.
Step-by-step solution:
| Step | T1 | T2 | Outcome |
|---|---|---|---|
| 1 | X(A) granted | T1 holds A | |
| 2 | X(B) granted | T2 holds B | |
| 3 | X(B) requested | T1 waits for T2 | |
| 4 | X(A) requested | T2 waits for T1 |
4.2 Conditions for Deadlock
A deadlock can occur only when all four of the following conditions hold at the same time. If a method of locking breaks any one condition, deadlock cannot happen.
| Condition | Meaning | In locking |
|---|---|---|
| 1. Mutual exclusion | A resource can be held by only one transaction at a time. | X locks are exclusive. |
| 2. Hold and wait | A transaction holds some locks while waiting for others. | T1 holds A and waits for B. |
| 3. No preemption | A lock cannot be forcibly taken away; the holder must release it. | Locks are released only at commit/abort (Strict 2PL). |
| 4. Circular wait | A cycle of transactions exists, each waiting for a lock held by the next. | T1 → T2 → T1. |
4.3 Wait-For Graph and Deadlock Detection
The DBMS can allow deadlocks to happen and then detect and resolve them. The tool for detection is the wait-for graph, which the lock manager can build from its lock table and request queues.
Working process
- Whenever a lock request cannot be granted, note which transactions hold the conflicting lock; add edges from the requester to those holders.
- When a lock is released or a transaction ends, remove the related edges.
- Check the graph for a cycle periodically (for example, every few seconds), or when a transaction has waited for a long time.
- If a cycle is found, choose a victim in the cycle, abort it, and let others continue.
Example 2: Real-Life Application
Real-world situation: A bank has accounts 101 and 202. At the same moment, transaction T1 transfers ₹500 from 101 to 202, and T2 transfers ₹300 from 202 to 101. Each transaction first locks the account it debits and then the account it credits.How the concept is applied: T1 locks 101 and T2 locks 202. T1 now needs 202 and T2 needs 101. The wait-for graph has T1 → T2 and T2 → T1: a cycle. The DBMS aborts one transaction (the victim); the other completes; the victim is restarted and then completes as well.
Learning outcome: Transfers in opposite directions are a classic source of deadlock. A good design avoids it by always locking accounts in a fixed order (for example, lower account number first); then both transactions would try 101 first, and one would simply wait.
Example 3: Practical / Case Study
Background: Three transactions run: T1 holds X(A), T2 holds X(B), T3 holds X(C).Problem: T1 requests X(B) and waits. T2 requests X(C) and waits. T3 requests X(A) and waits. Is there a deadlock? Which transaction should be aborted?
Application of the concept: Edges: T1 → T2 (T1 waits for B held by T2), T2 → T3, T3 → T1. This is a cycle, so deadlock. Suppose T3 has done the least work (fewest locks and updates); choose T3 as the victim and roll it back. Its lock on C is released, so T2 gets C; and T3’s request for A is cancelled.
Result: T2 completes and releases B, then T1 gets B and completes. T3 is restarted later.
Conclusion: Aborting one transaction in the cycle is enough to break the deadlock, so the cost is the work lost by the victim.
4.4 Recovery from Deadlock: Victim Selection and Rollback
Choosing the victim
The DBMS should abort the transaction whose abort costs least. Common criteria are:
| Criterion | Reason |
|---|---|
| Fewest locks held | Less to release and usually less work done. |
| Least work done so far | Less wasted effort when rolled back. |
| Youngest transaction (latest start) | Older transactions have invested more. |
| Fewest transactions to be rolled back with it | Avoids cascading effects. |
| Not chosen repeatedly | Prevents starvation of one transaction. |
Rollback
- Total rollback: abort the victim completely and restart it. Simple and most common.
- Partial rollback: roll back only as far as is needed to release the lock that breaks the cycle. Less wasted work, but the system must track more information.
After rollback, the victim’s locks are released, waiting transactions are given the locks, and the victim is usually restarted automatically, or an error is returned to the application so that it can retry.
4.5 Timeouts
A very simple method is to give each lock wait a time limit. If a transaction has waited longer than the limit, the DBMS assumes it is deadlocked and aborts it.
| Advantages | Limitations |
|---|---|
| Very easy to implement; no graph is needed. Works well when deadlocks are rare. | Difficult to choose a good limit: too short aborts transactions that were only slow; too long leaves real deadlocks unresolved. May abort innocent waiting transactions. |
4.6 Deadlock Prevention
Instead of detecting deadlocks, the DBMS can use rules that make them impossible.
(a) Conservative 2PL
A transaction acquires all its locks before it starts. If any lock is unavailable it waits holding nothing. It breaks the hold-and-wait condition. Drawback: the transaction needs to know in advance what it will access, and locks are held longer.
(b) Lock ordering
All data items are given a fixed order (for example, by account number), and every transaction must request locks in that order. A cycle is impossible because waits always go from lower to higher items. It breaks circular wait. Drawback: needs knowledge of what will be accessed.
(c) Priority-based schemes using timestamps
Each transaction gets a timestamp when it starts. An older transaction (smaller timestamp) has higher priority. Suppose Ti requests a lock held by Tj.
| Scheme | If Ti has higher priority (older) | If Ti has lower priority (younger) | Type |
|---|---|---|---|
| Wait-Die | Ti waits for Tj | Ti dies (is aborted and restarted) | Non-preemptive |
| Wound-Wait | Ti wounds Tj (Tj is aborted and restarted); Ti gets the lock | Ti waits for Tj | Preemptive |
- In both schemes, an aborted transaction is restarted with its original timestamp. Over time it becomes the oldest and gets the highest priority, so it cannot be starved.
- In both schemes, waits go in only one direction of age (Wait-Die: older waits for younger; Wound-Wait: younger waits for older), so a cycle cannot form.
- These schemes may abort transactions even when no deadlock would have happened.
Worked Example: Wait-Die and Wound-Wait
Situation: Timestamps: T1 = 10 (oldest), T2 = 20, T3 = 30 (youngest). A smaller timestamp means higher priority.| Case | Request | Wait-Die result | Wound-Wait result |
|---|---|---|---|
| 1 | T1 requests a lock held by T2 (older requests from younger) | T1 is older, so T1 waits | T1 is older, so T2 is wounded; T1 gets the lock |
| 2 | T3 requests a lock held by T1 (younger requests from older) | T3 is younger, so T3 dies | T3 is younger, so T3 waits |
| 3 | T2 requests a lock held by T3 | T2 is older, so T2 waits | T2 is older, so T3 is wounded |
4.7 Starvation and Livelock
| Term | Meaning | Example / remedy |
|---|---|---|
| Deadlock | Transactions wait for each other in a cycle; nobody progresses. | Detect and abort a victim, or prevent. |
| Starvation | A transaction waits indefinitely (or is aborted again and again) while others proceed. | A transaction always chosen as victim, or a writer kept waiting behind a stream of readers. Remedy: first-come-first-served lock queues; do not pick the same victim repeatedly; restart with the original timestamp. |
| Livelock | Transactions keep changing state (running, aborting, restarting) but make no useful progress. | Two transactions repeatedly abort each other. Remedy: use priorities and random back-off before restart. |
4.8 Comparison, Applications, Advantages and Limitations
| Basis | Detection and recovery | Timeout | Prevention (wait-die / wound-wait, ordering, conservative 2PL) |
|---|---|---|---|
| Idea | Allow deadlock; find cycle in wait-for graph; abort a victim. | Abort transactions that wait too long. | Rules make cycles impossible. |
| Overhead | Graph maintenance and periodic checks. | Very low. | Extra aborts, or advance knowledge of locks. |
| Unnecessary aborts | None (only real deadlocks). | Possible (false alarms). | Possible (aborts even when no deadlock). |
| Best when | Deadlocks are infrequent. | Simplicity is wanted. | Deadlocks are frequent or must be avoided. |
Since deadlocks are relatively rare in most workloads, many practical DBMSs prefer detection (wait-for graph) or timeouts over prevention.
Applications
- Banking: opposite-direction transfers between accounts.
- Order processing and inventory: orders that update the same stock rows in a different order.
- Reservation systems: multi-seat or multi-leg bookings that lock several records.
- Application design: programmers reduce deadlocks by accessing tables and rows in a consistent order and by keeping transactions short.
| Advantages of deadlock handling | Limitations |
|---|---|
| System keeps running instead of freezing. Detection aborts only when a real deadlock exists. Prevention schemes give guaranteed absence of deadlock. Timestamps give fairness (no starvation). | Aborted transactions waste work and must be restarted. Detection has overhead. Prevention may abort unnecessarily. Timeouts need careful tuning. |
Important Points for Revision
Difference Between Important Concepts
| Basis | Wait-Die | Wound-Wait |
|---|---|---|
| Older requests from younger | Older waits | Younger holder is aborted |
| Younger requests from older | Younger dies | Younger waits |
| Type | Non-preemptive | Preemptive |
| Basis | Deadlock prevention | Deadlock detection |
|---|---|---|
| When it acts | Before waits can form cycles | After a deadlock has formed |
| Cost | Possible unnecessary aborts | Graph checks; abort of victim |
| Typical use | Frequent conflicts | Most commercial DBMSs |
| Basis | Deadlock | Starvation |
|---|---|---|
| Cause | Circular wait | Unfair scheduling or repeated victim choice |
| Affected | A group of transactions | Usually a single transaction |
| Remedy | Abort a victim / prevent cycles | FCFS queues, original timestamp |
Chapter 4: Questions with Answers
A. Multiple Choice Questions (20)
B. Very Short Answer Questions (10)
C. Short Answer Questions (10)
D. Long Answer Questions (5)
Conditions. Four conditions must hold: mutual exclusion (X locks are exclusive); hold and wait (a transaction holds locks and waits for more); no preemption (locks released only voluntarily, at commit/abort under Strict 2PL); circular wait (a cycle of waiting transactions).
Example. T1 holds A and requests B; T2 holds B and requests A.
Wait-for graph. Nodes are active transactions. An edge Ti → Tj means Ti waits for a lock held by Tj. The lock manager adds edges when a request is blocked and removes them on release. A deadlock exists if and only if the graph has a cycle. In the example, T1 → T2 and T2 → T1 form a cycle.
Detection procedure. The graph is examined periodically (or when a transaction has waited long). If a cycle is found, a victim is chosen and aborted; its locks are released and the other transactions proceed (Figure 4.2).
Conclusion. Wait-for graph detection finds only real deadlocks, so it avoids unnecessary aborts.
Conservative 2PL. All locks are acquired before the transaction begins; if any is unavailable, it waits holding nothing. It breaks hold-and-wait but requires advance knowledge and reduces concurrency.
Lock ordering. Items have a fixed order and locks are requested in that order. Waits then always go to later items and circular wait is impossible.
Timestamp-based priority schemes. Each transaction gets a timestamp at start; older means higher priority. If Ti requests a lock held by Tj:
Wait-Die: if Ti is older it waits; otherwise Ti dies (aborts and restarts). It is non-preemptive.
Wound-Wait: if Ti is older it wounds Tj, which is aborted, and Ti gets the lock; otherwise Ti waits. It is preemptive.
Since waiting goes in only one direction of age, no cycle can form. An aborted transaction restarts with its original timestamp, so it eventually becomes the oldest and is not starved.
Example. T1 (ts 10), T2 (20), T3 (30). T1 requests a lock held by T2: Wait-Die: T1 waits; Wound-Wait: T2 is aborted. T3 requests a lock held by T1: Wait-Die: T3 dies; Wound-Wait: T3 waits.
Drawback. Transactions may be aborted even when no deadlock would have occurred.
Victim selection. The aim is to minimise cost. Criteria: fewest locks held, least work done, youngest, fewest other transactions that would have to be rolled back, and not the same transaction repeatedly (to avoid starvation).
Rollback. Total rollback aborts the victim completely and restarts it. It is simple and widely used. Partial rollback undoes only as much as needed to release the lock that breaks the cycle and then resumes; it wastes less work but needs more bookkeeping.
Starvation. If the same transaction is always the cheapest victim it may never finish. Including the number of previous rollbacks (or the original timestamp) in the cost solves this.
Example. In a cycle T1 → T2 → T3 → T1, T3 has done the least work and is aborted. T2 obtains the lock held by T3, completes, and then T1 completes. T3 is restarted.
Conclusion. Careful victim selection limits wasted work and keeps the system fair.
Timeout. Aborts any transaction that waits longer than a limit. Very simple and cheap, but may abort transactions that were only slow, and a poorly chosen limit leaves real deadlocks unresolved or causes false aborts.
Prevention. Conservative 2PL, lock ordering, Wait-Die and Wound-Wait ensure that cycles cannot form. No detection is needed. But they may abort transactions needlessly, or need advance knowledge of the locks required.
| Basis | Detection | Timeout | Prevention |
|---|---|---|---|
| Unnecessary aborts | None | Possible | Possible |
| Overhead | Graph checks | Minimal | Restarts or advance planning |
| Guarantee | Resolves deadlock after it forms | Resolves eventually | No deadlock |
Detection and recovery. The detector finds the cycle and picks a victim, say T3 (least work). T3 is rolled back, releasing C. T2 gets C, completes and releases B. T1 gets B and completes. T3 restarts later.
Timeout. After the time limit expires, the transaction that has waited longest (or any waiting one) is aborted; the others continue as above. A slow but not deadlocked transaction might also be aborted by mistake.
Wait-Die (timestamps T1 = 10, T2 = 20, T3 = 30). T1 requests B held by T2: T1 is older, so it waits. T2 requests C held by T3: T2 is older, so it waits. T3 requests A held by T1: T3 is younger, so it dies; its lock on C is released and the cycle never forms.
Wound-Wait. T1 requests B held by T2: T1 is older, so T2 is wounded and aborted; T1 gets B. T3 requesting A (held by T1) waits as it is younger. No cycle forms.
Lock ordering. If all transactions lock in the order A, B, C then T3 would request A before C, and no cycle can occur.
Conclusion. Every approach breaks the cycle by aborting or avoiding a wait, but at different cost.
E. Application-Based Questions (5)
Chapter 4 Assessment (Total 30 marks)
Section A: MCQs (10 × 1 = 10 marks)
2. A cycle in the wait-for graph means: (A) Commit (B) Deadlock (C) Checkpoint (D) Latch
3. Wait-Die: a younger requester: (A) Waits (B) Dies (C) Wounds the holder (D) Commits
4. Wound-Wait: an older requester: (A) Waits (B) Dies (C) Wounds the holder (D) Is ignored
5. The chosen transaction to abort is the: (A) Victim (B) Leader (C) Parent (D) Coordinator
6. Fixed lock ordering prevents: (A) Circular wait (B) Mutual exclusion (C) Logging (D) Commit
7. Livelock means: (A) No transactions (B) Transactions active but no progress (C) Disk failure (D) Log overflow
8. A disadvantage of timeouts: (A) Needs a graph (B) May abort non-deadlocked transactions (C) Impossible to implement (D) Always prevents deadlock
9. Restarted transactions keep their: (A) New timestamp (B) Original timestamp (C) No timestamp (D) Random timestamp
10. Which prevention method locks everything in advance? (A) Conservative 2PL (B) Strict 2PL (C) Wait-Die (D) Timeout
Section B: Short answers (3 × 3 = 9 marks)
12. Differentiate Wait-Die and Wound-Wait.
13. Why can a long wait not always be treated as a deadlock?
Section C: Descriptive (2 × 5.5 = 11 marks)
15. T1 (ts 10), T2 (ts 20), T3 (ts 30). T1 holds X(A), T2 holds X(B). T2 requests A, then T3 requests B, then T1 requests B. Show what happens under Wait-Die. (5.5)
Answer Key
Q11: Mutual exclusion, hold and wait, no preemption, circular wait.
Q12: Wait-Die: older requester waits, younger requester dies (non-preemptive). Wound-Wait: older requester aborts the holder, younger requester waits (preemptive).
Q13: A transaction may be waiting for a slow but active transaction that will finish; only a cycle proves deadlock. Timeouts may therefore abort healthy transactions.
Q14: See L1 and L3. Award 2 marks for graph and cycle, 2 for victim criteria, 1.5 for rollback and restart.
Q15: T2 (ts 20) requests A held by T1 (ts 10): T2 is younger, so T2 dies and releases B. T3 requests B: B is now free (T2 released it when it died), so it is granted. T1 requests B held by T3 (ts 30): T1 is older, so it waits. When T3 commits, T1 gets B. T2 restarts with timestamp 20. No deadlock arises. Award marks for each step with the age comparison.
Quick Revision: Chapter 4
- Deadlock: each transaction in a set waits for a lock held by another in the set. Needs mutual exclusion, hold and wait, no preemption and circular wait.
- Wait-for graph: nodes are transactions; Ti → Tj means Ti waits for Tj. Deadlock if and only if there is a cycle.
- Recovery: choose a cheap victim (few locks, little work, youngest), roll back (total or partial), restart; avoid choosing the same victim repeatedly.
- Timeouts: simple but may abort healthy transactions.
- Prevention: conservative 2PL, lock ordering, Wait-Die (younger requester dies), Wound-Wait (older requester wounds holder); restart with original timestamp.
- Starvation: indefinite waiting or repeated abort. Livelock: active but no progress.
- Many commercial DBMSs use detection or timeouts, since deadlocks are relatively rare.
2. Explain deadlock prevention: Wait-Die and Wound-Wait.
3. How is a victim selected and how is rollback done?
4. Compare detection, timeout and prevention.
5. Distinguish deadlock, starvation and livelock.
Next: Chapter 5 – Transaction Support in SQL and Introduction to Crash Recovery
Reference books: R. Ramakrishnan & J. Gehrke, Database Management Systems; Silberschatz, Korth & Sudarshan, Database System Concepts; Elmasri & Navathe, Fundamentals of Database Systems.


0 Comments
If you have any doubts let me know