Highlights

Contents

Part IX
09

Recovery and storage engines

A committed booking must survive its promised failures. Logs and recovery establish that boundary. Buffer management and storage structures make separate choices about residency, writes, and later cleanup.

CHAPTER ATLAS / FOLLOW THE READING PATHCHAPTER ATLAS / FOLLOW THE READING PATH1Database model2Keys and ER3Algebra and SQL4Dependencies5Storage and indexes6Query execution7Transactions8Concurrency control9Recovery and engines10Distributed databases11Application design12The complete query

#Section 44Write-ahead logging and crash boundaries

Asha’s booking can commit while its data page remains dirty in RAM. Recovery needs durable evidence to preserve that acknowledgement after power loss.

Write-ahead logging, or WAL, records recovery information before the corresponding changed data page is allowed to reach persistent storage. A log record describes an operation with the information needed by the engine’s recovery method. A dirty page is a cached page changed relative to its backing copy. The central ordering rule is about durable log data preceding durable page data, not merely appending bytes to a userspace buffer.

THE RECOVERY RECORD MUST REACH STORAGE BEFORE ITS DEPENDENT PAGETHE RECOVERY RECORD MUST REACH STORAGE BEFORE ITS DEPENDENT PAGEdirty page in RAMwrite-ahead logchangechangeCOMMITdurable logflush required recorddata page, laterlog first
Figure 1.50A conceptual durable-commit path. A data page may be flushed before or after commit as long as the required WAL is durable first; the diagram shows the useful no-force case.

Why one ordered log helps

Changing a reservation may touch a heap page and several index pages at different storage locations. Forcing every one to stable storage at every commit can add scattered work. The log can collect a compact ordered recovery record, and several transactions can share a flush through group commit. Data pages can be written later according to cache and checkpoint policies.

No-force allows changed pages to remain unflushed at commit, requiring redo where committed work is missing. Steal can flush uncommitted changes, requiring undo or visibility rules that keep them invalid. These policies are separate from WAL.

WHERE THE CRASH LANDS DECIDES WHAT RECOVERY MUST DOWHERE THE CRASH LANDS DECIDES WHAT RECOVERY MUST DOupdate in RAMlog record durableCOMMIT durabledata page writtenwork vanishes;never acknowledgedlog exists, no commit:undo, never exposecommitted, page old:REDO from the logpage already new:skip, do not apply twicethe log is what makes cases 2, 3 and 4 tell apart
Figure 1.51The failure boundary determines whether recovery must restore a committed effect or exclude unfinished work. Durable recovery information makes the distinction possible.

Walk through the failure cases

A durable update without durable commit remains unfinished. A durable commit with an old page needs redo. A page already containing the change must not apply it twice. RAM-only unacknowledged work may be lost.

A log sequence number, or LSN, orders log positions. A page can record the newest log position already reflected in it, allowing recovery to determine whether a particular redo action is still needed. The recovery operation must be restartable: a second crash halfway through recovery cannot turn the same committed increment into another increment.

A checkpoint records a recovery starting boundary and associated durable state so restart need not replay the complete lifetime of the database. Checkpointing can spread writes over time rather than stopping all users for one enormous flush. Old log can be removed only when all relevant recovery, replication and backup obligations permit it, not just because a transaction committed.

#Section 45ARIES: analysis, redo and undo

ARIES recovers logged history through analysis, redo, and restartable undo. A crash may leave both committed work missing and unfinished work present on pages.

Its phases are analysis, redo and undo. Analysis reconstructs information about transactions and potentially dirty pages from checkpoint and log state. Redo repeats the relevant logged history, using page state to avoid applying an already-present action again. Undo reverses the remaining unfinished transactions. Repeating history can include changes from transactions that will later be undone; “redo only committed records” is not the general ARIES mechanism.

ARIES-STYLE RECOVERY: REDO EVERYTHING LOGGED, THEN UNDO THE LOSERS. X = 120, Y = 100ARIES-STYLE RECOVERY: REDO EVERYTHING LOGGED, THEN UNDO THE LOSERS. X = 120, Y = 100T1 beginX 100→120T2 beginY 100→50T1 commitcrashredo: repeat history forwardundo T2 backwarddurable pagesX 100Y 100after redoX 120Y 50after undoX 120Y 100T1 committed and stays; T2 never committed and is rolled back
Figure 1.52Illustrative undo/redo engine. X changes from 100 to 120 under committed T₁; Y changes from 100 to 50 under unfinished T₂. After recovery, X is 120 and Y is 100.

A small recovery trace

The log records one committed and one unfinished transaction. Their page values may already have reached disk or still be old; durable status and page state differ.

Analysis identifies transaction and page state. Redo repairs missing logged history without repeating applied changes; undo removes the unfinished transaction while retaining the committed one.

A compensation log record, or CLR, records the action taken during undo. If recovery crashes again, redo can repeat the compensation safely and undo can continue from the remaining work, rather than reversing the compensation as if it were an ordinary new application change. This is why restartable recovery needs more than “read the log backwards.”

Page policies explain the need for the phases

No-force creates the need to reconstruct committed work not yet forced to data pages. Steal creates the possibility that uncommitted history is already on disk. ARIES coordinates these flexible buffer policies with fine-grained transactional work. The original ARIES paper, by C. Mohan and colleagues, explains the full recovery design.

PostgreSQL uses WAL and MVCC but should not be described as simply running this textbook physical-undo trace. Its uncommitted tuple versions remain invisible and are reclaimed through its own mechanisms. ARIES is the conceptual recovery method requested by the syllabus; the practical PostgreSQL part returns to that engine’s specific lifecycle. Keep a general recovery algorithm separate from a claim about a named product.

#Section 46Buffer pools, pinning and eviction

A buffer pool caches persistent pages in RAM. Repeated root-page reads can reuse one resident frame rather than repeatedly fetch storage.

On a hit, the manager finds a resident page and lets the caller use it. On a miss, it obtains a free or reusable frame, loads the requested page, and updates the mapping. A pin prevents a frame from being evicted while a caller still needs it. Pinning does not grant exclusive permission to change page contents: an internal latch may be needed for that separate task.

THE BUFFER POOL REUSES RESIDENT PAGES AND FLUSHES DIRTY ONESTHE BUFFER POOL REUSES RESIDENT PAGES AND FLUSHES DIRTY ONESP0cleanP1cleanP2dirtyP3pinnedP4freeP5cleandirty eviction needs safe writeback
Figure 1.53A hit uses the resident page; a miss must obtain a frame and load data. A dirty victim needs a safe flush before reuse.

What makes a frame reusable

A clean unpinned page can be discarded because its backing copy already represents its contents. A dirty page cannot simply vanish: the engine must preserve its changes according to the logging and writeback rules. Before flushing it, the manager ensures the WAL required by that page is durable. It then writes the page safely and eventually reuses the frame when no caller pins it.

If every frame is pinned, ordinary eviction cannot make space. A caller that forgets to unpin can therefore cause resource exhaustion even when the cache’s nominal byte size seems adequate. Long page usage intervals and transaction lifetime are different issues; some engines retain logical locks after releasing page pins.

A replacement policy chooses which reusable page should leave. Least-recently-used reasoning favours pages accessed lately, while clock-style policies approximate recency with cheaper metadata updates. A large sequential scan can pollute a cache intended for repeatedly accessed point queries, so engines may distinguish one-time scans from reusable working data.

Cache hit ratio measures requests served by a cache. Misses may hit another layer, and rare expensive misses or locks can still dominate latency.

Flush is not eviction, and cache is not durability

An engine can flush a dirty page and retain it in the pool as a clean page. It can later evict that clean page without another write. A transaction can commit while some dirty pages remain cached under a no-force design. These distinctions connect the buffer manager to WAL: the cache optimizes access, while the recovery contract determines what must survive RAM loss.

#Section 47LSM trees, compaction and amplification

A log-structured merge tree, or LSM tree, collects updates into sorted components and merges them. Sequential writes trade against merge and read costs.

The write path commonly appends recovery information to WAL and applies the update to an ordered MemTable in RAM. When that structure fills, it becomes an immutable MemTable so a background flush can write it while a new mutable table receives later writes. A sorted string table, or SSTable, is an immutable sorted file containing keys and associated versioned data or deletion markers.

SORTED RUNS ACCUMULATE ON DISK, THEN MERGE THROUGH COMPACTIONSORTED RUNS ACCUMULATE ON DISK, THEN MERGE THROUGH COMPACTIONmutable memtableWALappendflushABCBDEAFGABCDEFGcompaction merges keys and keeps the permitted newest state
Figure 1.54A conceptual LSM lifecycle. The exact ordering of acknowledgement and persistence depends on the engine’s configured durability contract.

A read must resolve several possible copies

Suppose a key first has a free value in an older SSTable and later receives a held value in the MemTable. The reader searches appropriate newer components and selects the visible newest version under the engine’s version rules. It cannot return the old free value merely because it found that copy first. Range reads merge ordered iterators across components while resolving duplicates and versions.

A tombstone records a deletion. Removing a key only from the newest component would expose an older copy again. The marker must remain until compaction and retention rules prove that no older visible value can reappear. Snapshots and overlapping runs complicate that proof.

Compaction merges selected sorted runs, resolves versions that can be removed, propagates necessary tombstones and writes replacement files. Once readers and recovery no longer need the old runs, the engine can retire them. Leveled and tiered strategies choose different overlap and rewrite patterns; their read, write and space costs differ. RocksDB’s compaction documentation gives concrete versions of these strategies.

Count the work a write causes

Write amplification is physical bytes written divided by logical bytes changed, under a stated accounting boundary. Read amplification counts extra read work required to answer a logical request; define whether that work means runs, blocks or bytes. Space amplification compares stored bytes with the live logical data, including obsolete versions and duplication within the chosen boundary.

4,096 LOGICAL BYTES BECOME 28,672 PHYSICAL BYTES: WRITE AMPLIFICATION 74,096 LOGICAL BYTES BECOME 28,672 PHYSICAL BYTES: WRITE AMPLIFICATION 7you changed4,096WAL 4,096flush 8,192compaction 16,3844,096 + 8,192 + 16,384 = 28,67228,672 ÷ 4,096 = 7illustrative accounted batch, not a measured engine
Figure 1.55An illustrative accounted batch changes 4,096 logical bytes and causes 28,672 physical bytes across WAL, flush and compaction. This is a declared workload example, not a measured engine prediction.

Write amplification compares physical writes with logical changes. WAL, flushing, and later compaction all contribute, so foreground acknowledgement alone does not capture the complete write cost.

B+ trees and LSM trees both support useful point and range access. B+ trees maintain an ordered mutable structure; LSMs collect and merge ordered runs. LSM writes can be sequentialized, but reads and compaction pay for multiple components. A compaction backlog can increase read work, consume space and eventually stall incoming writes. Choose from measured workload and retention behaviour rather than calling either family universally faster.

#Section 48Bloom filters and one-sided errors

A Bloom filter reports definite absence or possible presence. It can skip irrelevant SSTables but cannot replace a real check after a positive result.

Initialize a bit array to zero. To insert a key, compute its hash positions and set those bits to one. To query a key, compute the same positions. If any corresponding bit is zero, the key could not have been inserted into that filter. If all are one, the key may have been inserted, or other keys may have set the same bits. That second outcome requires checking the real data.

ILLUSTRATIVE BLOOM BITS: NEGATIVES ARE DECISIVE0011021314051607query hashes to 1 and 6: both set -> possibly presentquery hashes to 0 and 6: zero bit -> definitely absenta set bit remembers collisions too
Figure 1.56Illustrative eight-bit array with set positions 1, 3, 4 and 6. A query requiring bit 0 is rejected; a query requiring bits 1 and 6 still needs a data lookup.

Why false positives are possible but ordinary false negatives are not

A false positive reports possible membership for an absent key because hash positions overlap. It creates extra checks, while a correctly maintained negative excludes a represented key.

An inserted key’s positions remain set, so an unchanged ordinary Bloom filter has no false negatives. Clearing a bit to delete one key is unsafe because another inserted key may share it. A counting variant can track counts, but overflow and correct decrement handling introduce different obligations. The no-false-negative claim assumes consistent hashing, an intact filter and normal insertion-only semantics for the represented set.

For a general m-bit filter with n inserted keys and k hashes, the familiar independent-bit approximation is

Filter error depends on space, inserted keys, and hash behavior. The formula is a model estimate, not a production guarantee for every workload.

Where an LSM uses the result

A negative filter skips a point lookup; a positive still needs real checks. Include tombstones so skipped deletions cannot expose stale values. Whole-key filters do not prove arbitrary ranges empty. RocksDB reference.