BOOK DEEP READ · Database Internals · Chapter 7

Log-Structured Storage

Database Internals · Ch 7 · Alex Petrov · 2019

中文 →

What is this chapter about?

Every message you send, every like you tap, every heartbeat your watch records ends up inside some database. The previous chapters described one way of storing it — like editing a dictionary: turn to the right page, rub out the old entry, write the new one. This chapter describes the opposite temperament: keeping a ledger. You only ever write on the next blank line, and you never go back to change a word.

An analogy first

You keep the books for a small shop. The dictionary school: one page per customer, and when a balance changes you flip to that page and rewrite it. Looking things up is easy, but you flip pages a thousand times a day. The ledger school: your pen never leaves the paper — "Alice +100", "Bob −30", "Alice +50", line after line. It is absurdly fast to write; the price is that to learn what Alice's balance is now, you must read from the top, find several Alice lines, and trust only the most recent one.

Why the old world struggled

Disks have one blunt preference: writing straight ahead is fast; hunting around for a spot to write is slow — not by a little, by tens to hundreds of times. And "editing a dictionary" is exactly the second kind: changing one number means visiting the page it lives on, and those pages are scattered all over the disk. For anything write-heavy — chat logs, sensor readings, application logs, like counters — that is the bottleneck.

How it pulls this off

One more trick: each volume gets a cheat-strip on its cover that can tell you at a glance "this volume definitely does not contain Alice," which saves an enormous amount of pointless flipping.

So how do you choose?

It does not make writing cheaper; it changes "pay now" into "put it on credit and repay in the background." The same record gets carried around several times during tidying, and several versions of it sit on disk at once. If you write a lot, read less, and rarely revise what you wrote — logs, metrics, messages — the ledger school wins outright. If you look things up precisely over and over, or need to read a whole range in order, the dictionary school is still the better fit.

One line to remember

The whole cleverness of log-structured storage is replacing "go back and edit" with "append, then merge later." Writes got faster, but not one cent of the cost disappeared — it was simply moved onto three other bills: more volumes to search, more copies on disk, and a background clerk who never stops working.

Want the mechanisms, the numbers and the diagrams? → Switch to the deep read