BOOKS DEEP-READ · Database Internals · CH 11

Replication and Consistency

Database Internals · Ch 11 · Alex Petrov · 2019

中文 →

What is this chapter about?

You change your profile picture, hit refresh, and the old one is still there; two seconds later the new one shows up. Chapter 11 of Database Internals is about what happens in those two seconds — your data is actually stored in several copies at once, and they are not always the same. What the chapter delivers is a language for saying precisely which copy a read is allowed to return.

A strange thing first

Think of your data as an important document, copied three times and handed to three people — that way no single person going on holiday loses it. But trouble follows: you update the copy held by the first person, and the other two still hold the old text. Ask the second person and you get the old answer. Stranger still: ask the first and get the new answer, then ask the second and get the old one — from the asker's point of view, the data went backwards.

Why the old world found this hard

The obvious fix is "when you change it, make all three change at once, nobody jumps ahead." But that means every change waits for the slowest person to nod. A round trip between data centers in the same city is about 1 millisecond; across an ocean it is tens of milliseconds — pushing "always read the latest" to its limit means every read and write pays for several extra rounds of asking, and if even one person is unreachable, nobody can change anything. Go the other way for speed, and you accept the occasional stale read. This is an unavoidable trade, not laziness.

Consistency is not a switch, it is a row of tiers

The most important idea in the chapter: "consistent or not" is not a yes/no question but a row of priced promises, from expensive to cheap —

Which tier you buy depends on what happens if you read a stale value: an account balance and a like counter clearly should not buy the same one.

And some data needs no negotiation at all

The end of the chapter has a lovely idea: some data can be designed so that any two versions always merge cleanly. To count likes, let each machine track only the share it saw, and when merging, take the larger number per machine and add those up — duplicates, reordering and resends cannot change the result. This kind of data never needs the machines to negotiate who is right; it converges on its own. The cost: only some data types can be designed this way, and "it merged" is not the same as "the merge is what a human wanted".

Remember this one line

Extra copies exist so you don't lose the data, but copies always differ for a while. So don't ask "is the data consistent?" — ask "which tier of promise am I willing to pay how much latency for?" Between "always the latest" and "eventually the same" there are several very good bargains.

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