5.3 The Rule That the Log Is Written Before Data Pages

Having a log file is not enough to guarantee data consistency. To reconstruct or recover data from the log, the write order matters. To go back to a point in time and cancel a transaction, or to finish writing what never reached disk, log records must be written to disk in order and before the data file. If the order of data page writes and WAL writes is reversed, the data is corrupted and cannot be recovered. As the name (Write-Ahead Log) says, the log record must always be written first.

The WAL rule comes down to two lines.

  1. For any change, the modified data page is not written to disk until the log that records the change has been safely stored on disk.
  2. A transaction is considered committed only at the moment its commit record has been safely stored on disk.

Figure 5-2. The order of WAL

flowchart TB
  S1["① Modify the page in the buffer pool<br/>it becomes a dirty page"]
  S2["② Write the log record to the log buffer"]
  S3["③ COMMIT: store the log on disk"]
  S4["Commit complete response"]
  S5["④ Write the dirty page to the data file<br/>long after, regardless of the commit"]
  S1 --> S2 --> S3 --> S4
  S3 -.->|"A background thread or process<br/>writes periodically"| S5

This is the write order for one transaction, from top to bottom.

  1. In ①, the session modifies a page in the buffer pool, and that page becomes a dirty page.
  2. In ②, the same change is made into a log record and appended to the log buffer. Everything up to here is memory work.
  3. In ③, at COMMIT the log is stored on disk, and the commit complete response goes out only after that finishes (rule 2).
  4. In ④, the dirty page is not on the solid path. As the dotted line shows, it is written to the data file later, regardless of the commit response, and only when its log is already on disk (rule 1).

At commit time, only the log is written to disk. The actual data pages are flushed to disk periodically by background threads or processes, independent of commits. This rule is why Section 1.5 could say that dirty pages do not need to be written to disk immediately.

5.3.1 Torn Pages

A torn page arises when the unit that the operating system and disk device write atomically does not match the page unit the database manages, so page writes are not atomic. The WAL rule of writing the log first cannot prevent this problem by itself.

Figure 5-2b. How one page gets corrupted: an 8KB write is split into two 4KB writes, and the power fails between them

flowchart TB
  A["(1) DBMS · write(page, 8KB)"] --> W1["(2) device · 4KB write #1 · bytes 0-4KB · done"]
  A --> W2["(2) device · 4KB write #2 · bytes 4-8KB · not done"]
  P(["power off"]) -.-> W2
  W1 --> D1["(3) page on disk · bytes 0-4KB · header (LSN = new) · slot directory (new)"]
  W2 -. "never written" .-> D2["(3) page on disk · bytes 4-8KB · records (old)"]
  class A meta
  class W1,D1 hot
  class W2,P warn
  class D2 muted

(1) to (3) in the figure correspond to ① to ③ in the text. In ①, the database requests that one 8KB page be written in a single operation. In ②, the disk device handles this as two 4KB writes, and the power fails with only the first write finished. ③ is the page left on disk as a result. The header and slot directory in the first 4KB are updated, but the record area in the last 4KB is still the old content.

Reading this page, the positions and count of records that the slot directory points to may not match the actual record area. Recovery runs into a bigger problem. The LSN in the header is the latest value, so the recovery process concludes that all changes have already been applied to this page and skips Redo.

The page size is 8KB in PostgreSQL, SQL Server, and Oracle (default), and 16KB in InnoDB. A page write passes in turn through the operating system's page cache (usually in 4KB units), the file system, and the disk controller. The only unit in which a disk device guarantees atomic writes is the sector (512 bytes or 4KB), so one 8KB page is several sector writes from the device's point of view. The order in which sectors are written is not guaranteed either. If the power suddenly fails, only some sectors of a page may have been updated.

Why the log alone cannot fix it. A log record is usually not a whole page but a small change that points to a location within a page, such as "on page 17, set the balance of the record in slot 3 to 400,000." To reapply such a record, the slot directory must point to the right record. In other words, the page must at least be in an intact state from some point in time. A torn page is in the state of no point in time, so there is no base on which to apply the log.

The problem of corruption going undetected because of the LSN. The page header holds "the position (LSN) of the last log record applied to this page," and the recovery process uses this value to skip changes that were already applied. If only the leading sector holding the header was written with new content, the header's LSN is the latest but the records behind it hold old values. Recovery skips Redo, and the corruption remains.

First countermeasure: detect the tear. Most DBMSs put a checksum on pages. It is computed and stored when the page is written to disk, and recomputed and compared when it is read. If only some sectors changed, the values disagree, so a torn page can be noticed. In addition, InnoDB and Oracle put the same value (part of the log position) at the very start and very end of the page, and judge the page torn if the two values differ. SQL Server's older method (TORN_PAGE_DETECTION) kept a marker bit for each 512-byte sector and checked that all of them matched; today the checksum (PAGE_VERIFY CHECKSUM) is the default. Detection alone cannot fix anything, though. To fix a page, an intact copy must exist.

Second countermeasure: keep an intact copy separately. Here the DBMSs diverge (Figure 5-2a).

Figure 5-2a. Torn page countermeasures: PostgreSQL keeps the intact copy in the log, InnoDB in a separate area

flowchart TB
  subgraph PG ["PostgreSQL: full page write"]
    direction TB
    P1["First modification of a page after a checkpoint"] --> P2["Write the full page image to WAL"]
    P2 --> P3["Until the next checkpoint, the same page<br/>gets only small change records"]
    P3 --> P4["Recovery: overwrite the page with the full image,<br/>then apply later records"]
  end
  subgraph INNO ["InnoDB: doublewrite buffer"]
    direction TB
    I1["Write several dirty pages to the doublewrite area<br/>sequentially in one batch"] --> I2["Confirm completion with fsync"]
    I2 --> I3["Write each page to its place<br/>in the tablespace"]
    I3 --> I4["Recovery: if the in-place page checksum is wrong,<br/>replace it with the doublewrite copy, then Redo"]
  end

The left side is PostgreSQL and the right side is InnoDB. Both approaches share the goal of never applying the log on top of a torn page, and differ in where the intact copy is kept.

  • PostgreSQL: The copy is inside WAL. A page modified for the first time after a checkpoint has its full image placed in WAL, so recovery starts by overwriting the page with that image, regardless of whether the page on disk was torn.
  • InnoDB: The copy is in the doublewrite area. Data is written twice, and the second write (the in-place write) starts only after the fsync of the first write has finished. So wherever the power fails during either write, one of the two copies is intact.

PostgreSQL keeps the copy in the log. When a page is modified for the first time after a checkpoint (Chapter 6), a full page image is written to WAL instead of a small change record (the full_page_writes setting). After that, further changes to the same page leave only small records until the next checkpoint. Recovery starts from a checkpoint, so even a page that may have been torn is first overwritten entirely with the full image from WAL, and the following records are then applied. Using a torn page as a base never happens. The cost is log volume. Right after a checkpoint, almost every page being modified is being modified for the first time, so WAL grows suddenly; this burden is tuned with the checkpoint interval and WAL compression (wal_compression).

InnoDB keeps the copy in a separate area. When flushing dirty pages to disk, it first writes several pages sequentially in one batch to the doublewrite area and confirms completion with fsync, then writes each page to its place in the tablespace. If the power fails during the in-place write, an intact copy is in the doublewrite area; if it fails during the doublewrite write, the existing page in place is intact. Whenever the power fails, one side is intact. During recovery, if the in-place page's checksum is wrong, it is replaced with the doublewrite copy and then Redo is applied. Data is written twice, but the first write is a batched sequential write (Table 5-A in Section 5.2), so the burden is smaller than it might seem.

SQL Server and Oracle do not keep a separate copy during normal writes. When a checksum detects a tear, they fix only that page by fetching it from a backup and bringing it up to date with the log (SQL Server page restore, Oracle RMAN block-level recovery). In exchange, they are often operated on the premise that the storage device guarantees page-sized writes are not interrupted (for example, storage with a battery-protected write cache). For the same reason, on a file system that guarantees atomic writes such as ZFS, PostgreSQL's full_page_writes or InnoDB's doublewrite is sometimes turned off. Turning it off reduces writes, but if it is turned off without verifying that the guarantee actually exists, there is no way left to repair a torn page.

DBMSTear detectionIntact copyRecovery method
PostgreSQLData checksums (initdb option)Full page image in WALOverwrite with the image, then Redo
MySQL InnoDBPage checksum, comparison of leading and trailing valuesDoublewrite areaReplace with the copy, then Redo
SQL ServerPAGE_VERIFY CHECKSUM (older method: TORN_PAGE_DETECTION)None in normal operationRestore the page from backup, then apply the log
OracleBlock checksum, comparison of leading and trailing block valuesNone in normal operationRMAN block-level recovery

Learn more — full_page_writes, InnoDB doublewrite buffer, PAGE_VERIFY

Table 5-3a. Torn page countermeasures by DBMS

NOTE Setting names, defaults, and detailed behavior of each product may differ by version.

Can the log file be torn too? Yes. If the power fails while the log is being written, the last block may be half written. But the log carries a checksum on each record (or each block), so recovery accepts the log only up to the last record whose checksum is valid. The records in the torn tail had not finished their disk write, so no response was sent for those commits either (Section 5.2). The log of any transaction whose user received a commit complete response is already intact on disk, so nothing is lost. The log structure that is only appended to the end of the file helps here as well.