Courses / System Design Interview / Chapter 8
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 8 of 49
Databases: Choosing, Replicating and Partitioning
Builds on Core Concepts: RPCs, Consistency, Failures and Time, Building Blocks: The Parts Every Design Reuses and Load Balancers. Next up: Design a Distributed Key-Value Store.
Part 1 · Choosing a store from access patterns
What a database promises
Almost every product keeps its state in a database, and a few choices at the start decide how far that state can grow. A database is a program that stores data durably, lets many clients read and write it at once, and answers questions about it faster than scanning files.
Two things make databases hard once a product succeeds. One machine eventually holds too much data or takes too many requests, so the data has to be copied or split across machines. And any machine can fail, so the system has to keep working when one disappears. This chapter follows those two forces: replication (copies) and partitioning (splits), after first choosing a kind of store.
The kind of store follows from the access pattern: which questions the application asks, how often, and how fast the answer must come. A train booking site asks 'which seats are free on this train' thousands of times a minute and 'what did this user book' once in a while. Those are different patterns, and they favour different stores.
The five families
A relational database stores rows in tables with a fixed schema, and joins tables with SQL. It gives transactions across several rows, which is why money and inventory usually live there. A document store keeps each record as a nested JSON-like document, so the data you read together is stored together, and the schema can vary between documents.
A key-value store maps a key to an opaque value and supports little more than get, put and delete. That narrow API is what lets it spread across many machines and answer in a millisecond. A wide-column store keeps rows addressed by a row key, with columns grouped into families, and sorts rows by key so that range scans over a key prefix are cheap. A graph database stores nodes and edges and is built for queries that follow connections several steps deep, such as friends of friends.
| Family | Shape of data | Best at | Weak at |
|---|---|---|---|
| Relational | Rows in tables with relations | Transactions, joins, ad hoc queries | Spreading one table over many machines |
| Document | Nested documents per key | Reading one entity in a single fetch | Joins across documents |
| Key-value | Key to opaque value | Huge scale, single-key speed | Queries on anything but the key |
| Wide-column | Sorted rows, column families | Heavy writes, range scans on a key | Flexible queries, multi-row transactions |
| Graph | Nodes and edges | Multi-hop relationship queries |
Matching a product to a store
Take a railway booking site. Seat inventory needs exact answers: two people must never hold the same seat, and a payment and a seat must succeed or fail together. That is a relational job. The train timetable is read millions of times and changes once a day, so it suits a cache in front of any store. The session of a logged-in user is a small blob looked up by an id, which is a key-value job.
A common mistake is to choose by fashion or by the largest number in the plan. A single well-provisioned relational server can hold terabytes and serve thousands of simple queries per second, and many products never outgrow one machine plus a few copies. Start from the access pattern, and move a part of the data to a different store only when a specific operation has become too slow or too large.
Many real systems use several stores at once, each holding the data it is best at, with one of them as the source of truth and the others filled from it. The cost is that copies can disagree for a while, which later lessons treat as a normal property and not a bug.
A product needs to show a user's recent order with its items and address in one fetch, and the shape of an order varies by category. Which family fits best?
- A document store: it keeps an order and its items together, so one fetch returns everything, and documents can differ in shape.
- A relational store also works if the shape is stable and joins or cross-order transactions matter.
What is an access pattern, and why start from it?
- It is the list of queries the application runs, how often, and how fast each must be.
- Different stores make different operations cheap, so the pattern tells you which trade you are making.
Why can a single relational server be enough for a long time?
- One well-provisioned server can hold terabytes and serve thousands of simple queries a second, and copies for reads and backups extend that further. Move data out only when a measured operation becomes too slow.
Part 2 · Transactions and isolation
What a transaction guarantees
A bank transfer subtracts 300 from one account and adds 300 to another. If the program stops between the two steps, money has disappeared. A transaction groups steps so that the database treats them as one unit. Its guarantees are summed up as ACID.
- Atomicity: all the steps happen, or none of them do. A failure part-way undoes the steps already taken.
- Consistency: a transaction moves the data from one valid state to another, where valid is defined by constraints such as a balance that cannot go negative. This C is about constraints, not the consistency models of the core concepts chapter.
- Isolation: transactions running at the same time do not see each other's half-finished work.
- Durability: once the database reports a commit, the change survives a crash, because it was written to disk first.
Atomicity is easiest to see by breaking a transfer. The program below creates two accounts with a rule that a balance cannot drop below zero. The transfer credits the receiver first and debits the sender second. When the debit violates the rule, the database rolls the whole transaction back, including the credit that had already run.
import sqlite3 db = sqlite3.connect(":memory:", isolation_level=None) db.execute( "CREATE TABLE acct (name TEXT PRIMARY KEY, " "bal INTEGER CHECK (bal >= 0))" ) db.execute("INSERT INTO acct VALUES ('asha', 100), ('ravi', 500)") def move(src, dst, amount): db.execute("BEGIN IMMEDIATE") try: db.execute("UPDATE acct SET bal = bal + ? WHERE name=?", (amount, dst)) db.execute("UPDATE acct SET bal = bal - ? WHERE name=?", (amount, src)) db.execute("COMMIT") return "committed" except sqlite3.IntegrityError as e: db.execute("ROLLBACK") return "rolled back: " + str(e)
tx_abort.py: a transfer that must roll back
print(move("asha", "ravi", 300)) print(db.execute("SELECT * FROM acct ORDER BY name").fetchall()) print(move("ravi", "asha", 300)) print(db.execute("SELECT * FROM acct ORDER BY name").fetchall())
rolled back: CHECK constraint failed: bal >= 0 [('asha', 100), ('ravi', 500)] committed [('asha', 400), ('ravi', 200)]
Python 3.12.10 on this machine. Deterministic.
Isolation and snapshots
Isolation is the expensive guarantee, so databases offer levels. The strongest, serializable, makes the outcome the same as if the transactions had run one after another. Weaker levels allow anomalies, which are results that no one-at-a-time order could produce. A dirty read sees data another transaction has not committed. A non-repeatable read gets a different answer when it reads the same row twice. A lost update happens when two transactions read a value, both add to it, and the second write overwrites the first. Write skew happens when two transactions each read a set of rows, then update different rows based on what they read, so a rule that spans the rows breaks.
Many databases implement isolation with snapshots. When a transaction starts it sees the database as it was at that moment, and writes that commit later stay invisible to it. This is called snapshot isolation, and it means readers never wait for writers. The SQLite documentation says all its transactions are serializable, because it lets only one writer run at a time, and that in write-ahead log mode a reader keeps an unchanging snapshot while a writer commits.
The next program, which uses a fresh database, opens two connections to the same file in that mode. The reader starts a transaction and reads Asha's balance. The writer then commits a transfer. The reader reads again before it finishes, and once more after it ends.
import os, sqlite3, tempfile path = os.path.join(tempfile.mkdtemp(), "bank.db") setup = sqlite3.connect(path, isolation_level=None) setup.execute("PRAGMA journal_mode=WAL") setup.execute( "CREATE TABLE acct (name TEXT PRIMARY KEY, bal INTEGER)") setup.execute("INSERT INTO acct VALUES ('asha', 1000), ('ravi', 500)") reader = sqlite3.connect(path, isolation_level=None) writer = sqlite3.connect(path, isolation_level=None) total = "SELECT SUM(bal) FROM acct" asha = "SELECT bal FROM acct WHERE name='asha'" reader.execute("BEGIN") print("reader sees asha =", reader.execute(asha).fetchone()[0]) writer.execute("BEGIN IMMEDIATE") writer.execute("UPDATE acct SET bal = bal - 300 WHERE name='asha'") writer.execute("UPDATE acct SET bal = bal + 300 WHERE name='ravi'") writer.execute("COMMIT") print("writer committed a transfer of 300") print("reader still sees asha =", reader.execute(asha).fetchone()[0]) reader.execute("COMMIT") print("a new read sees asha =", reader.execute(asha).fetchone()[0]) print("total is still", reader.execute(total).fetchone()[0])
tx.py: a reader keeps its snapshot while a writer commits
reader sees asha = 1000 writer committed a transfer of 300 reader still sees asha = 1000 a new read sees asha = 700 total is still 1500
Python 3.12.10 on this machine. Deterministic.
What isolation costs you
A snapshot gives a stable view, and it has a price: a transaction that read old data and then tries to write based on it may conflict with a newer commit. In SQLite's write-ahead log mode, a read transaction whose snapshot is no longer the latest fails with SQLITE_BUSY_SNAPSHOT when it tries to become a writer. Its documentation suggests starting a transaction that will write with BEGIN IMMEDIATE, which takes the write lock at the start. The same advice appears in other systems as 'lock the rows you plan to change'.
Many databases default to a level weaker than serializable, because stronger levels cost throughput or cause more aborted transactions. PostgreSQL's default, for example, is Read Committed. The practical rules are short. Keep transactions small and short. Do not hold one open while waiting for a user or a network call. When a rule spans several rows, such as 'a coach holds at most 72 bookings', do not trust a weak level to enforce it: use a constraint, lock the rows, or run that transaction at the serializable level.
The distinction matters for the rest of the chapter. Everything above happens on one machine, where the database can order operations itself. Once data is copied to other machines, those machines receive changes at different times, and the guarantees get weaker unless the system pays for them.
In the snapshot run, why did the reader see 1000 after the writer had committed 700?
- The reader's transaction started before the commit, and it keeps the snapshot from that moment until it ends. A new transaction started afterwards sees 700.
In the rollback run, Ravi was credited before Asha was debited. Why did his balance return to 500?
- The failed debit aborted the whole transaction. Atomicity means the credit that already ran is undone with it.
What is a lost update, and what is one way to prevent it?
- Two transactions read the same value, each adds to it, and the second write erases the first.
- Use an atomic update such as
SET n = n + 1, lock the row first, or run at a level that detects the conflict.
Part 3 · Leader-follower replication
Why copy the data
Replication keeps copies of the same data on several machines. It serves three goals: reads spread over more machines, a failed machine does not take the data with it, and copies can sit closer to users in other cities. The simplest arrangement is leader-follower replication, also called primary-replica.
One machine is the leader. Every write goes to it. It appends each change to an ordered log and sends that log to the followers, which apply the changes in the same order. Followers serve reads. Because the log is ordered, a follower that has applied the first n entries holds exactly the data the leader held after n changes.
The key choice is when the leader reports 'committed'. With asynchronous replication it answers as soon as its own disk has the change, and ships the change afterwards. Writes are fast, but a follower can be behind, the lag of the core concepts chapter. With synchronous replication it waits until a follower has confirmed, so a crash of the leader cannot lose an acknowledged write, but each write is as slow as the slowest follower it waits for and stalls if that follower is down.
PostgreSQL 18 exposes this as synchronous_commit. The default, on, waits until the synchronous standbys have flushed the commit to durable storage, or only for the local flush when none are configured. remote_apply also waits until a standby has applied the change, so queries there see it, and off does not wait even for the local flush. synchronous_standby_names picks the standbys: FIRST n by priority, ANY n whichever n reply first. A standby serves read-only queries when hot_standby is on, the default.
Lag and what users notice
Lag is invisible until a user acts on something they just did. The model below has a leader and two followers that apply each change three ticks after the leader. A write lands at tick 0 and is read from a follower at ticks 0, 2 and 3.
class Node: def __init__(self, name): self.name, self.data, self.log = name, {}, [] class Cluster: """One leader, followers that apply the leader's log after a lag.""" def __init__(self, followers, lag): self.leader = Node("leader") self.followers = [Node(f) for f in followers] self.lag, self.now, self.pending = lag, 0, [] def write(self, key, value): self.leader.data[key] = value self.leader.log.append((key, value)) for f in self.followers: self.pending.append((self.now + self.lag, f, key, value)) def tick(self, n=1): self.now += n due = [p for p in self.pending if p[0] <= self.now] self.pending = [p for p in self.pending if p[0] > self.now] for _, f, k, v in due: f.data[k] = v f.log.append((k, v))
repl.py: a leader and followers that apply changes after a lag
c = Cluster(["f1", "f2"], lag=3) c.write("bio:asha", "new bio") print("t=0 leader:", c.leader.data.get("bio:asha")) print("t=0 f1 :", c.followers[0].data.get("bio:asha")) c.tick(2) print("t=2 f1 :", c.followers[0].data.get("bio:asha")) c.tick(1) print("t=3 f1 :", c.followers[0].data.get("bio:asha"))
Continues repl.py.
t=0 leader: new bio t=0 f1 : None t=2 f1 : None t=3 f1 : new bio
Python 3.12.10 on this machine. Deterministic: the lag is simulated.
The run breaks read-your-writes, the session guarantee from the core concepts chapter. The user saved a change and the next page load went to a follower that had not received it, so the change seemed lost until the follower caught up.
Repairing read-your-writes
A fix is to send a user's reads to the leader briefly after that user writes, and to followers otherwise. The run below sends 2,000 random operations from 50 users, one in five a write, and counts stale reads of a user's own recent write: first with every read sent to a follower, then with a user's reads sent to the leader for ten ticks after their write.
import random from repl import Cluster def run(policy, seed=7, ops=2000): rnd = random.Random(seed) c = Cluster(["f1", "f2"], lag=3) stale = 0 # user -> tick of last own write last_write = {} for _ in range(ops): u = rnd.randrange(50) if rnd.random() < 0.2: c.write(f"bio:{u}", c.now) last_write[u] = c.now else: mine = u in last_write and c.now - last_write[u] < 10 node = c.leader if policy == "leader-after-write" and mine \ else rnd.choice(c.followers) if mine and node.data.get( f"bio:{u}") != c.leader.data[f"bio:{u}"]: stale += 1 c.tick() return stale for policy in ("any-follower", "leader-after-write"): print(f"{policy:20} stale reads of own writes: {run(policy)}")
ryw.py, next to repl.py: reads of your own writes, stale or fixed
any-follower stale reads of own writes: 11 leader-after-write stale reads of own writes: 0
Python 3.12.10 on this machine. Deterministic: seeded.
Eleven reads were stale when every read went to a follower, and none when recent writers read from the leader. The cost is more load on the leader, so the window should match the real lag.
Watch for where Asha's read goes in the seconds after she writes
Read it as steps
Failover
The harder problem is failover. When the leader fails, a follower must become the new leader. It needs a failure detector, a rule for choosing a follower whose log is complete, and a way to stop the old leader from taking writes. Consensus protocols such as Raft handle all three. In the Raft paper, a follower that hears nothing from the leader for an election timeout increases its term, a counter of elections, and asks for votes. Each server votes for at most one candidate per term and refuses a candidate whose log is less up to date than its own. A candidate with votes from a majority of the cluster becomes leader, and a leader that sees a higher term steps down. Such a group makes progress while any majority is available, so five nodes survive two failures.
Watch for reads fanning out to followers while writes all go to the leader
Read it as steps
Followers share the reads; when the leader dies, a follower with the log takes over.
With asynchronous replication, failover can lose data. The next run writes five orders one tick apart and then crashes the leader.
from repl import Cluster c = Cluster(["f1", "f2"], lag=3) for i in range(1, 6): c.write(f"order:{i}", "paid") c.tick() print("leader has", len(c.leader.log), "writes") print("f1 has ", len(c.followers[0].log), "writes") print("f2 has ", len(c.followers[1].log), "writes") print( "leader crashes, asynchronous replication, promote the follower") new = max(c.followers, key=lambda f: len(f.log)) lost = [k for k, _ in c.leader.log if k not in new.data] print("promoted", new.name, "with", len(new.log), "writes; lost:", lost)
failover.py: promoting a follower after a crash
Reads after a leader change
Failover also changes what a read can return. A customer who saw order 5 a moment ago can find it missing on the new leader. And the old leader may not know it was replaced: a long pause or a network partition can leave it answering reads from data that a new leader has already changed.
The Raft paper names this risk and two precautions. A new leader commits a blank no-op entry at the start of its term, so that it learns which entries are committed. And before answering a read, a leader exchanges heartbeats with a majority to confirm that it has not been deposed. A lease can replace the heartbeat round, and the paper notes that a lease relies on bounded clock skew. The model below cuts the old leader off, elects a new one, books a seat, and reads at the old leader with and without the check.
# n1 led term 1; a partition now cuts it off from n2 and n3. term = {"n1": 1, "n2": 1, "n3": 1} data = {n: {"seat:12A": "free"} for n in term} cut_off = {"n1"} def peers(n): return [m for m in term if (m in cut_off) == (n in cut_off)] def read_checked(n, key): """A leader confirms its term with a majority before it answers.""" newer = [term[m] for m in peers(n) if term[m] > term[n]] if newer: term[n] = max(newer) return f"stepped down to follower in term {term[n]}, retry" if len(peers(n)) * 2 <= len(term): return f"refused: {len(peers(n))} of 3 confirm term {term[n]}" return data[n][key]
leaderchange.py: terms, a partition and a checked read
from leaderchange import term, data, cut_off, peers, read_checked votes = peers("n2") # n2 times out and asks for votes for n in votes: term[n] = 2 print("n2 wins term 2 with votes from", votes) for n in peers("n2"): # a majority stores the booking data[n]["seat:12A"] = "booked" print("booking committed on", peers("n2")) print("plain read at n1 :", data["n1"]["seat:12A"]) print("checked read at n1:", read_checked("n1", "seat:12A")) cut_off.clear() # the partition heals print("after the heal :", read_checked("n1", "seat:12A")) print("checked read at n2:", read_checked("n2", "seat:12A"))
leaderchange_run.py: a new leader, then reads at the old one
n2 wins term 2 with votes from ['n2', 'n3'] booking committed on ['n2', 'n3'] plain read at n1 : free checked read at n1: refused: 1 of 3 confirm term 1 after the heal : stepped down to follower in term 2, retry checked read at n2: booked
Python 3.12.10 on this machine. Deterministic: a model with no logs or timers.
Node n2 won term 2 with two of three votes and committed the booking. Node n1 still believed it led term 1, and a plain read there returned free for a booked seat. The checked read reached only n1 itself, so it refused. After the heal, the check met term 2, n1 stepped down, and the new leader returned booked. The model skips logs and timers; it shows only why a leader's read needs a majority's confirmation.
Part 4 · Multi-leader and leaderless replication
More than one place to write
A single leader is a bottleneck for writes and a single point of failure for them. Two other designs remove it. In multi-leader replication several nodes accept writes, usually one per data centre, and each forwards its writes to the others. A user in Mumbai writes to the Mumbai leader at normal speed, and the Delhi leader picks the change up later. In leaderless replication any replica accepts a write, and the client or a coordinator sends it to several replicas at once.
Both designs give up the single order of writes that a leader provides, so two users can change the same item at about the same time on different nodes. That is a write conflict. The simplest resolution is last-write-wins: attach a timestamp to each write and keep the highest. It is easy, and it silently discards the other change.
# Two leaders accept a write to the same key at nearly the same time. a = {"title": ("Intro", 100)} # value, timestamp b = {"title": ("Intro", 100)} a["title"] = ("Databases 101", 101) # editor in Mumbai b["title"] = ("Databases, Part 1", 102) # editor in Delhi def merge_lww(x, y): return {k: max(x[k], y[k], key=lambda v: v[1]) for k in x} print("leader A:", a["title"]) print("leader B:", b["title"]) print("after replication, last-write-wins keeps:", merge_lww(a, b)["title"]) print("the Mumbai edit is gone without a trace")
multileader.py: two leaders accept the same key
leader A: ('Databases 101', 101) leader B: ('Databases, Part 1', 102) after replication, last-write-wins keeps: ('Databases, Part 1', 102) the Mumbai edit is gone without a trace
Python 3.12.10 on this machine. Deterministic.
Both editors saw their own change succeed. After the leaders exchanged writes, the one with timestamp 102 won, and the Mumbai edit vanished with no error. Better strategies keep both versions and merge them, or detect the conflict with version information, which the next chapter shows with vector clocks. Wherever you can, avoid the conflict by sending all writes for one item to the same leader.
Quorums
In a leaderless system with N replicas of each item, a write is sent to all N and counts as successful when W of them acknowledge. A read asks R replicas and takes the newest answer. The settings are chosen so that the replicas a read asks overlap with the replicas a write reached: if W + R > N, at least one replica in any read set holds the latest acknowledged write. That condition is called a quorum condition. The Cassandra documentation states the rule as W + R > RF, where RF is the replication factor, and defines its QUORUM level as a majority, n/2 + 1, of the replicas. The Dynamo paper reports (3, 2, 2) as the common setting for N, R and W.
The overlap can be counted without any network. For N = 3, the program below lists every set of replicas a write could reach and every set a read could ask, and counts the combinations where the read contained no replica that holds the write.
from itertools import combinations N = 3 replicas = range(N) def check(w, r): """All ways a write reaches w replicas and a read asks r.""" missed = total = 0 for wset in combinations(replicas, w): for rset in combinations(replicas, r): total += 1 # read saw no copy of the write if not set(wset) & set(rset): missed += 1 return missed, total print(" W R W+R>N reads that miss the write") for w, r in [(1, 1), (2, 1), (1, 2), (2, 2), (3, 1), (1, 3)]: missed, total = check(w, r) print(f" {w} {r} {str(w + r > N):5} {missed} of {total}")
quorum.py: every write set against every read set, N = 3
W R W+R>N reads that miss the write 1 1 False 6 of 9 2 1 False 3 of 9 1 2 False 3 of 9 2 2 True 0 of 9 3 1 True 0 of 3 1 3 True 0 of 3
Python 3.12.10 on this machine. Deterministic: exhaustive.
What the counts mean
With W = R = 1, six of the nine combinations miss the write, so most reads return an old value. With W = 2 and R = 2, none miss: any two replicas out of three must share at least one. W = 3 with R = 1 never misses, and neither does W = 1 with R = 3, but they push the cost to one side. A write that must reach all three fails when any replica is down. A read that must ask all three has the same problem.
| W | R | Reads can be stale | Good for |
|---|---|---|---|
| 1 | 1 | Yes | Lowest latency, data that tolerates stale reads |
| 2 | 2 | No, for acknowledged writes | Balanced default for N = 3 |
| 3 | 1 | No | Read-heavy data; a write fails if any replica is down |
| 1 | 3 | No | Write-heavy data; a read fails if any replica is down |
R1
Reads can be staleYes
Good forLowest latency, data that tolerates stale reads
R2
Reads can be staleNo, for acknowledged writes
Part 5 · Partitioning
Splitting data across machines
Copies help reads and survival, but every copy holds all the data. When the data or the write load is larger than one machine, you split it. Partitioning, also called sharding, divides a dataset so each partition lives on its own node, and each node may itself be replicated. The partition key decides where a row goes.
Two methods dominate. Range partitioning assigns contiguous ranges of the key to partitions, such as orders 1 to 2,50,000 in the first. Neighbouring keys stay together, so a range scan reads one or two partitions. Hash partitioning applies a hash function to the key and uses the result to choose a partition, which spreads keys evenly and destroys their order. PostgreSQL's declarative partitioning offers range, list and hash methods, and other databases offer similar ones.
The danger of range partitioning is a hot spot: one partition receiving most of the load. If the key grows with time, such as an order id or a timestamp, all new writes go to the last range. The run below sends the newest 1,000 orders to four range partitions and to four hash partitions.
import hashlib from collections import Counter # Four range partitions over order ids that only ever grow. bounds = [250_000, 500_000, 750_000] # p0 | p1 | p2 | p3 def range_part(order_id): return sum(order_id >= b for b in bounds) def hash_part(order_id): return hashlib.sha256(str(order_id).encode()).digest()[0] % 4 # 1,000 orders placed today newest = range(900_000, 901_000) print("range:", sorted(Counter(range_part(i) for i in newest).items())) print("hash: ", sorted(Counter(hash_part(i) for i in newest).items()))
rangehot.py: new orders under range and hash partitioning
range: [(3, 1000)] hash: [(0, 250), (1, 240), (2, 275), (3, 235)]
Python 3.12.10 on this machine. Deterministic.
All 1,000 writes landed on partition 3 under range partitioning, and spread within about 10 percent of an even split under hashing. Hashing fixes write hot spots and costs range scans. A compromise is a compound key, such as user id then time, that hashes the first part and keeps the second part ordered.
Rebalancing without moving everything
Nodes join and leave, and the partitioning must follow. The obvious placement, hash(key) mod N, breaks when N changes, because almost every key's remainder changes with it. Moving most of the data on every resize is far too expensive.
Consistent hashing is the usual answer. The load balancer chapter built the ring, with each node at many points on it: adding a node takes over only the keys between it and its predecessor, and removing one hands its keys to its successor. Here the point is why partitioning needs it. The run below compares the two placements for 10,000 keys when a fourth node becomes five.
import hashlib from bisect import bisect def h(s): return int.from_bytes( hashlib.sha256(s.encode()).digest()[:8], "big") keys = [f"user:{i}" for i in range(10000)] def mod_owner(key, nodes): return h(key) % nodes class Ring: def __init__(self, names, vnodes=100): self.points = sorted( (h(f"{n}#{i}"), n) for n in names for i in range(vnodes)) self.hashes = [p[0] for p in self.points] def owner(self, key): i = bisect(self.hashes, h(key)) % len(self.points) return self.points[i][1]
partition.py: keys moved when a node is added
before = {k: mod_owner(k, 4) for k in keys}
after = {k: mod_owner(k, 5) for k in keys}
print("mod N, 4 -> 5 nodes: moved",
sum(before[k] != after[k] for k in keys))
r4 = Ring([f"n{i}" for i in range(4)])
r5 = Ring([f"n{i}" for i in range(5)])
moved = [k for k in keys if r4.owner(k) != r5.owner(k)]
print("ring, 4 -> 5 nodes: moved", len(moved),
"| all to n4:", all(r5.owner(k) == "n4" for k in moved))
print("ideal share to move: about", len(keys) // 5)mod N, 4 -> 5 nodes: moved 7973 ring, 4 -> 5 nodes: moved 2052 | all to n4: True ideal share to move: about 2000
Python 3.12.10 on this machine. Deterministic.
Modulo placement moved 7,973 of 10,000 keys, close to the four fifths that change in theory. The ring moved 2,052, close to the ideal share of one fifth, and the check printed True: every moved key went to the new node, n4. Both runs use the same keys and the same hash.
Other rebalancing schemes
A ring is one answer. Another is to create many more partitions than nodes at the start, say 1,000 partitions over 10 nodes, and to move whole partitions between nodes when nodes change. The key-to-partition mapping never changes, so only the partition-to-node table does. Many systems also split a partition when it grows past a size limit, and merge small ones. Automatic rebalancing is convenient, and it can add load at the moment the cluster is already stressed, so some teams prefer to approve each move.
A directory service is the last piece. Clients must find the right node for a key, which they do by asking a routing tier, by asking any node and following a redirect, or by caching the partition map. Whichever is chosen, the map must be updated when partitions move, and a stale map must lead to a redirect and not to a wrong answer.
Why does hash(key) mod N fail when you add a node?
- Changing N changes the remainder for most keys, so nearly all data has to move. The run moved 7,973 of 10,000.
What is a hot spot, and which partitioning method causes it when keys grow over time?
- One partition receiving most of the load. Range partitioning on an increasing key sends all new writes to the last range.
In the ring run, where did the moved keys go when a fifth node joined?
- All of them went to the new node. Existing nodes did not exchange data with each other.
Part 6 · Choosing a store, and indexes across partitions
Secondary indexes and partitions
Partitioning by a key makes queries on that key cheap. A lookup for one user goes straight to the one partition that owns it. But products also ask other questions, such as 'all users in Kochi'. Those need a secondary index, an extra structure keyed by a column other than the partition key.
There are two ways to build one across partitions. A local index lives in each partition and covers only that partition's rows. Writes stay on one node, because the row and its index entry are together, but a query on the indexed column has to ask every partition and merge the answers. This is called scatter-gather. A global index is itself partitioned by the indexed value, so a query for one city goes to one partition. Reads are cheap, but a write to a row may have to update an index entry on a different node, which makes writes slower and harder to keep consistent.
import hashlib from collections import defaultdict SHARDS = 4 def shard_of(user_id): return hashlib.sha256(str(user_id).encode()).digest()[0] % SHARDS cities = ["Pune", "Chennai", "Jaipur", "Kochi"] users = {i: cities[i % 4] for i in range(1, 41)} data = [dict() for _ in range(SHARDS)] local = [defaultdict(set) for _ in range(SHARDS)] # index per shard for uid, city in users.items(): s = shard_of(uid) data[s][uid] = city local[s][city].add(uid)
secindex.py: one lookup by key, then by city two ways
# Query by partition key: one shard. print("get user 17: shards asked = 1 ->", data[shard_of(17)][17]) # Query by city with local indexes: every shard must be asked. hits = [local[s]["Kochi"] for s in range(SHARDS)] print("users in Kochi, local indexes: shards asked =", SHARDS, "-> found", sum(len(x) for x in hits)) # A global index partitioned by city: one shard, but writes touch two. global_index = defaultdict(set) for uid, city in users.items(): global_index[city].add(uid) print("users in Kochi, global index: shards asked = 1 -> found", len(global_index["Kochi"]))
get user 17: shards asked = 1 -> Chennai users in Kochi, local indexes: shards asked = 4 -> found 10 users in Kochi, global index: shards asked = 1 -> found 10
Python 3.12.10 on this machine. Deterministic.
The lookup by user id asked one of four partitions. The city query with local indexes asked all four to find ten people, and the global index answered from one. With four partitions the difference is small. With four hundred, a local-index query touches four hundred nodes, and its latency is set by the slowest of them.
Putting the choices together
The decisions in this chapter fit one checklist. Start from the queries and choose the family. Decide the isolation each operation needs. Choose a replication mode from how much loss you can tolerate on failure and how much write latency you can afford. Choose the partition key from the dominant query and from where writes will land. Then list the other queries and decide how each is served: a local index, a global index, a copy of the data in another store, or a slow path that is allowed to be slow.
| Decision | Question to ask | Typical answer |
|---|---|---|
| Store family | Which operation must be fast? | Relational by default, others for a measured reason |
| Isolation | What breaks if two users interleave? | Serializable or locks for money and inventory |
| Replication | How much loss on a crash is acceptable? | Synchronous to one standby for payments, asynchronous elsewhere |
| Partition key | Where do reads and writes land? | A hash of the entity id, or a compound key |
| Other queries | Can they be slow, or stale? | Local index, global index, or a derived copy |
Apply it to a railway booking site. Seat inventory is relational with serializable transactions on the seat rows, partitioned by train and date so that one booking touches one partition. Each partition has a synchronous standby, because a lost booking is a refund. Search for trains between two stations is a read-heavy query and runs from a derived copy in a search index or a cache, which may be a few seconds stale. User sessions live in a key-value store.
Each of these choices has a cost that appears later: more copies to keep in sync, more partitions to rebalance, more indexes to maintain. The next chapter builds one of these systems from the ground up, a key-value store that spreads data with consistent hashing, replicates with quorums, and detects conflicting versions with vector clocks.
Terms
| Term | Meaning |
|---|---|
| Access pattern | The queries an application runs, with their frequency and latency needs |
| ACID | Atomicity, consistency, isolation and durability of transactions |
| Snapshot isolation | Each transaction reads the database as it was when it began |
| Replication lag | How far a follower is behind the leader |
| Read-your-writes | A user always sees their own earlier writes |
| Quorum | Enough replicas that any read set overlaps any acknowledged write set |
| Hot spot | A partition that receives a disproportionate share of the load |
| Scatter-gather | Asking every partition and merging the answers |
A query by city must be fast and cheap on a 400-partition table partitioned by user id. Which index fits, and what does it cost?
- A global index partitioned by city, so the query asks one partition.
- Writes must update the index on a second node, so they are slower and harder to keep consistent.
In the run, how many partitions did the lookup by user id contact, and the city query with local indexes?
- One partition for the user id, and all four for the city query.
Why is synchronous replication chosen for seat bookings but not for a trending page?
- Losing an acknowledged booking costs a refund and trust. A trending page can be stale or rebuilt at no real cost.