Skip to main content

Chapter 18 — How Databases Store Bytes: Pages, WAL, B-tree vs LSM, OLTP vs OLAP

Part IV · Data & Storage | Prerequisites: Ch 17 | Builds: the ability to predict Pulsely's index needs from access patterns

For three chapters you've treated the database as a place that keeps promises. Earlier you made it the enforcer of correctness, then the keeper of a theory of your domain, then the arbiter of concurrent timelines. In all three, "the database" was a black box you reasoned about by its guarantees, never its mechanics. That was the right altitude for those chapters. It is the wrong altitude for the next two, because every question you are about to be paged about at 2 a.m. — why is this query slow, does it need an index, which engine should this workload run on, why did the billing report wreck charting — is answered not at the level of guarantees but at the level of bytes on a disk and how the engine moves them into memory.

This chapter opens the box. We go down to the page, the write-ahead log, the B-tree, and its rebellious cousin the LSM-tree, and we come back up with a single hard skill: the ability to look at an access pattern and predict, before you type a single CREATE INDEX, what the engine will have to do to satisfy it. We deliberately do not master Postgres's specific index types, EXPLAIN output, or VACUUM here — that's Chapter 19. We're building the physics; Chapter 19 is the engineering on top of it.


1. The problem: the day "free" stopped being free​

Here's a story that has happened to almost everyone who has run a database past its honeymoon.

A Pulsely engineer ships a patient chart-timeline endpoint. SELECT * FROM encounters WHERE patient_id = $1 ORDER BY started_at DESC LIMIT 20. In dev it returns in 3 ms. In staging, 4 ms. In production for the first eight months, a comfortable single-digit milliseconds. Nobody indexes anything; nobody needs to. Then one Tuesday at 2 a.m. the pager goes off: that exact query, with no code change, no deploy, nothing — is now taking nine seconds, and it's holding connections long enough that unrelated endpoints are timing out behind it.

What changed? The table crossed roughly ten million rows. For the first eight months, the entire encounters table fit in memory, and "scan every row to find this patient's twenty" was so cheap it was indistinguishable from instant. Reading a few thousand rows from RAM is free in any sense that matters. Then the table grew past the memory the database had for it, the scan started hitting the disk, and "scan every row" became "drag ten million rows across a slow storage medium to find twenty." Same SQL. Same code. The difference was bytes on disk and how they were laid out — and the engineer had no model for that, so the slowdown looked like magic.

Now the same story's evil twin. SELECT * FROM observations WHERE code = '8867-4' — pull every heart-rate reading (that's the LOINC code for heart rate) from the remote-monitoring firehose — returns instantly in dev against five thousand seeded rows and times out in prod against forty million. The developer stares at the query. It's correct. It's simple. There is nothing to "fix" in the SQL, because the problem was never in the SQL — it's that the engine has no faster way to find the heart-rate rows than to read every page of the table and check each row. Until you understand what a page is and why the engine reads them in bulk, that timeout is unexplainable, and unexplainable performance problems are the ones you can't fix.

Then there's the overcorrection. Someone gets burned by a slow query, reads online that "indexes make queries fast," and adds eleven indexes to chart_entries. The reads they cared about do get faster. But now every INSERT and UPDATE to chart_entries has to update eleven separate sorted structures, write latency roughly doubles, and disk usage triples. Indexes are not free magic. They are a write tax you pay in exchange for read speed, and you took out eleven loans without reading the terms.

And the cross-system catastrophe. The revenue-cycle team runs a GROUP BY payer_id, date_trunc('month', submitted_at) over all-time claims, directly against the production database, at noon. It's a perfectly reasonable business question. It is also a query that reads the entire claims table — and in doing so, it drags forty million claims' worth of pages into the database's memory, evicting the carefully warmed working set that live charting depends on. For the next ten minutes every clinician's chart save is slow, because the pages charting needs got thrown out to make room for a biller's report. Nothing crashed. One query quietly poisoned a thousand others.

🧭 The through-line of this chapter. Every one of those incidents — the slow scan, the index tax, the analytics blast radius — is downstream of how the engine stores and reads bytes. You cannot reason about performance you don't understand the storage of. This is the chapter where the database stops being a place that keeps promises and becomes a machine you can predict.

We can't leave this a black box, because every index decision, every "why is this slow," every capacity plan is a question about pages, memory, and the structures that point into them. So let's build the model.


2. The mental model: a machine that hoards RAM and fears the disk​

Hold one picture above all others: a database is a byte-management machine whose entire personality is shaped by one brutal fact — disk is slow and RAM is fast and scarce. Almost everything an engine does is choreography around that asymmetry: keep the data you're using in RAM, touch the disk as rarely as possible, and when you must touch it, move in big efficient chunks rather than tiny ones. Internalize that and most storage design stops being arbitrary.

How brutal is the asymmetry? Reading a value already in RAM costs on the order of nanoseconds. Reading from a modern SSD costs tens to hundreds of microseconds — a thousandfold gap. From a spinning disk, milliseconds — a millionfold. An engine that treated disk like RAM would be a thousand to a million times too slow. So it doesn't. It hoards.

The page is the atom​

Here is the first idea that breaks beginners' intuition. The database never reads "a row" from disk. It can't — disk hardware is block-addressed, it deals in fixed-size chunks, not individual rows. So the engine reads a fixed-size page (commonly 8 KB in Postgres, 16 KB in MySQL's InnoDB), and that page holds many rows. When your query wants one row, the engine reads the whole page that row lives on — and the dozens of neighboring rows that happened to share it come along for free.

This single fact rewrites how you reason about cost. The right question is never "how many rows does this query touch." It is "how many pages does this query have to read." A query that reads one row from each of a thousand scattered pages is roughly a thousand times more expensive than a query that reads a thousand rows from a single page — even though both return a thousand rows. Page count, not row count, is the currency of database performance.

Two structures, one job​

Picture a table as two separate things. First, the heap (or data structure): the pages where the actual rows live, in no particular order — roughly, in the order they were inserted. Second, an index: a separate structure whose only job is to turn "find the rows matching X" from "read every page of the heap" into "navigate a tree." The heap is the warehouse; the index is the catalog that tells you which shelf to walk to.

🧭 Mental model. An index is a phone book. It's a copy of one or more columns, kept sorted, with a pointer next to each entry saying where the full row lives. You don't read a phone book front to back to find "Nguyen" — you exploit the sorting to jump. That jump is why an index lookup is O(log n) instead of O(n): each step down the tree eliminates a huge fraction of the remaining search space, exactly the way binary search beats a linear scan, except on disk pages instead of array slots. The cost: like a real phone book, the index is a second copy that has to be kept in sync with the original on every write. That's the write tax from §1, named.

Durability without bravery: the WAL​

Now the trick that makes databases survive crashes. Naively, "make a change durable" means "carefully update the data page on disk and make sure it's safe." But data pages live scattered across the disk, updating them in place means slow random writes, and a crash mid-update could leave a page half-written and corrupt. So engines don't do that on the commit path.

Instead: write down your intent before you do it. Before touching the real data pages, the engine appends a small record describing the change — "row X went from this to that" — to a write-ahead log (WAL), a file it only ever appends to, sequentially, which is the fastest thing a disk can do. Once that log record is safely on durable storage, the change is considered durable, and the engine can return success to the client. The actual data pages get updated lazily, in the background, whenever it's convenient. If the machine loses power one nanosecond after commit, recovery replays the log and reconstructs every change the data pages hadn't caught up on yet. Durability is "the intent is logged," not "the data is in its final place." This is the same WAL that made COMMIT mean something survivable — durability and crash recovery are the same machinery seen from two angles.

Two philosophies of sorted storage​

Finally, the fork in the road we'll spend §3 and §7 on. Both a B-tree and an LSM-tree give you sorted access to your data; they disagree violently about where to pay for it.

  • B-tree: read-optimized, update-in-place. Keep the data in a balanced sorted tree on disk, and when a value changes, go find its page and edit it. Reads are fast and predictable; writes do scattered random I/O and occasionally have to reorganize.
  • LSM-tree: write-optimized, append-then-merge. Never edit in place. Buffer writes in memory, periodically dump them to disk as new immutable sorted files, and merge those files together in the background. Writes are blazing sequential appends; reads may have to check several files, and the background merging is a constant tax.

🔑 The storage invariant. Every storage engine is choreography to keep the working set in RAM and minimize disk page touches. B-tree and LSM are two different bets on which operation deserves the cheap path — and there is no free lunch: optimizing writes makes reads (or space) more expensive, and vice versa. You will choose between them by knowing your workload's read/write shape, not by which is "faster," because neither is faster at everything.


3. Theory & invariants​

The mental model tells you how to picture the machine. The invariants tell you what is always true about it — the load-bearing rules you reason from when a query misbehaves.

Inside a page​

Open up that 8 KB page and you'll find a deliberate layout:

┌──────────────────────────────────────────────┐
│ page header (checksum, free-space pointers) │ ← fixed, top
├──────────────────────────────────────────────┤
│ slot array → [ptr0][ptr1][ptr2]... │ ← grows down
│ │
│ ░░░ free space ░░░ │ ← shrinks from both ends
│ │
│ ...[tuple2][tuple1][tuple0] │ ← rows grow up from bottom
└──────────────────────────────────────────────┘

A header at the top. A slot array (line pointers) growing down from just below it. The actual tuples (rows) growing up from the bottom. Free space in the middle, consumed from both ends until they meet. The slot array is the clever bit: an index doesn't point directly at a tuple's byte offset — it points at a slot, and the slot points at the tuple. It's a level of indirection like a React key or a ref: outsiders hold a stable handle (the slot number), and the engine is free to shuffle the actual row around inside the page without anyone re-pointing — the same way React can move a keyed DOM node without the parent caring where it physically sits. So a row can be moved within its page (say, after an update changes its size) without invalidating any external pointer to it; you just repoint the slot. One level of indirection buys you the freedom to rearrange a page's interior without telling the rest of the world.

The buffer pool​

The engine cannot work on a page sitting on disk. It must first read that page into a region of RAM called the buffer pool, where pages live in fixed-size frames. A page in a frame is marked clean (matches disk) or dirty (has unflushed changes). When the buffer pool fills and a new page must be read in, the engine evicts a resident page to make room — and a dirty page must be flushed to disk before its frame can be reused, or you'd lose the change. Which page gets evicted is decided by a policy (an approximation of least-recently-used — Postgres uses a clock-sweep variant).

🔑 The buffer-pool invariant. The single most predictive number in a database is the cache hit ratio: the fraction of page requests served from the buffer pool without touching disk. When your working set fits in the buffer pool, hit ratio approaches 100% and queries run at RAM speed. When the working set exceeds the pool, hit ratio collapses, every query starts paying disk latency, and performance goes off a cliff — not gracefully, but suddenly, at the exact moment the working set stops fitting. This is why capacity planning is "working set vs. RAM," not "rows vs. disk." Remember the §1 story: the chart-timeline query didn't degrade slowly; it fell off the cliff the week the table outgrew memory.

The write-ahead rule​

The WAL has one inviolable ordering rule, and durability hangs entirely on it:

🔑 The write-ahead rule. The log record describing a change must reach durable storage before the corresponding data page is allowed to be flushed. The commit point is the moment the transaction's WAL record is fsync'd to disk — fsync being the syscall that forces the operating system to actually flush the write onto the physical disk, instead of leaving it in a fast in-memory OS buffer that a crash would wipe — not the moment the data page is written. (In frontend terms: it's the difference between React state changed in memory and the moment that change is actually persisted to the backend — until the server confirms, a refresh loses it.) A client that receives "committed" is guaranteed that the log survives a crash, from which the data can always be reconstructed.

From that one rule, crash recovery falls out as redo + undo. After a crash, the engine replays the WAL from the last checkpoint: it redoes committed changes that hadn't yet made it into the data pages (the lazy flush hadn't caught up), and it undoes changes from transactions that were in flight but never committed. Checkpoints — periodic moments where the engine forces all dirty pages to disk and records "everything before here is safely in the data files" — exist to bound recovery time: without them, recovery would have to replay the entire history of the database; with them, it replays only since the last checkpoint.

change ──▶ append WAL record ──▶ fsync ◀── COMMIT POINT (durable, client told "ok")
│
▼ (lazily, in background)
flush data page to disk
│
─ ─ ─ CRASH ─ ─ ─
│
▼
recovery: replay WAL from last checkpoint
redo committed-but-unflushed · undo uncommitted

Why a B-tree is O(log n) — and why the constant is tiny​

A B-tree is a balanced search tree built for disk. Its invariants are precise and they're what make it fast:

  • All leaves sit at the same depth — the tree is perfectly balanced, so every lookup costs the same number of steps. No row is "deeper" than another.
  • Each node is one page, kept at least roughly half-full, holding many keys (not two children like a binary tree, but hundreds — because a node is a whole page and a page holds hundreds of keys-plus-pointers).
  • That high count of children per node — the fan-out — is the whole trick. With a fan-out in the hundreds, the tree gets wide fast and stays shallow. A three-level tree with fan-out 500 addresses 500 × 500 × 500 = 125 million keys. Four levels addresses sixty billion.
[ root page ] ← 1 page read
/ | \
[internal] [internal] [internal] ← 1 page read
/ | \ / | \ / | \
[leaf][leaf]... ... ...[leaf] ← 1 page read
│ → then 1 read into the heap
▼ for the actual row
heap page (the full row lives here) (the "bookmark lookup")

So "O(log n)" isn't an abstract reassurance — it's three or four page reads to find any single key among billions of rows. That's the real-world constant: a handful of page touches versus reading every page of the table. That's the entire value proposition of an index, made concrete.

When you insert a key into a leaf that's already full, the engine splits the page — allocates a new page, moves half the keys over, and pushes a separator key up into the parent (which may itself split, recursively). Splits are how the tree grows and stays balanced; they're also, as we'll see in §4, where insert order quietly decides whether your table stays tidy or fragments.

Clustered vs. secondary​

Two flavors of index, and the difference matters:

  • A clustered index stores the actual table rows in the index's leaf pages, in key order. InnoDB does this with the primary key: the PK index is the table. A PK lookup lands you directly on the row.
  • A secondary index stores only the indexed columns plus a pointer to where the full row lives. Finding a row through a secondary index is two lookups: navigate the secondary index to get the pointer, then follow the pointer to fetch the row. That second hop is the bookmark lookup drawn above.

Postgres takes a different stance: its heap is unclustered (rows sit in insertion order in a separate heap), so in Postgres every index is effectively secondary, and every index lookup pays a bookmark lookup into the heap. This is a genuine design split between engines, and it'll resurface in §7's tradeoffs. (Postgres's specific index types — GIN, GiST, BRIN, partial, covering — are Chapter 19's job; here we only need "B-tree, and one or two lookups.")

The LSM-tree: writes first, order later​

Now the other philosophy. In plain terms: instead of editing rows where they sit, an LSM-tree (log-structured merge-tree) keeps a scratchpad in RAM, dumps it to disk as a fresh sealed file when the scratchpad is full, and later merges the piles in the background — so writes are cheap, but a read might have to check several piles. Here are the named pieces that make up that picture:

  • Every write goes to two places: an in-memory sorted structure called the memtable (the scratchpad), and a WAL for durability (same write-ahead trick). The write returns as soon as those two appends are done — and appends are fast.
  • When the memtable fills, it's flushed to disk as an immutable, sorted file: an SSTable (sorted string table — a sealed file). Immutable — never edited again.
  • Over time you accumulate many SSTables. A read may therefore have to check the memtable and several SSTables to find the newest version of a key (or confirm it's absent). To keep that fan-out bounded, a background process called compaction continually merges SSTables together — discarding superseded versions and deleted keys, reclaiming space, and keeping the number of files a read must consult small.
  • Reads are made bearable by bloom filters: a tiny probabilistic structure per SSTable that can say "this key is definitely not here" cheaply, so a read skips SSTables that can't contain its key instead of probing all of them.

The shape that falls out: a write is "append to memtable + WAL," so writes are near-constant-time and sequential — wonderful. But a read might consult several structures, and compaction is forever rewriting data in the background. That's the bet: cheap writes, paid for in read complexity and background work.

Selectivity decides whether an index even helps​

An index is only worth using when it eliminates most of the work. Two related terms:

  • Cardinality — how many distinct values a column has. mrn (medical record number) has cardinality near the row count (almost all distinct). is_active has cardinality 2.
  • Selectivity — what fraction of rows a given predicate keeps. WHERE mrn = $1 is highly selective (keeps ~one row). WHERE is_active = true might keep 95% of the table — barely selective at all.

🔑 The selectivity invariant. An index pays off only when the predicate is selective enough that navigating the tree and doing bookmark lookups for the matches is cheaper than just scanning the heap. For a low-selectivity predicate — say, one that matches 80% of rows — using the index means doing a bookmark lookup for 80% of the table one row at a time in random order, which touches more pages, more expensively, than reading the heap sequentially front to back. This is why the engine will sometimes "ignore" an index you built: it's not broken, it correctly judged that the scan is cheaper. Low-cardinality columns are usually the wrong thing to index alone. (The full story of how Postgres's planner makes that judgment — and how it goes wrong with stale statistics — is Chapter 19.)

The inverted index, in one paragraph​

A B-tree answers "find the rows where column = value." But what about "find the clinical notes that contain the word penicillin"? You can't B-tree your way to that efficiently — a note's free text is one big blob, not a column you match exactly. The structure for that job inverts the layout: instead of mapping row → text, you map term → list of row IDs that contain it (a postings list). Want notes containing "penicillin"? Look up "penicillin," get the list. It's the same fundamental idea as every index in this chapter — a sorted structure pointing back at records — just keyed by token instead of by column value.

🛑 What we deliberately did not explain. How text gets tokenized into terms (lowercasing, stemming "running" → "run", stripping stop-words), how multi-term queries intersect postings lists, how results are ranked by relevance, and how a dedicated search engine scales this across machines (and, in healthcare, how results are access-scoped so a search never leaks a chart the searcher can't see). That's a whole discipline, and it gets its own chapter: search and the inverted index in depth is Chapter 22. We named the structure and located it; we did not build it.


4. Under the hood: making the page model visible​

Theory you can't observe is theory you won't trust. Let's make the storage model show itself in tools you'll actually run — lightly, because the deep tooling is Chapter 19.

Seeing pages move with EXPLAIN (ANALYZE, BUFFERS). Postgres will tell you, per query, exactly how many pages it touched and whether they came from RAM or disk:

EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM observations WHERE code = '8867-4';

In the output you'll see lines like Buffers: shared hit=812 read=40231. That's the whole §2–§3 model made literal: shared hit = pages found in the buffer pool (RAM, fast), read = pages fetched from disk (slow). A query that's "fast" with 99% hits can become a monster with 99% reads against the same data, purely because the working set fell out of cache. You are watching the buffer pool work. (Reading the rest of an EXPLAIN plan — scan types, join nodes, estimated-vs-actual rows — is Chapter 19; here we only watch the BUFFERS counters, because they are the page model.)

Postgres page specifics. Pages are 8 KB. A value too big to fit in a page (a long note body, a large JSON of device telemetry) gets pushed out-of-line via a mechanism called TOAST and stored compressed in a side table, so the main row stays page-sized — which is why a table of "small" rows can have surprisingly large storage when a few columns are huge. And recall the MVCC you already met: Postgres writes a new tuple version on every update and marks the old one dead, so pages accumulate dead tuples until VACUUM reclaims them. That ties storage directly to MVCC — the corpses live in the pages, taking up space your reads still have to skip over. (The mechanics and tuning of VACUUM are Chapter 19.)

The WAL, in operation. The durability-vs-throughput dial from §3 is a real setting: synchronous_commit. With it on (the default), COMMIT waits for the WAL record to be fsync'd before returning — full durability, but every commit pays an fsync. With it off, COMMIT returns immediately and the WAL is flushed a few milliseconds later — much higher throughput, at the cost of losing the last few milliseconds of commits if the machine crashes in that window. The WAL is also the source of truth for streaming replication (a replica replays the primary's WAL to stay in sync) and point-in-time recovery. Which means a stalled replica or a long-open transaction can prevent old WAL from being recycled, and the disk fills — a failure mode you'll learn to watch for. (Specific knobs — wal_level, checkpoint_timeout, max_wal_size — are Chapter 19.)

Insert order decides B-tree health. Here's a consequence of page splits (§3) that bites in production. If your primary key is monotonic — bigserial, or a time-ordered ID — every insert goes to the rightmost leaf of the B-tree. New keys append cleanly, pages fill and split predictably at the edge, and the tree stays compact:

monotonic key: ... [97][98][99] → append [100] one tidy growing edge

random UUID: [a3..][f1..][07..][b9..] inserts land everywhere →
random leaves split, pages left half-empty, tree bloats

If your primary key is a random UUID (v4), inserts land at random leaves all over the tree. Random leaves split, pages are left half-empty, the index fragments and grows far larger than its data warrants, and the working set you need in RAM balloons — more pages, worse hit ratio. The fix is to use time-ordered identifiers (UUIDv7, ULID, or plain bigserial) so inserts append instead of scattering. This is the storage-level reason behind the key-design advice you saw earlier, now visible at the page level: random keys fragment B-trees.

LSM engines, grounded. The LSM design isn't theoretical — it powers RocksDB and LevelDB (embeddable LSM engines), and stores like Cassandra and ScyllaDB are LSM-backed. In all of them a write is "append to memtable + WAL" → near-constant fast ingest, and a read may consult the memtable plus several bloom-filtered SSTable levels. Worth noting because it proves the concept is engine-agnostic, not "a database thing": RocksDB shows up as the state store inside stream processors like Kafka Streams and Flink, where the same write-heavy LSM tradeoff is exactly what a high-throughput event pipeline wants — and a firehose of remote-monitoring vitals is precisely that shape. Same physics, different product.

📎 Borrowed on credit: the connection pool sits above the buffer pool. In Node you'll reach storage through a driver — pg for Postgres, mysql2 for MySQL — and you'll put a connection pool in front of it. Keep the two pools straight: the connection pool rations how many client connections talk to the database; the buffer pool is the database's own RAM cache of pages. They're different layers solving different problems, and conflating them causes muddled tuning. (Connection-pool sizing, and why an external pooler like PgBouncer exists, is Chapter 19.) If you want to see a B-tree on disk with your own eyes, the cheapest lab is SQLite via better-sqlite3: set PRAGMA page_size, insert rows, and the file is the B-tree — pages and all — in a single inspectable artifact.


5. In production: turning the model into operating decisions​

The storage model isn't trivia; it's the basis of the operating decisions a backend engineer actually makes. Six of them, in the order you'll meet them.

Right-size the buffer pool — and know your engine's model. Postgres deliberately keeps shared_buffers modest (a common starting point is ~25% of RAM) because it also relies on the operating system's own file cache for the rest — pages can be hot in the OS cache even when not in shared_buffers. InnoDB takes the opposite stance: innodb_buffer_pool_size is set high (~70–80% of RAM) because it does not lean on the OS cache. Tune the wrong model and you either starve the cache or double-cache and waste RAM. Know which model your engine uses before you touch the number.

Read the plan, not the vibes. When a query is slow, the senior move is not to guess — it's to ask the engine what it actually did. Confirm whether an index is being used, because the planner may correctly reject one for low selectivity (§3) or because its statistics about the table are stale and it misjudged the row count. "I added the index" and "the engine uses the index" are different claims; only the plan tells you which is true. (The full diagnostic loop — pg_stat_statements, keeping statistics fresh, the planner's reasoning — is Chapter 19.)

Practice index hygiene. Indexes rot. Some get built and never used (the access pattern changed, or someone over-indexed in a panic). Each unused index still taxes every write and consumes disk, so the discipline is to periodically find indexes with zero scans and drop them, watch for index bloat, and reach for covering indexes — an index that contains every column a query needs — so the query is answered from the index alone without the bookmark lookup into the heap (an "index-only scan"). Fewer page touches, faster query.

Order composite-index columns correctly. A composite index on (code, observed_at) is sorted by observation code first, then time within each code. That sorting means it serves WHERE code = '8867-4' and WHERE code = '8867-4' AND observed_at > now() - interval '1 day' beautifully — but it is useless for WHERE observed_at > ... alone, because the index isn't sorted by time at the top level; time only orders rows within a code. The rule of thumb: equality-matched columns first, then the range column. You'll see this developed as the "ESR rule" (equality, sort, range) in Chapter 19; the storage reason is exactly the §3 phone-book sorting — a B-tree can only seek on a contiguous prefix of its sort order.

Operate the WAL. The WAL is not just a durability detail; in production it's your replication stream and your point-in-time-recovery source. So you monitor WAL generation rate, archive WAL safely, and watch for the trap from §4: a long-running transaction or a stalled replica can pin old WAL so it can't be recycled, and the disk fills — taking the database down for a reason that has nothing to do with your data volume.

Separate OLTP from OLAP — physically. This is the §1 billing-report catastrophe, prevented by design. Your transactional database (OLTP) is tuned for many small, fast reads and writes against a hot working set — live charting, scheduling, order entry. Analytics (OLAP) wants to scan enormous ranges and aggregate — denial rates by payer, panel-wide risk scores, RPM adherence trends — which evicts the OLTP working set and tanks everyone's latency. The production answer is to move analytics off the primary: read-replicas for read scaling, then CDC/ETL into a separate columnar analytics store (BigQuery, Snowflake, Redshift, ClickHouse) built for exactly that shape. Never point the BI or RCM-reporting tool at the primary. We'll explain why a columnar store is the right home for analytics in §7; the operating rule is simply: separate the two, always.

🏭 The biggest production lesson in this chapter is that storage decisions have blast radius beyond the one query. A missing index doesn't just slow its own query; it can saturate the disk for the whole instance. An unbounded analytics scan doesn't just run slowly; it evicts the working set every other query depends on. A random-UUID key doesn't just fragment its own index; it bloats the working set and lowers hit ratio cluster-wide. You operate the shared substrate, not isolated queries.


6. Common pitfalls​

Each is signature → fix: the symptom you'll observe, then the principle that resolves it.

The planner ignores your index. Signature: you built the index, but the query is still slow and the plan shows a full scan instead of an index scan. Fix: it's usually one of three things, and all trace back to §3. Low selectivity — the predicate matches too many rows, so the scan is genuinely cheaper and the engine is right to skip the index. Stale statistics — the engine's beliefs about the data are out of date, so it misjudged. Or a non-sargable predicate (jargon for "the engine can't use it as a search argument") — you wrapped the column in a function (WHERE lower(email) = ... against a plain email index) or used a leading wildcard (LIKE '%mycin' to find antibiotics), either of which destroys the sorted-prefix property the index depends on. Check selectivity first; don't reflexively "add another index." (Diagnosing which, via the plan, is Chapter 19.)

Over-indexing. Signature: you added several indexes to speed reads, and now insert/update p99 has climbed and disk usage jumped after the feature shipped. Fix: every index is a second sorted structure maintained on every write — the write tax from §2, multiplied per index. Audit which indexes are actually scanned, drop the ones with zero scans, and consolidate overlapping single-column indexes into one well-ordered composite. Index per access pattern, never "index everything."

Random-UUID primary key. Signature: high page-split rate, an index far larger than its data, poor cache locality, and PK lookups that miss the buffer pool more than they should. Fix: the §4 problem — random keys scatter inserts across the B-tree, fragmenting it. Use time-ordered identifiers (UUIDv7, ULID, or bigserial) so inserts append to the right edge and pages fill cleanly.

Type-mismatch or function in the predicate. Signature: an index exists on observed_at, but a query filtering WHERE observed_at::date = '2026-01-01' does a full scan anyway. Fix: casting or wrapping the indexed column means the index — sorted on the raw column — no longer matches the expression. Rewrite as a sargable range (observed_at >= '2026-01-01' AND observed_at < '2026-01-02') so the B-tree's sorted prefix can be used.

Analytics on the OLTP primary. Signature: charting (or the live RPM dashboard) latency spikes whenever a report runs; the buffer-pool hit ratio drops and big sequential scans appear in the activity view. Fix: the §1/§5 blast radius — the analytics scan evicts the transactional working set. Move analytics to a read-replica or a columnar warehouse; never let a denial-rate report and live charting fight over the same buffer pool.

Assuming synchronous_commit = off is safe. Signature: "the claim said submitted but vanished after the outage." Fix: turning off synchronous commit trades the last few milliseconds of durability for throughput (§4). That's acceptable for tolerant, regenerable writes — and unacceptable for money and for anything a payer or regulator will ask you to prove. Keep synchronous commit on for paths where a lost commit is a real-world loss: claim submission, a signed note, an administered medication.

Long-running / idle-in-transaction transaction. Signature: table bloat grows, the WAL disk creeps toward full, and VACUUM can't reclaim space no matter how often it runs. Fix: an open transaction holds the snapshot horizon back (the MVCC snapshot behavior you already met), so dead tuples can't be reclaimed and WAL can't be recycled — one stuck transaction starves cleanup for the whole database. Bound transaction lifetime, and never leave one idle while you do slow non-database work — a synchronous call out to a clearinghouse or lab, say — inside it.


7. Tradeoffs​

Storage engineering is a field of dials, none of which has a universally correct setting. Senior judgment is naming the dial and saying why you set it where you did.

B-tree ↔ LSM. The headline choice. A B-tree gives fast, low-variance point reads and in-place updates with modest read amplification — but writes do random I/O and trigger page splits, which sets a ceiling on write throughput. An LSM-tree gives blazing sequential writes — but pays for them three ways: read amplification (a read may probe the memtable plus several SSTables), write amplification (compaction rewrites the same data repeatedly as it merges levels), and space amplification (stale superseded copies linger on disk until compaction reclaims them). Choose LSM for write-heavy, append-heavy workloads — audit-log ingest, time-series, the high-ingest remote-monitoring vitals firehose — where the write rate would crush a B-tree's random-I/O ceiling. Choose B-tree for read-heavy, mixed OLTP — which is most transactional applications, Pulsely's charting and scheduling core included. You'd reverse toward LSM the day your ingest rate outgrows the B-tree's write ceiling; you'd reverse away from LSM the day the latency variance from background compaction becomes unacceptable for your reads.

The amplification triangle. A sharper way to hold the LSM tradeoff: you cannot minimize read, write, and space amplification at once — improving one worsens another. Compaction tuning is literally choosing which corner to sacrifice: leveled compaction keeps read and space amplification low at the cost of more write amplification; size-tiered compaction does the opposite. There's no setting that wins all three; there's only the one that matches your workload's pain.

read amp
/\
/ \ you may have any two cheap;
/ \ the third pays for them.
/______\
write space
amp amp

Index more ↔ index less. Every index accelerates some reads and taxes every write plus storage plus the planner's decision time. There is no "index everything" that isn't also "tax every write maximally." The decision is per access pattern: index where a real, selective read path demands it; leave columns unindexed where the write cost outweighs a read you rarely make.

Clustered ↔ heap. InnoDB's clustered PK gives you free, fast range scans on the primary key (rows are physically stored in PK order) — but every secondary-index lookup pays a bookmark lookup through the PK, and changing a row's PK is expensive (it physically moves). Postgres's heap is uniform — no index is privileged — but every index, including the PK's, pays a bookmark lookup into the heap. Neither is better; they optimize different access shapes, and knowing which engine you're on tells you which lookups are cheap.

Durability ↔ throughput. synchronous_commit, group commit, fsync batching — these are a literal, continuous dial between "no committed transaction is ever lost" and "more commits per second." You don't set it once globally; you set it per workload, with money and clinical paths pinned to maximum durability and regenerable paths free to trade durability for speed.

🚫 A framing this book rejects. "OLAP is just OLTP with bigger queries — run the analytics on the same database, maybe on a replica, and you're done." This misunderstands the storage layout. A transactional database is a row store: a row's columns are stored contiguously, which is perfect for "give me this whole encounter" but wasteful for "average the charge_amount_cents column over a billion claims," because to read one column you drag every other column of every row through memory too. An analytics database is a column store: each column is stored contiguously and compressed, so "average charge_amount_cents over a billion rows" reads only that column — orders of magnitude less I/O — and compresses brilliantly because a single column's values are similar. OLTP and OLAP want physically opposite byte layouts. That's why a separate analytics store exists — not laziness, not "we couldn't make the primary fast enough," but a fundamental mismatch in how the bytes should be arranged. Running analytics on your row-store primary isn't a smaller version of the right thing; it's the wrong byte layout for the job, with the working-set blast radius thrown in for free.


8. Security & scale notes​

Indexes and storage leak information. A UNIQUE index on email (or on a patient mrn) makes "is this account registered?" / "is this person a patient here?" answerable by timing or by the error message on a duplicate insert — an attacker can enumerate which identifiers exist, which for a patient roster is itself PHI. And the WAL and backups contain your data in plaintext by default: the log that makes you durable is also a complete, readable copy of every change — every note, every result, every claim. A leaked WAL archive or backup is a full breach, and in healthcare a reportable one. Treat WAL archives and backups as crown jewels — encrypted, access-controlled, and audited.

Encryption at rest is narrower than it sounds. Transparent Data Encryption (TDE) encrypts the bytes on disk, which protects a stolen disk or backup file. It does not encrypt pages once they're in the buffer pool (they're decrypted to be used), and it does nothing for an attacker who has legitimate query access. Don't conflate "encrypted at rest" with "PHI is protected" — column-level encryption for sensitive fields is a different, additional control, and neither replaces the immutable audit trail that records who read which chart. (The cryptographic machinery is Chapter 31.)

The scale cliff is buffer-pool thrashing. This is the most important scale fact in the chapter, and it's non-linear. As long as the working set fits in the buffer pool, latency is flat and predictable. The instant the working set exceeds RAM, hit ratio collapses, every query becomes disk-bound, and latency goes off a cliff — not a gentle slope, a wall. This is precisely why capacity planning is "working set vs. RAM" and not "rows vs. disk": a vitals table ten times bigger than RAM can still be fast if its hot working set (this week's readings for active-monitoring patients) fits, and a table that just barely outgrows RAM can fall off the cliff. (The general discipline of measuring and defending tail latency is Chapter 30.)

One bad query has instance-wide blast radius. A single unindexed hot query — say, vitals-by-patient with no supporting index on a multi-tenant instance — forces a full scan that saturates the instance's I/O for every clinic on it. A missing index is therefore not just a performance bug; it's a DoS amplifier, where a cheap attacker request forces an expensive full-table scan, and enough of them starve everyone. Under peak ingest, LSM write amplification and WAL volume set your real disk-write budget and your replication-lag ceiling — and an analytics scan on the primary is, quite literally, a self-inflicted denial-of-service on your own working set.

🔑 Storage is a shared, finite substrate. The buffer pool, the disk's I/O bandwidth, the WAL disk — these are shared across every query and every tenant on an instance. So a storage decision is never local: one query's pages evict another's; one table's bloat fills the disk for all; one unindexed scan starves I/O for everybody. You secure and scale a database by reasoning about the shared substrate, not the individual query. (Whole-system scale and isolation are Chapter 29.)


9. Interview lens & exercises​

Interview questions​

The same question separates a junior who recites from a senior who reasons in pages and amplification.

"Why is a B-tree index O(log n), and what's the actual constant in practice?"

  • Junior: "Because it's a balanced tree, and balanced trees are logarithmic." Correct and hollow.
  • Senior: "Because each node is a page holding hundreds of keys, so the fan-out is huge and the tree is shallow — three or four levels addresses billions of rows. So 'O(log n)' really means three or four page reads to find any key versus reading every page of the table. The constant is tiny because we count disk-page touches, not abstract comparisons." Frames it as I/O, which is the whole point.

"You have a write-heavy ingest table — B-tree or LSM, and what do you give up?"

  • Junior: "LSM, it's faster for writes."
  • Senior: "LSM, because writes become memtable-plus-WAL appends instead of random in-place B-tree updates with page splits. What I give up is read and space amplification — a read may probe several SSTables, and compaction rewrites data repeatedly in the background. I'd tune compaction (leveled vs. size-tiered) per the amplification I can least afford, and I'd reverse to a B-tree if read-latency variance from compaction became unacceptable." Names the cost, not just the win.

"A query has an index but the database ignores it — why?"

  • Junior: "Add another index."
  • Senior: "Three usual causes: the predicate's selectivity is too low, so a scan is genuinely cheaper and the planner is right; the table statistics are stale, so it misestimated; or the predicate is non-sargable — a function on the column or a leading wildcard — so the sorted index can't be used. I'd read the plan to see which, not guess." Reasons from selectivity and sargability.

"Why not run analytics on the production database?"

  • Junior: "It might be slow."
  • Senior: "Two reasons. First, the analytics scan evicts the OLTP working set from the buffer pool, so charting latency spikes for everyone while the report runs. Second, the layouts are physically opposed — OLTP is a row store, great for whole-record reads; analytics wants a column store, which reads only the needed column and compresses it. So you replicate or CDC into a columnar warehouse; the separation is a layout decision, not laziness." Names both blast radius and row-vs-column.

"How does a database guarantee durability across a crash?"

  • Junior: "It saves to disk."
  • Senior: "Write-ahead logging. Before touching the data pages, it appends the change's intent to a sequential WAL and fsyncs it — that is the commit point, not the data-page write, which happens lazily. After a crash it replays the WAL from the last checkpoint: redo committed-but-unflushed changes, undo uncommitted ones. Checkpoints bound how much log recovery must replay, and synchronous_commit is the durability-vs-throughput dial on that fsync." States the write-ahead rule by reasoning.

Exercises & the Pulsely increment​

Do the prediction before you run anything — the entire skill is forming the hypothesis first.

  1. The Pulsely prediction drill (the increment). Before writing a single CREATE INDEX, list Pulsely's hot read paths and predict each one's index need from access pattern and selectivity. Work through these four:

    • Login by email — WHERE email = $1 on the provider/staff table. High cardinality, perfectly selective (one row). Prediction: needs an index on email; in fact the UNIQUE constraint you already declared created one, so it's covered — confirm, don't duplicate.
    • Chart notes by provider, recent first — WHERE provider_id = $1 ORDER BY signed_at DESC LIMIT 20 (a clinician's own worklist). Equality on provider, then a sort. Prediction: a composite (provider_id, signed_at DESC) so the engine seeks to the provider and reads the newest notes already in order — no separate sort, no scanning the whole provider's history. Order matters: equality column first, sort column second.
    • Encounter search by diagnosis + date — WHERE icd10_code = $1 AND started_at BETWEEN $2 AND $3. Equality then range. Prediction: composite (icd10_code, started_at) — equality column first so the index seeks to the code, then the date range reads a contiguous run within it. (started_at, icd10_code) would be wrong.
    • Claim lookup by patient — WHERE patient_id = $1 ORDER BY submitted_at DESC. Prediction: composite (patient_id, submitted_at DESC), same shape as the worklist.

    Now the deliberate non-index: an index you'd refuse to build. WHERE is_active = true on patients, where 95% of patients are active. Prediction: do NOT index is_active alone — selectivity ~0.95 means the engine would do bookmark lookups for nearly the whole table, slower than a scan, so the planner would ignore it anyway, and you'd have paid a write tax for an index nobody uses. Write all of this down as a hypothesis, then validate against the plan (the EXPLAIN-driven validation is fully developed in Chapter 19).

  2. Watch selectivity decide. Load observations with ~5M synthetic vitals rows. Run EXPLAIN (ANALYZE, BUFFERS) for a code filter with no index, then add an index on (code) and re-run, then change the query to equality-plus-range (code = $1 AND observed_at > ...) and compare (code) vs (code, observed_at). Read the shared hit / read buffer counts each time. You are watching pages move and the planner change its mind.

  3. Feel page splits. Build the same table twice — once with a random-UUIDv4 primary key, once with a bigserial or ULID — and measure insert throughput and final index size. The random-key table will be slower to write and larger on disk. That gap is page-split fragmentation, made tangible.

  4. See a B-tree on disk. Open a database with better-sqlite3, set PRAGMA page_size, insert rows, and inspect the file. You're looking at literal pages and a literal B-tree in a single file — the §3 theory, observable.


Key takeaways​

  • A database is a byte-management machine built around one fact: disk is slow, RAM is fast and scarce. All cost is "how many pages must I touch," never "how many rows."
  • The page is the unit of I/O; the buffer pool caches pages in RAM, and cache hit ratio is the most predictive metric you have. The scale cliff is the moment the working set stops fitting in RAM — non-linear, sudden.
  • WAL achieves durability by writing intent before data: the commit point is the fsync'd log record, not the data-page write; recovery is redo + undo from the last checkpoint.
  • A B-tree is O(log n) with a tiny constant — three or four page reads for billions of rows — because high fan-out keeps it shallow. Random keys fragment it; monotonic keys keep it tidy.
  • B-tree vs LSM is the read-optimized vs write-optimized choice; LSM buys fast sequential writes at the cost of read, write, and space amplification (you can minimize at most two).
  • An index helps only when the predicate is selective; low-cardinality columns are usually the wrong thing to index, and every index is a write tax.
  • OLTP and OLAP want physically opposite byte layouts (row store vs column store), which is why analytics belongs in a separate store — and why a report on the primary evicts the working set and wrecks everyone's latency.
  • Predict index needs from access pattern and selectivity before you build them; the index is the answer to a read path, not a reflex.

← Previous: Ch 17 — Transactions, ACID & Isolation · Up: Part IV overview · Master TOC · Next: Ch 19 — PostgreSQL Deep Dive →