Distributed Databases
The setup
A ticket app has offices in three cities, each keeping the data it uses most. Alice, in Singapore, wants the last two seats for a concert in Tokyo. Bob, in Virginia, wants the same two.
To sell her the seats, the app has to:
- check she isn't over her monthly spending limit;
- make sure Bob can't get the same seats;
- record the sale in all three cities.
On one machine that's one transaction: a group of reads and writes that happens all together or not at all. Spread over three cities, each of those steps runs into a problem.
One machine isn't enough
Start simple: put every user, order, concert and seat on one machine in Singapore. What could go wrong? Two things:
- the machine runs out of room;
- every click Bob makes in Virginia crosses the Pacific and back.
So you cut the data up and keep each piece near the people who use it: you fragment (or partition) it. You can cut it in a few ways.
Horizontal, vertical and derived fragments
- By rows (horizontal). Asian users live in Singapore and American users in Virginia. Each piece is the rows matching a condition.
- By columns (vertical). People read a concert's name, city and date constantly and its long description almost never. Keep the hot columns in Tokyo and the cold ones somewhere cheaper. A join on the concert's ID, which both halves keep, puts the row back together.
- Rows that follow other rows (derived). An order lives wherever its user lives. "This user's orders" then never leaves the building. Joining users to their orders needs no network at all.
However you cut, three rules apply:
- Complete: every row ends up in some piece.
- Reconstructable: you can rebuild the original, with a union for row pieces and a join on the key for column pieces.
- Disjoint, ideally: no row in two pieces, which means you never update anything twice.
Derived fragments are only disjoint if every order points at exactly one user, which is why the link has to be a real key that's never empty.
Consistent hashing
Because seats change constantly, Tokyo spreads them over several servers. The app needs a rule for which server holds each concert, one that doesn't fall apart when a server is added. It hashes each concert to a number and places it on a ring. Each server sits at a point on the ring and owns the stretch just before it: a key belongs to the first server clockwise from where it lands. The usual alternative is hash % number_of_servers. Try adding a server under each:
With the remainder, adding a fourth server changes almost every key's home and moves nearly all the data. On the ring, the new server only takes one stretch from its neighbour. Real systems, like Cassandra and Amazon's Dynamo, also give each server many points on the ring ("virtual nodes"). That evens out the load and lets a bigger server take more points.
Local and global indexes
Now the app wants every order for one concert. Can you see the catch? Because orders are split by region, it has to ask Singapore and Virginia: a lookup that doesn't use the key you split by has to ask every piece.
An index helps. You choose what kind:
- A local index lives next to each piece and only covers that piece. It's cheap to keep up to date. A search still has to ask every site, though.
- A global index is split by the thing you search on (here, the concert), which lets one question find the right sites. But every new order now has to update the index somewhere else too. Fetching the rows also takes a second round trip.
DynamoDB has both. Its local secondary index keeps the table's own partition key. Its global secondary index is partitioned by a different key.
Shipping data between cities is slow
Before selling, the app has to add up Alice's orders this month for concerts outside Singapore and compare the total with her limit. Her orders are in Singapore and the concert cities are in Tokyo. Every byte sent between them takes time. So you plan the query to move as little data as you can, with a few tricks.
Pruning fragments
Replace each table with its pieces, then cross out the ones that can't contribute. Alice is in Asia, which rules out the American users and, with them, their orders. The query never reads descriptions either, which rules out the cold half of the concerts.
Join strategies
To join orders with concerts, matching rows have to end up on the same machine. Four standard ways make that happen:
Which one wins depends on how the tables are already split and how big they are. Broadcast looks wasteful, since it copies a whole table to every site. With a tiny table it's the cheapest of all; with a big one, the worst.
Semijoins and pushdown
The query only needs a few columns and a few concerts. The naive plan ships Tokyo's whole concerts table anyway. Step through three ways to shrink it:
- push the projections down;
- use a semijoin;
- push the selection down.
A semijoin costs an extra round trip. Tokyo can't start until the IDs arrive either. A planner only uses one when the bytes it saves beat the cost of sending the filter.
Aggregating early
Last, aggregate early. Singapore totals Alice's orders into one number before joining it with her user row, instead of carrying every order along. If her orders were spread over two sites, each would compute a subtotal and one site would add the two (or take the larger of two maximums, and so on). These rewrites only apply under conditions, roughly when grouping first can't change which rows match. When they do apply, they shrink everything that follows.
She's spent 330 this month. Two more tickets make 570, under her limit of 600. Great, she can buy!
Two buyers want the same seats
But at that very moment, Bob clicks buy on the same two seats. What do you think happens? Each city on its own behaves correctly. But Tokyo handles Alice first and Virginia handles Bob first. Put the two histories together and they say Alice came first and Bob came first. Both can't be true. Worse, both of them could end up paying for the same seats. A database is serializable when transactions running at the same time give the same result as running them one after another in some order. Across cities you need global serializability: one such order that every site agrees with.
Distributed locking and deadlock
The usual fix is locking. Under two-phase locking, a transaction takes all the locks it needs before it releases any. In the distributed version, each site locks its own data. A transaction holds all its locks, everywhere, until it has finished everywhere. (The alternative, one central lock manager for all sites, is simpler but becomes both a bottleneck and a single point of failure.) Holding locks that long creates a new way to get stuck:
You have two ways out:
- Detect the circle: someone collects the waiting lists from every site, builds one global "who waits for whom" graph, and aborts a transaction to break any cycle.
- Prevent it with a rule based on age.
In wound-wait, an older transaction never waits for a younger one: it aborts ("wounds") it instead. Only the young wait for the old. In wait-die, it's the reverse: the old may wait. A young one that would have to wait aborts itself. Either way, waiting only ever goes in one direction and no circle can form.
Under wound-wait, the database aborts Bob, the younger of the two. When he retries, the seats are gone. Sorry, Bob.
Snapshot isolation and write skew
Locking makes readers and writers wait for each other. Snapshot isolation avoids that: every transaction reads from a snapshot of the data as it was when it started. The database checks only the writes. If two transactions write the same item, one loses. Under first-committer-wins the second to commit aborts. Under first-updater-wins the second to write waits and aborts if the first commits.
Its blind spot is write skew. Suppose each buyer checks "fewer than 2 seats sold?" and then inserts their own sale row. Since their writes touch different rows, nothing flags a conflict. Both commit and the concert is oversold. Across sites there's an extra wrinkle: every site has to agree on which transactions are in a snapshot, which is why distributed versions hand out snapshot and commit timestamps carefully.
Part of a purchase can fail
Great! Alice has the seats and Bob is out of the way. Now the sale has to be recorded in all three cities. What if one of them crashes halfway? Say Tokyo marks the seats sold and then Singapore crashes before saving her order: the seats are gone and Alice has nothing to show for it. The purchase has to happen everywhere or nowhere.
Two-phase commit
Two-phase commit handles this with one site as the coordinator. Phase one asks everyone to vote; phase two announces the decision. Each site is a small state machine. Step through a normal run, then crash Singapore or Tokyo at different points and see what happens:
It works because every site writes to its own log before it speaks and forces those writes to disk. A yes vote is a promise: if Tokyo voted yes before saving READY, a crash could make it forget, wake up, and abort while everyone else commits. Likewise Singapore must save COMMIT before announcing it. Otherwise it could restart, find nothing, and abort after someone already committed.
The crashes show the rules a site follows when it stops hearing from the others (its termination protocol):
- A site that hasn't voted can always abort.
- A coordinator still waiting for votes can abort.
- A site that voted yes and is sitting in READY can't do anything alone.
That last one can ask the other participants (cooperative termination), which helps if any of them already knows the answer or voted no. If they're all in READY too, nobody knows the answer and everyone waits. So two-phase commit can block.
Three-phase commit
Three-phase commit removes that blocking by adding a step between "everyone voted yes" and "commit": PRECOMMIT, meaning "we're going to commit". Nobody commits until everyone has acknowledged PRECOMMIT. That gives survivors a rule they can follow without the coordinator: if anyone reached PRECOMMIT, everyone voted yes and they commit; if all of them are still in READY, nobody can have committed and they abort. Try the same crashes:
The network can still break it. Three-phase commit assumes a crashed site is really down. If the network splits instead, the two halves can each run the rule on their own, reach different answers, and end up inconsistent. Versions of the protocol that use quorums fix that, at the cost of blocking whichever side lacks a majority. In practice, many systems keep two-phase commit and make the coordinator itself survive crashes, by replicating it.
Machines die
Great! Alice's purchase is now recorded in all three cities. But what if the machine in Tokyo that holds the seats dies? Every sale for a Tokyo concert stops. If its disk is lost, so are the sales it recorded, including its READY note. So you keep every piece on several machines: you replicate it. Replicas also let reads go to a nearby copy. In exchange, every write has to reach several places and the copies have to stay consistent.
Eager and lazy replication
Two choices shape every replication scheme:
- Where writes go: to one primary copy that forwards them (simple, but the primary is a bottleneck), or to any copy (flexible, but two copies can accept conflicting writes).
- When the others hear about it: eagerly, inside the transaction, which keeps every copy up to date when it commits (slow, and a dead copy can hold everything up), or lazily, after it commits (fast, but copies lag and you can read stale data).
Ideally you want one-copy serializability: however many copies exist, the result looks as if there were one copy and the transactions ran one at a time. Read one, write all gets you there: a read can use any copy; a write must update every copy. But then a single dead copy blocks all writes. Writing to all available copies keeps going, at the cost of resynchronising the stragglers when they return.
Quorums
Or you meet in the middle with a quorum: a write must reach some number of copies and a read must ask some number. You choose the numbers so the groups always overlap. Pick them yourself:
You need two rules:
- Read and write groups must overlap: reads plus writes greater than the number of copies.
- Any two write groups must overlap: writes greater than half. Then two writes can't both succeed on disjoint halves.
Copies can carry different weights: a big data centre counts for more than a small one. And if copies do accept conflicting writes, a common tiebreak is last writer wins: keep the one with the later timestamp and drop the other.
When the network splits, a system has to choose between (the CAP trade-off):
- staying available, and risking inconsistent copies;
- staying consistent, and refusing some requests.
Raft log replication
For the most important data, like Tokyo's READY note, the copies need to agree on one exact sequence of updates. That's what Raft does. etcd and CockroachDB, for example, run on it. In Tokyo, five machines keep the same log. One leads. An entry counts once a majority has written it down. Crash some followers and send an entry:
Once three of the five have the entry, it's safe: any future majority includes at least one machine that has it. Every entry carries the term the leader created it in. The leader sends each new entry along with the index and term of the one before it. A follower only accepts it if its own log matches there; if not, the leader steps back through its log until they agree, then fills in the rest. That's how a lagging machine like TK5 catches up, and why logs that match at one entry match all the way back.
Raft leader election
When the leader dies, the others elect a new one. Every machine is a follower, a candidate, or a leader:
Two details make elections safe:
- Each term has at most one leader, because a machine votes at most once per term and a leader needs a majority.
- A machine only votes for a candidate whose log is at least as complete as its own: a later last term, or the same last term and at least as long.
One more rule: a new leader only counts an entry as committed by majority if it's from its own term. Older entries become committed indirectly, once a newer entry after them is.
Copies lag behind
Copies updated lazily run a little behind. So what does Alice see if she checks her tickets right after buying? Right after Alice buys, Virginia's copy of the seat count can still say 2 seats are left and her ticket list can still be empty. Which copy may answer depends on what you promised the reader. Different readers need different promises.
Consistency levels
Take a baseball game. Two records hold the score, one for the home team and one for the visitors. The scorekeeper writes to them as runs come in: seven writes take the score from 0-0 to 2-5. Writes go to the primary first and reach the other copies later, in the same order. Now people read the score. What a read may return depends on the consistency level it asks for. Pick a level and a moment in the game:
The levels, from strongest to weakest:
- Strong: you see every write that has completed. Only the latest value.
- Bounded staleness: you see every write older than some limit, say 30 minutes. Newer ones may or may not show.
- Consistent prefix: you see the writes in order, up to some point. The answer was the real score at some moment, just maybe not now.
- Monotonic reads: never older than what you've read before. Your view only moves forward.
- Read my writes: you always see your own writes. Ideal when you're the only writer.
- Eventual: anything that was ever written, for each record separately. Records can be out of step with each other, which is how a read can return 2-1, a score that never existed.
Pileus
The weaker the promise, the more copies can answer and the faster and cheaper the read. Pileus lets every read pick its own level. Each level turns into a minimum timestamp the answering copy must have caught up to, for example:
- for strong, the primary's latest;
- for monotonic reads, whatever you read last;
- for read my writes, your own last write to those keys.
Each copy advertises how far it has caught up. The client picks the nearest copy that's far enough along.
Back to Alice. After the purchase, she checks her tickets from Virginia. Virginia's own copy is quick but hasn't caught up to her purchase. Under "eventual" she'd be told she has no tickets, which is allowed and a terrible experience. Under "read my writes" the read skips Virginia for a copy that has caught up. Her tickets are there.
Pileus also does transactions over several keys. At commit, the primaries involved each propose a timestamp. The largest wins and every write gets it. This small negotiation on top of two-phase commit makes the transaction's writes appear at one moment everywhere.
Writes pile up
Now picture the concert going on sale, with orders pouring into Singapore. Updating each one in its place on disk means jumping around the disk for every write. At that rate, the disk can't keep up. So you never update in place.
LSM trees
An LSM tree (log-structured merge tree) is storage built for writes. Cassandra, RocksDB, and LevelDB all use one. New writes collect in memory and get flushed to disk as small sorted files that are never edited again. In the background, files merge into bigger ones, level by level.
Because files are never edited, deleting means writing a marker (a tombstone). The old value hangs around until a merge drops it. The marker itself has to stay until no older copy could still be hiding in a lower level.
Reads and Bloom filters
Reads may have to look in several places, newest first: memory, then each level. Two things keep that cheap:
- In level 1 and below, files cover separate key ranges. Each level needs at most one file checked.
- Before you read that file from disk, you check its Bloom filter, a tiny summary of which keys it holds. It answers "definitely not here" (always right) or "maybe" (sometimes wrong).
For keys that don't exist, the filter skips the disk read.
Compaction
How you merge is a balancing act between three kinds of waste:
- write amplification: rewriting the same record many times;
- read amplification: checking many files per read;
- space amplification: keeping stale versions around.
Size-tiered compaction waits until there are several files of similar size and merges them into one bigger file: little rewriting, but reads may check many files. Levelled compaction keeps each level as one sorted run of files that don't overlap. A read then checks at most one file per level. Every merge rewrites more, though.
Clocks disagree
Alice's purchase is confirmed. A moment later, her friend in Virginia opens the seat map. Will the friend see the seats as taken? Reads are ordered by timestamp. If Virginia's clock runs a few milliseconds behind Tokyo's, the friend's read can get an earlier timestamp than the purchase and still show the seats as free. Ordering by time needs every machine to agree on the time. Clocks never quite do.
Spanner and TrueTime
Google's Spanner fixes this. It splits the data into shards, replicates each shard with Paxos (a consensus algorithm like Raft, where a majority agrees on each update), and runs two-phase commit between the shards' leaders. On top of that it promises external consistency: if Alice's purchase finished before her friend started reading, the friend sees it, even on another continent.
Its clock, TrueTime, reports its error. It doesn't say "it's 1000"; it says "it's somewhere between 996 and 1004", using GPS and atomic clocks to keep that range small. When Alice's purchase commits, the coordinator picks a timestamp no smaller than any participant's proposal or the latest possible current time. Then it waits until even the earliest possible current time is past that timestamp, and only then tells Alice she's done. Play it:
That commit wait lasts a few milliseconds. It guarantees that anyone who starts later, anywhere, gets a later timestamp and sees the purchase. Without it, Spanner could confirm the purchase early. A friend starting a read right after could then pick an earlier timestamp and miss a purchase Spanner had already confirmed.
Lock-free snapshot reads
A read-only transaction picks a timestamp and reads a consistent snapshot without taking a single lock. A replica can serve it once it's sure it has everything up to that timestamp:
- it has applied all the updates before it;
- no transaction still in progress could commit at or before it.
Until then, it waits. That's how Spanner serves consistent reads from nearby replicas without asking the leader.
Everything in the course
Here's everything I learnt in the course: the 75 topics on the syllabus, the 33 algorithms I ran by hand, and the 20 families of variants. What a ride!
Further reading
- M. Tamer Özsu and Patrick Valduriez, Principles of Distributed Database Systems, 4th edition (2020). The course's textbook.
- Martin Kleppmann and Chris Riccomini, Designing Data-Intensive Applications, 2nd edition. The same ideas through real systems.
- Doug Terry, Replicated Data Consistency Explained Through Baseball, Communications of the ACM (2013). The baseball game.
- Diego Ongaro and John Ousterhout, In Search of an Understandable Consensus Algorithm (2014). Raft.
- James C. Corbett et al., Spanner: Google's Globally-Distributed Database, OSDI (2012). TrueTime and commit wait.
- Sanjay Ghemawat and Jeff Dean, LevelDB implementation notes. Levelled compaction and the search path.