Sub topic 1
What a Transaction Is and How It Moves Through Its States
Prerequisites
This chapter assumes you already know the following:
- Basic relational database ideas: tables, rows, and queries.
- Simple SQL statements such as
SELECT,UPDATE, andINSERT. - Directed graphs, which later chapters use for precedence and wait-for graphs. This chapter does not need them.
You do not need any prior knowledge of concurrency control. This chapter sets up the vocabulary that the rest of the tutorial relies on.
What a transaction is
A transaction is a unit of work made of one or more database operations. The database treats the whole unit as a single logical step. Either all of its effects become permanent, or none of them do.
The standard example is a bank transfer of 100 from account A to account B. In terms of operations it looks like this:
- Read A.
- Subtract 100 from A.
- Write A.
- Read B.
- Add 100 to B.
- Write B.
If the system fails after step 3 and before step 6, 100 has disappeared from the database. A transaction exists to prevent that. The system must either complete all six steps or undo the effects of the steps already done.
In GATE questions, a transaction is usually written as a sequence of R(X) and W(X) operations. R(X) reads data item X from the database into a local buffer. W(X) writes a value from the local buffer back to the database. The transfer above becomes:
R(A); A = A - 100; W(A); R(B); B = B + 100; W(B); COMMITThe arithmetic happens in the transaction's local memory. Only reads, writes, and the final commit or abort matter for scheduling, so later chapters drop the arithmetic.
A data item
A data item is whatever unit the database system locks or versions. It can be a row, a page, or a whole table. In theory problems the data items are simply named variables such as A, B, X, and Y. Later chapters on multiple granularity locking return to the choice of unit.
Transaction boundaries in SQL
In SQL you mark the boundaries yourself. BEGIN (or START TRANSACTION) opens a transaction. COMMIT ends it successfully. ROLLBACK ends it by undoing its work.
BEGIN;
UPDATE account SET balance = balance - 100 WHERE id = 1;
UPDATE account SET balance = balance + 100 WHERE id = 2;
COMMIT;Many systems run in autocommit mode by default. In that mode each statement is its own transaction, and it commits as soon as it finishes. A transfer written as two separate statements in autocommit mode is therefore two transactions, and the guarantee of all-or-nothing no longer covers the pair.
Why the database needs a model of transactions
Real systems run many transactions at once. Running them one at a time would be correct but slow, because the disk and the CPU would sit idle while a transaction waits for I/O. Interleaving operations from different transactions improves throughput and reduces average waiting time. It also creates the risk that one transaction sees or overwrites the half-finished work of another.
Two components of the DBMS handle this. The concurrency control manager decides how operations from different transactions may interleave. The recovery manager makes sure that failures leave the database with either the full effect of a transaction or none of it. The transaction states below describe the points at which these two components take over.
The states of a transaction
A transaction is always in exactly one of five states.
| State | Meaning |
|---|---|
| Active | The initial state. The transaction is executing its reads and writes. |
| Partially committed | The final operation has executed, but the results may still be only in main memory buffers. |
| Committed | The transaction has finished successfully and its effects are guaranteed to be permanent. |
| Failed | Normal execution cannot continue, either because of an error in the transaction or because the system decided to stop it. |
| Aborted | The transaction has been rolled back and the database is restored to its state before the transaction began. |
The following diagram shows the allowed moves between these states.
Active
The transaction starts here and stays here while it reads and writes. Writes in this state change data in buffers and write log records, but they are not yet permanent.
Partially committed
The transaction enters this state after its last statement runs. It has not yet committed, because the database cannot promise durability until the log records for the transaction are safely on stable storage. A crash right now could still lose the work, so the transaction is not safe.
Committed
Once the system has forced the needed log records to disk, the transaction is committed. From here on, a system crash cannot undo it. If the application wants to reverse a committed transaction, it must run a new transaction, called a compensating transaction, that undoes the effect. The database itself never rolls back a committed transaction.
Failed
A transaction can fail from the active state or from the partially committed state. Common causes are:
- A logical error, such as division by zero or a violated integrity constraint.
- A system error, such as a deadlock that forces the system to pick a victim.
- A system crash, such as a power loss that wipes main memory.
- A failure while writing the commit information to disk.
Aborted
After the failure, the system rolls the transaction back and restores the data items it changed. The transaction is then aborted. The system has two choices afterward:
- Restart the transaction. This is allowed only if the failure was caused by something other than a logical error in the transaction, for example a deadlock victim. The restarted transaction counts as a new transaction.
- Kill the transaction. This is the correct choice after an internal logical error, because rerunning the same code would fail the same way.
Terminated
Some textbooks add a sixth word, terminated, for a transaction that has either committed or aborted and has left the system. It describes the same end points as the two terminal states in the diagram, so it does not add a new state to the five-state model that GATE uses.
Why partially committed is a separate state
The most frequent confusion is between "the last statement ran" and "the transaction committed". They differ because of how a DBMS handles disk writes.
The DBMS keeps recently changed data in a buffer in main memory and writes it to disk later. If a transaction counted as committed as soon as its last statement ran, a crash could erase changes that the user had been told were saved. The DBMS avoids this by following the write-ahead logging rule: before a transaction commits, its log records, including a commit record, must be written to stable storage. The data pages themselves can reach the disk later, because the log is enough to redo them after a crash.
So the move from partially committed to committed happens when the commit record is safely in the log. The move from partially committed to failed happens if that write cannot be completed.
Tracing two transactions through the states
Consider two transactions running at once. T1 transfers 100 from A to B. T2 divides a value by a variable that happens to be zero.
- Both start in the active state.
- T1 runs its last write, moves to partially committed, the log is forced, and T1 moves to committed.
- T2 raises a divide-by-zero error while active. It moves to failed.
- The system undoes any writes T2 made, and T2 moves to aborted.
- Because the cause was a logical error in T2, the system does not restart it.
The final database contains the effect of T1 and no effect of T2. This outcome is what the atomicity property of the next chapter requires.
Operations that matter to the scheduler
For the rest of the tutorial, each transaction is a sequence of these operations:
| Operation | Meaning |
|---|---|
| `R(X)` | Read data item X. |
| `W(X)` | Write data item X. |
| `C` | Commit. |
| `A` | Abort. |
A transaction ends with exactly one of C or A. A schedule, which later chapters define, is an interleaving of the operations of several transactions that keeps each transaction's own operations in their original order.
# A transaction is an ordered list of operations.
T1 = [("R", "A"), ("W", "A"), ("R", "B"), ("W", "B"), ("C", None)]
T2 = [("R", "A"), ("W", "A"), ("C", None)]
def ends_properly(txn):
# A well-formed transaction ends with exactly one commit or abort.
ends = [op for op, _ in txn if op in ("C", "A")]
return len(ends) == 1 and txn[-1][0] in ("C", "A")
print(ends_properly(T1)) # True
print(ends_properly(T2)) # True
print(ends_properly([("R", "A"), ("W", "A")])) # FalseCommon errors
- Treating the partially committed state as committed. Only the committed state guarantees that the effects survive a crash.
- Believing that a committed transaction can be rolled back. Only a compensating transaction can reverse it.
- Drawing an arrow from committed to aborted, or from aborted to committed. Both are terminal.
- Drawing an arrow from partially committed to active. No arrow goes back to active. A restart creates a new transaction.
- Forgetting that a transaction can fail from the partially committed state, not only from active.
- Assuming every aborted transaction is restarted. The system restarts only when the cause is not an internal logical error.
Summary
A transaction is a logical unit of work that the database executes as a whole or not at all. It is modeled as reads and writes followed by a commit or an abort. It moves through five states: active, partially committed, committed, failed, and aborted. The step from partially committed to committed depends on the log reaching stable storage. The next chapter uses this model to define the ACID properties.
Exercise
A transaction has executed its last statement, and its log records have not yet been forced to disk. The system loses power. Which state was the transaction in, which state does it reach after recovery, and can the system restart it?
Show answer
The transaction was in the partially committed state, because its last statement had run but the commit was not yet durable. After the crash it moves to failed and then to aborted, and recovery undoes any of its changes that reached disk. The system may restart it as a new transaction, because the cause was a system failure and not a logical error in the transaction.
Exercise
State whether each transition is allowed in the transaction state diagram: (a) Active to Committed, (b) Partially committed to Failed, (c) Failed to Active, (d) Committed to Aborted.
Show answer
(a) Not allowed, because the transaction must pass through partially committed first. (b) Allowed, for example when writing the commit record to disk fails. (c) Not allowed, because a restart creates a new transaction instead of reviving the failed one. (d) Not allowed, because committed is terminal and only a compensating transaction can reverse the effects.