Chapter 4. What Is a Transaction?

User A sends 100,000 won to user B. In a banking system, a single transfer requires two record changes in total: subtract 100,000 won from user A's balance and add 100,000 won to user B's balance. If the two users' records are stored in different pages, both the page holding A's record and the page holding B's record must be modified.

Suppose the server loses power and terminates abnormally right after the first page change finishes and just before the second begins. When the database server starts again, only user A's balance has been reduced by 100,000 won, and user B's balance is unchanged. The 100,000 won has vanished into thin air. Had the order been reversed, 100,000 won would have appeared from nowhere. In a bank, the total amount must neither shrink nor grow because of a transfer. Either way, a bank cannot tolerate even one such state.

Figure 4-1. Failure during a transfer: two pages where only the withdrawal was applied and the deposit was not

flowchart TB
  S["Transfer request<br/>User A → User B, 100,000 won"]
  S --> W1["① Change page 1<br/>User A balance −100,000 won"]
  W1 --> X["② Power loss<br/>Server terminates abnormally"]
  X -.->|"Never executed"| W2["③ Change page 2<br/>User B balance +100,000 won"]
  X --> R["④ Server restarts"]
  subgraph after ["Data after restart"]
    P1["Page 1<br/>User A: 100,000 won deducted"]
    P2["Page 2<br/>User B: unchanged"]
  end
  R --> P1
  R --> P2
  P1 --> L["Total of all balances is 100,000 won lower"]
  P2 --> L

Read the diagram top to bottom in time order. One transfer request splits into two changes to two pages. In ①, page 1, which holds user A's record, is changed first and the balance drops by 100,000 won. Right after that, the server loses power in ②, so the change to page 2, which holds user B's record (③, shown with a dotted line), is never executed.

When the server restarts in ④, page 1 shows the deduction and page 2 is as it was before, as in the box below. Taken together, the two pages leave the bank's total balance 100,000 won lower. Had the change order been reversed, only page 2 would have been applied and the total would be 100,000 won higher. Either way, the problem is that an intermediate state, with only one of the two changes applied, remains on disk.

To prevent such accidents, databases provide a feature called a transaction. A transaction groups multiple record changes into a single change. The database guarantees that either all updates belonging to the transaction are applied or none are. This property is called atomicity. A transaction is the smallest unit of change that cannot be divided further. Part 2 explains how the transaction feature works. It also explains why, even when multiple sessions update the same record concurrently, the changes can be applied without loss.