6.5 Restart Recovery
Putting together WAL, fsync, and checkpoints, what the server does at restart can be explained. A server that lost power and came back on does the following before accepting user requests.
- It finds the position of the last checkpoint in the log. Changes before it are already in the data pages, so they are not examined.
- It reads from the checkpoint to the end of the log and determines which transactions committed and which were cut off without a commit record.
- It reapplies the changes of committed transactions to the data pages (Redo). This is how the contents of dirty pages that could not be written to disk are restored.
- It reverses the changes of uncommitted transactions (Undo). If any dirty pages had been written to disk before commit, this returns them to their original state.
Restart recovery steps
flowchart TB
S["Server restart"] --> A["① Find the last checkpoint position"]
A --> B["② Read from the checkpoint to the end of the log<br/>check the commit record of each transaction"]
B --> C["③ Redo<br/>reapply changes of committed transactions"]
C --> D["④ Undo<br/>reverse changes of uncommitted transactions"]
D --> E["Start accepting user requests"]
C -.->|"Apply only log records<br/>after the page LSN"| P["Data page"]
This is the order in which recovery proceeds, from top to bottom. In ①, the reading start point is determined, and in ②, the log after the checkpoint is scanned and the transactions are split into committed ones and cut-off ones. ③ is Redo for committed transactions, and ④ is Undo for uncommitted transactions. The server accepts user requests only after ④ finishes. The dotted line means that in ③ the LSN in each data page header is checked, and only log records not yet reflected in that page are applied (explained below).
When this process finishes, the data pages are in the state of "everything committed is reflected, and nothing uncommitted is reflected." The atomicity and durability described in Chapter 4 have been kept even after the power cut. A transfer whose user received the commit complete response remains, and a transfer whose user did not receive it becomes as if it never happened.
One question remains here. If a change already reflected on disk is applied again in step 3, would it not be applied twice? Some dirty pages were surely written to disk after the checkpoint, so would reapplying the log to those pages not deduct the balance twice? What solves this is the LSN that Section 1.2 said is written in the page header. A page records "the position in the log up to which this page has been reflected," so recovery applies only log records after that. The concrete behavior of this comparison, and why it is safe even if the power fails again during recovery, are covered in Chapter 10.