5.2 Log Records and the Log Buffer

The solution is to keep one more record, separate from the data pages, that describes "what was changed and how." This record is the log. Consider how the transfer transaction in the table below is processed.

StepAction
1Transaction T1 starts
2Hong Gildong's balance on page 17: 500,000 → 400,000
3Kim Cheolsu's balance on page 42: 200,000 → 300,000
4Transaction T1 commits

The page numbers and values are the same hypothetical values used in Section 5.4.

Figure 5-1a. Time order of statement execution and log file writes in a transfer transaction

sequenceDiagram
  participant S as Session T1
  participant BP as Buffer pool
  participant LB as Log buffer
  participant LF as Log file (disk)
  S->>LB: 1. Append T1 start record
  S->>BP: 2. Page 17 Hong Gildong 500k → 400k
  S->>LB: 2. Append change log record
  S->>BP: 3. Page 42 Kim Cheolsu 200k → 300k
  S->>LB: 3. Append change log record
  S->>LB: 4. Append commit record
  LB->>LF: Write records 1-4 to the end of the file in order
  LF-->>S: Disk write complete
  Note over S: Respond to the user: commit complete

The vertical lines are, from the left, the session executing the statements, the buffer pool (memory), the log buffer (memory), and the log file (disk). Time flows from top to bottom.

  1. When the transaction starts, a start record is appended to the log buffer.
  2. The first UPDATE modifies page 17 in the buffer pool and appends a log record describing the same change to the log buffer.
  3. The second UPDATE does the same for page 42. During steps 1 to 3, nothing is written to disk.
  4. When COMMIT arrives, a commit record is appended to the log buffer, and records 1 to 4 accumulated so far are written to the end of the log file in order. Only after the disk write completes does the session respond to the user that the commit is done.

Pages 17 and 42 in the buffer pool never go to disk anywhere in this figure. The only thing written to disk at commit time is the log.

When a transaction runs, a log record is created for each operation such as an insert, delete, or update, before the change is applied to the page. A log record passes through two stages before it reaches disk.

The first stage is that the session executing the statement records the change in the in-memory log buffer. The session handling the user's UPDATE (the process or thread in the database responsible for that connection) modifies page 17 in the buffer pool and, at the same time, creates a log record saying "on page 17, the balance of Hong Gildong's record: 500,000 → 400,000" and appends it to the end of the log buffer. Writing to the log buffer is a memory write, so it finishes much faster than a disk write.

Figure 5-1b. How log records from multiple sessions pass through the shared log buffer and accumulate at the end of the log file

flowchart LR
  SA["Session A"]
  SB["Session B"]
  SC["Session C"]
  subgraph LB ["Log buffer: shared by the instance, in memory"]
    direction LR
    R1["A change 1"] --> R2["B change 1"] --> R3["C change 1"] --> R4["A commit"] --> R5["B change 2"]
  end
  SA --> R1
  SB --> R2
  SC --> R3
  R4 -->|"On A's commit, everything up to here<br/>is appended as one range"| LF["End of log file"]
  W["Log writer thread<br/>usage threshold or elapsed time"] -.->|"Periodic write"| LF

Sessions A, B, and C on the left each run their own transactions, but all of their log records are appended to the end of one shared log buffer in the order they were created. The arrows inside the buffer show that order.

When session A commits, everything from the start of the log buffer through the A commit record is written to the end of the log file as one range. This range also includes the uncommitted records of B and C interleaved before it (B change 1, C change 1). Records accumulated after it, such as B change 2, go to disk at the next write. The dotted line is the log writer thread, the other agent that writes the log buffer to disk regardless of commits.

The log buffer is not allocated per session. It is a shared buffer belonging to one database instance. When sessions A, B, and C run transactions concurrently, their log records are written to the end of the buffer in order.

The second stage is to append the contents of the log buffer to the end of the on-disk log file, preserving order. Log buffer records are never stored in the log file out of order. When writing to disk, the database uses a pointer into the log buffer and writes in ranges. So when session A commits, B's uncommitted records that precede it are written to disk as well. Suppose the database terminates abnormally after the log file has received records only up to A's commit record, and B's commit record that follows was never written to the log file. Then B's transaction is judged incomplete and is rolled back during restart.

Records are never inserted into the middle of the log file, and earlier records are never modified. When the database writes the log buffer to the log file, it tracks how far it has written. Uncommitted records written to disk this way become targets of rollback (Undo, Section 5.4) after a failure, and the log written to disk is used to restore the data. Group commit, which combines several commits into one disk write (Chapter 6), is also possible thanks to this structure.

Two agents write the log buffer to the log file. One is the database's dedicated log-writing thread, whose name varies by DBMS: WAL writer in PostgreSQL, the log write thread in InnoDB, LGWR in Oracle, and log writer in SQL Server. This thread writes the log buffer to the log file and cleans up the buffer when buffer usage exceeds a threshold or a set time has passed since the last log write. The other is the committing session. When a transaction commits, it writes to the log file immediately, regardless of the interval or buffer usage.

When a session requests COMMIT, it must be guaranteed that the commit record has been safely written to disk, so the session responds to the user only after the write completes. In Figure 5-1a, the records of steps 1 to 3 stay in the log buffer and are written to the log file (disk) at the commit in step 4. This is exactly that behavior.

Figure 5-1c. Difference in response behavior between ordinary statements and COMMIT

sequenceDiagram
  participant S as Session
  participant LB as Log buffer
  participant LF as Log file (disk)
  S->>LB: Append UPDATE log record
  LB-->>S: Immediate completion response
  Note over S,LB: Asynchronous. Does not wait for a disk write
  S->>LB: Append INSERT log record
  LB-->>S: Immediate completion response
  S->>LB: COMMIT: append commit record
  LB->>LF: Write up to the commit record to disk
  Note over S,LF: Synchronous. Waits until the disk write completes
  LF-->>S: Write complete
  Note over S: Respond to the user: commit complete

The upper two statements (UPDATE, INSERT) get a completion response as soon as their records are appended to the log buffer. The arrows do not reach the log file. The COMMIT at the bottom appends the commit record to the log buffer, waits until the log file write finishes, and responds only after the write completion returns. Most of a transaction's latency arises in this last segment.

Ordinary statements such as UPDATE and INSERT write only to the log buffer (memory) and immediately send a completion response to the session. The disk write is handled later by the log-writing thread or by another session's commit. The session does not wait for the disk write to complete, so it is asynchronous with respect to disk. Whether these statements' logs reached disk does not need to be checked, because if the database terminates abnormally before commit, those changes would be rolled back anyway. COMMIT, by contrast, is synchronous: it waits until the commit record has been written to the log file and the disk write has completed, and then responds. So even if several UPDATEs in a transaction finish quickly, the final COMMIT adds a delay of one disk write. This delay largely determines the database's TPS (transactions per second). Chapter 6 covers how to reduce this delay (fsync, group commit) and how to make COMMIT asynchronous too (Durability settings).

Why Log Writes Are Faster Than Data Page Writes

Hard disk: A hard disk reads and writes by moving a head over a spinning platter to locate a position. One write takes the time to move the head to the target track (seek), the time to wait for the desired position to rotate under the head (rotational latency), and the time to actually write the data (transfer). Seek and rotational latency are each several milliseconds, whereas transferring 8KB takes far less. Each random write incurs a seek and rotational latency, so the limit is about 200 to 500 writes per second. Log records are always appended to the end of the file, so there is no seek or rotational latency. Even when writing the same 8KB, the difference is 10 to 100 times.

SSD: An SSD has no head and therefore no seek time, and random writes are hundreds of times faster than on a hard disk. Sequential writes are still advantageous, because of the characteristics of flash memory. Flash differs in the unit it writes (a flash page of several KB to tens of KB) and the unit it erases (a block of several MB), and it cannot overwrite a location that has already been written; it must be erased before being written again. So the SSD's internal management software (the FTL) writes modified data to new free space and marks the old space invalid. For a block where invalid data has accumulated, it moves the live data elsewhere and then erases the whole block (garbage collection). When random writes scatter across the whole SSD, each block holds a mix of live and invalid data, which increases the amount of data that must be moved at each erase. This phenomenon, where the amount the device actually writes exceeds the amount the user wrote, is called write amplification. When random writes continue for a long time, it causes slowdown and shortens device life.

Sequential appends, by contrast, fill blocks in order from the beginning, and old logs are erased together in whole ranges, which fits how an SSD works well.

Device4KB random writesSequential writesMain cause of the difference
Hard disk (7,200rpm)Hundreds per second (a few MB/s)Hundreds of MB/sHead seek and rotational latency
SATA SSDTens of thousands per secondHundreds of MB/sFixed cost per request, write amplification
NVMe SSDHundreds of thousands per second or moreSeveral GB/sWrite amplification, garbage collection under sustained load

Table 5-A. Random vs. sequential write performance by device

As the table shows, since SSDs the gap between random and sequential writes is smaller than on hard disks. However, what matters for a database commit is not throughput but the time it takes to get confirmation that the write completed. If data pages were written directly, each commit would have to send scattered write requests, one for each page the transaction modified, and wait for all of them to complete, whereas the log is written to the end of the file in one batch. This is why a design that reduces the number of requests and combines them into one write remains advantageous even as the medium gets faster. This principle is also the starting point for column stores (Chapter 15) and for storage engine designs that manage even data pages with sequential writes only (LSM trees and the like).