Chapter 24 — Distributed Systems Theory II: Replication, Partitioning, Quorums & Consensus
Part V · Distributed Systems, Messaging & Scale | Prerequisites: Ch 23 | Builds: how Pulsely's data is replicated and partitioned
The previous chapter gave you the honest bad news: the moment a fact lives in two places, you've inherited the network's right to drop, delay, duplicate, and reorder, and you've lost a single global now, a single global order, and exactly-once effects. It named the disease. It deliberately did not prescribe the medicine. This chapter is the medicine — the three mechanisms every real system uses to survive a node dying, to outgrow a single machine, and to make a herd of independent computers behave like one honest one. Those three mechanisms are replication (the same data on many nodes), partitioning (different data on different nodes), and consensus (nodes agreeing on a single ordered history). Keep them separate in your head. They solve three different problems and beginners conflate them constantly, which is how you end up "scaling" by adding read replicas to a system whose actual bottleneck is write throughput, and being baffled when nothing improves.
By the end you'll be able to choose Pulsely's replication and partitioning strategy from invariants — from what each design can and can't guarantee — rather than from whatever a cloud console pre-selected for you. You'll know why R + W > N is just pigeonhole arithmetic, why hash mod N is a trap that turns adding one server into a cluster-wide outage, and why you will almost certainly never write Raft yourself but will depend, every day, on someone who did. This is a heavy, concept-dense chapter. It earns its length.
1. The problem: you've outgrown one machine, and one machine was where correctness was free
Let me give you three pages from the same incident log, because they're three different problems that the word "scale" hides under one roof.
Page one: the flu-season Monday. Pulsely runs on a single, beefy Postgres primary. It's been fine for two years. At 08:00 on the first Monday of flu season — every clinic open, every provider opening a worklist and charting at once — the box pins at 100% CPU and stays there. Reads and writes are now fighting each other for the same cores and the same buffer cache; the analytics dashboard query and the INSERT INTO encounters are in a knife fight, and p99 on chart-save climbs from 80 ms to 4 seconds. Someone suggests "scale up the box." You're already on the largest instance the cloud sells. There is no bigger box. You have hit the ceiling of vertical scaling, the thing the previous chapter warned existed but pointedly did not solve. One machine is no longer enough machine.
Page two: the stale chart. A week earlier, to take read load off that same primary, you added a read replica and routed some SELECTs to it. It worked — until a nurse corrected a patient's legal name, hit save, the chart refreshed, and showed the old name. "I just changed that." She changes it again. Same thing. She files a bug — and in a chart, a wrong name next to a wrong allergy is not cosmetic. You can't reproduce it in staging, because staging is a single node and a single node has no replica to lag. The write went to the primary; the refresh read from a replica that was 600 ms behind. Nothing crashed. The system is "working." The clinician is furious. This is replication lag, and it is the tax you pay the instant the same fact lives in two places.
Page three: the 800 GB table. The observations table — every vital sign streamed in from every remote-monitoring device — is now 800 GB. A single index on it no longer fits in RAM, so every query that misses cache hits disk. Nightly backups take nine hours and aren't done before the morning traffic arrives. A routine schema migration takes an ACCESS EXCLUSIVE lock and freezes the entire product for the duration. You cannot keep this table on one machine — not because the machine is slow, but because the data no longer fits the operational envelope of a single machine. You have to split it across several.
Three pages, three distinct problems, and this is the crux of the whole chapter:
- Replication answers "I want more copies, for availability and read scale." (page two's tool, page two's tax)
- Partitioning answers "I want more machines, for write and storage scale." (page three's tool)
- Consensus answers "given all these copies, how do they agree on what's true?" (the glue under both)
None of this is free. Every copy you make and every split you introduce creates a window in which two nodes disagree about reality. The entire engineering discipline of this chapter is the management of that disagreement window — making it small, making it bounded, making it tolerable for the features that can tolerate it, and refusing it entirely for the features that can't.
🧭 A useful distinction. "Scaling" is not one verb. Read scaling (more identical copies to serve reads) and write scaling (more machines each owning a slice of the writes) are completely different operations with completely different costs and failure modes. Conflating them is the single most common reason a "scaling project" delivers nothing: a team drowning in writes adds read replicas, watches the write bottleneck stay exactly where it was, and concludes "distributed systems are hard." The system was telling you which axis to grow. You grew the other one.
2. The mental model: three orthogonal axes, four pictures
Hold one structural picture and four small operational ones.
The three axes
The structural picture is a coordinate system. There are three axes, and they are orthogonal — you can dial each independently, and real systems sit somewhere on all three at once.
REPLICATION ─ same data, N copies (survive node death, scale reads)
PARTITIONING ─ different data per node (scale writes, scale storage)
CONSENSUS ─ nodes agree on one history (behave like one honest machine)
A production database is usually all three stacked: the data is partitioned into slices, each slice is replicated onto several nodes for safety, and each replica set runs a consensus protocol so its copies agree on the order of writes. When you read "a sharded, replicated cluster," that sentence is naming a point on all three axes. Lose the ability to keep them separate and every later sentence in this chapter blurs.
Picture one — replication is timeline-copying
There is one logical sequence of writes — call it the leader's timeline: write 1, write 2, write 3, … Replicas are observers trying to stay caught up to that timeline. A replica that has applied up to write 3 while the leader is on write 7 is simply four writes behind. "Lag" is not a mysterious property; it's a distance along a timeline. Once you see it this way, "read-your-writes" is obvious: a reader who just produced write 7 must not be served by an observer who's only seen up to write 3.
Picture two — partitioning is routing
Given a key, a deterministic function tells you which node owns its data: owner = route(key). That part is easy. The genuinely hard part is not the lookup — it's moving ownership. When you add a node, some keys must change owners, and they must do so without losing the requests that arrive mid-move. Partitioning is a routing problem that becomes a migration problem the instant the cluster changes shape.
Picture three — quorums are overlap arithmetic
If every write must be acknowledged by a majority of replicas, and every read must consult a majority of replicas, then the write-majority and the read-majority cannot be disjoint — two majorities of the same set must share at least one member. That shared node saw the latest write, so the read sees it too. Agreement falls out of the pigeonhole principle, not out of any clever protocol. That single observation is the whole idea behind quorums.
Picture four — consensus is electing a temporary dictator
You could try to make N nodes agree on the value of every individual write by negotiation. That's exhausting and slow. The trick real systems use is to negotiate once about something cheaper: who gets to decide. The nodes elect a leader for a bounded term; for that term, the leader's log is the truth and everyone else just follows it. Leadership is the unit of agreement. You replace "agree on a million values" with "agree on one dictator at a time," which is a vastly smaller problem.
🧭 Mental model — the one-line mantra. Replication scales reads and survives node death; partitioning scales writes and storage; consensus makes a replica set behave like one honest machine. Memorize this. When someone proposes a fix, ask which axis it moves. Half of bad distributed-systems decisions are a correct tool aimed at the wrong axis.
3. Theory & invariants
A mental model tells you how to picture replication, partitioning, and consensus. Invariants tell you what each one guarantees and refuses to guarantee — the load-bearing facts you'll reason from for the rest of your career.
Replication models: who is allowed to accept a write?
The defining question for any replication scheme is brutally simple: which nodes may accept a write? There are exactly three answers, and each answer is a model.
Single-leader (primary/replica). One node — the leader — accepts all writes. It applies them in order and streams the changes to its followers, who replay them. This is what Postgres streaming replication and a default MongoDB replica set do.
🔑 The single-serialization-point invariant. Because exactly one node decides the order of writes, there are no write conflicts to resolve, ever. Two writes to the same row are simply ordered by the one node that saw them both. This is the model's superpower and the reason it's the right default for most systems: reasoning is simple because there is one authoritative timeline. Its two weaknesses are the flip side of the same coin — the leader is a write bottleneck (all writes funnel through one node) and a failover hazard (when it dies, something must promote a follower, and that promotion is where the hard problems live, §5).
Multi-leader. Several nodes accept writes — classically one leader per geographic region, so writes in the East hit the East leader and stay local. The leaders replicate to each other asynchronously.
🔑 The conflict invariant. With more than one node accepting writes, two clients can and eventually will write the same key on different leaders before those leaders have synced. The write conflict is no longer avoidable; it is guaranteed. Therefore choosing multi-leader is choosing to own a conflict-resolution policy — last-write-wins (and accept silent data loss), version vectors (the vector clocks you've already met — detect and surface concurrency), or an application-level merge. You buy write-locality and cross-region availability; you pay in convergence complexity. Never adopt multi-leader without naming, in writing, how conflicts resolve.
Leaderless (Dynamo-style). No node is special. A client (or a coordinator on its behalf) writes to several replicas directly and reads from several replicas directly. Cassandra and DynamoDB live here.
🔑 The R/W/N invariant. In a leaderless system, consistency is not a property of the topology — it's a runtime property of how many replicas you write to (W), how many you read from (R), out of how many exist (N), chosen per operation. The same cluster can give you a strong-ish read or a fast stale read depending on the numbers you pass at call time. This is the model's power and its footgun: correctness is now a parameter the application sets on every call, and getting it wrong is a code review away.
Synchronous vs asynchronous: when does the write "count"?
Cutting across all three models is a second dial: when does the leader acknowledge the write to the client?
- Asynchronous: the leader acks as soon as it has the write, then ships it to followers in the background. Fast (the client waits only for one node) but a leader crash loses any write the followers hadn't received yet. Acknowledged data can vanish.
- Synchronous: the leader does not ack until at least one follower confirms it has the write durably. Zero data loss on a single-node failure — but the client now waits for the slowest confirming follower, and if that follower hangs, the write hangs. One sick replica can freeze all writes.
- Semi-synchronous: the sane middle. Require at least one of K followers to confirm (not a specific one, and not all), so you get durability without being held hostage by any single slow node.
There is no universally correct choice here; there is a per-table choice. Pulsely's claims and signed encounters want synchronous-ish durability (losing an acknowledged claim submission or a signed note is unacceptable — one is money, one is the medico-legal record). Its RPM trend rollups and denormalized roster counts can be asynchronous (losing the last few milliseconds of a panel-size counter on a freak crash is survivable).
Replication lag and the anomalies it breeds
Asynchronous replication means replicas lag, and lag produces a small zoo of user-visible anomalies. You must know the three by name, because in production you'll be diagnosing them by symptom:
- Read-your-writes (read-after-write): a user must always see the result of their own writes. Broken when their post-write read lands on a lagging replica that hasn't applied the write yet. (This is page two of the opening incident.)
- Monotonic reads: a user must never see time run backwards — read a fresh value, then on a later read see an older one because the second read hit a more-lagged replica. The data appears to "un-happen."
- Consistent prefix reads: if writes occurred in causal order A→B (B only happened because A did — B exists only because A does), no reader may ever see B land before A. You've seen the felt symptom in a UI: a reply showing up above the message it answers — or, the healthcare version, a lab result appearing in the chart before the order that produced it. This one bites hardest under partitioning, where A and B may live on different partitions replicating at different speeds.
🔑 Lag is normal; unbounded lag is a bug. A replica being behind is the expected, healthy steady state of asynchronous replication — it is not an error. What's pathological is lag that grows without bound, which happens precisely when write volume spikes (the replica can't apply changes as fast as the leader produces them). Note the cruel timing: replica lag balloons exactly during write surges, which is exactly when you most wanted to offload reads onto replicas. The tool degrades when you lean on it.
Quorums: agreement by pigeonhole
For leaderless (and many configurable) systems, the central invariant is the overlap rule.
🔑 The quorum invariant:
R + W > N. With N replicas, a write that must reach W of them and a read that must consult R of them are guaranteed to overlap on at least one node whenever R + W > N — because two subsets of an N-set whose sizes sum to more than N cannot be disjoint. That overlapping node holds the latest write, so the read can find it. A companion rule,W > N/2, ensures two concurrent writes can't both reach a majority, preventing two simultaneous "successful" writes to the same key. You tune the dial:
R=1, W=N— instant reads, expensive writes (every replica must confirm each write).R=N, W=1— instant writes, expensive reads (every replica must be consulted on each read).R = W = a simple majority— balances both. A "simple majority" is just the smallest group that's more than half: for N=3 that's 2, for N=5 that's 3. (The textbook writes it⌈(N+1)/2⌉, but all that ceiling notation means is "round a bare majority up to a whole node.")
N = 3 replicas: [a] [b] [c]
W = 2 → write lands on, say, {a, b}
R = 2 → read consults, say, {b, c}
▲
guaranteed shared node 'b'
saw the latest write → read is fresh
R + W = 4 > 3 = N ✓ sets must overlap
Counter-case: R = 1, W = 1 → R + W = 2 ≤ 3
write {a}, read {c} → NO overlap → stale read possible
And now the crucial caveat that separates seniors from formula-reciters:
🛑 What a quorum does not give you.
R + W > Nguarantees overlap, not linearizability. Sloppy quorums (where W writes land on whatever nodes are reachable, not the "home" nodes), concurrent writes racing through the overlap, and read-repair timing all still permit stale or conflicting reads. Quorums bound staleness probabilistically; they do not abolish it. If you need "every read sees the latest write, period," you need real consensus, not quorum arithmetic. TreatingR + W > Nas a linearizability guarantee is a classic and expensive mistake.
Partitioning strategies: how do you decide who owns a key?
Three strategies, each with a defining strength and a defining failure mode.
Range partitioning. Sort the keys and assign contiguous ranges to nodes (keys A–F → node 1, G–M → node 2, …). Strength: range scans are efficient — "all of patient 42's encounters from last week" reads from one node. Failure mode: sequential keys (timestamps, autoincrement IDs) all sort to the end, so every new write hammers whichever node owns the highest range. A time-ordered vitals stream partitioned by created_at puts all of today's readings on one poor node.
Hash partitioning. Compute hash(key) mod N and that's the node. Strength: a good hash spreads load evenly regardless of key skew. Failure mode: you destroy range-scan locality (adjacent keys scatter everywhere), and — the deadly one — the mod N term means that changing N remaps almost every key. Go from 4 nodes to 5 and roughly 80% of keys now hash to a different node.
Consistent hashing. Place both keys and nodes on a hash ring (imagine a clock face of hash values); a key belongs to the first node found walking clockwise from the key's position.
🔑 The consistent-hashing invariant. Adding or removing a node remaps only the keys between the new/departed node and its predecessor on the ring — roughly 1/N of all keys, not nearly all of them. Virtual nodes (each physical machine claims many positions around the ring) both smooth out uneven distribution and make rebalancing incremental rather than lumpy. This is the technique that turns "add a server" from a cluster-wide reshuffle into a localized, survivable operation.
hash(key) mod N consistent hashing (ring)
─────────────── ──────────────────── ─────
N: 4 → 5 nodes add node E to ring
~80% of keys move only keys in E's arc move (~1/N)
[k]→2 becomes [k]→4 ╭──── A ────╮
[k]→0 becomes [k]→3 D B
...nearly everything ╰──── C ──E──╯
moves at once only this arc remaps
The hot-key invariant, which no hashing fixes.
🛑 Skew is a data property, not a hashing flaw. Perfect hashing spreads distinct keys evenly. It does nothing for a single key that's red-hot — one cardiac monitor streaming a reading every second, one ultra-high-volume provider's slot table. That one key lives on exactly one partition, and no hash function can split a single key across machines, because routing is defined by the key. A hot key is a data-distribution problem you must solve at the application layer (split the key yourself, cache it, rate-limit it — §5), never one the partitioner solves for you.
Consensus: the Raft invariants
When nodes must truly agree on a single ordered history — for leader election, for cluster configuration, for any "exactly one node decides" requirement — you reach for a consensus protocol. Raft is the one designed to be understandable, so it's the one to learn. Its safety rests on a handful of invariants:
- Election safety: at most one leader per term. A term is a logical clock — a monotonically increasing number — and each term has at most one winner. (No two leaders for the same term means no two authorities issuing conflicting orders under the same mandate.)
- Leader append-only & log matching: a leader never overwrites or deletes entries in its own log, only appends. And if two logs contain an entry with the same index and term, then all entries before that point are identical. This lets a follower's log be reconciled to the leader's by finding the last point they agree and copying forward. This is exactly how git fast-forwards a branch: find the last commit two histories share, then replay the newer commits on top. A follower whose log diverged rewinds to the last entry it shares with the leader and replays the leader's entries from there. (An "entry" here is one write in the log; its index is its position, its term is which leadership era appended it — together they name a point in history uniquely, the way a commit hash does.)
- The commit rule: an entry is committed once it's been replicated to a majority of nodes. Committed entries are durable across any minority failure and are never lost or overwritten in a future term. This is what "majority quorum" buys you: agreement that survives any minority dying.
- Liveness needs a majority: to elect a leader or commit anything, a candidate needs votes from a majority. So a network partition that strands you on the minority side cannot elect a leader and cannot commit — it stalls. This is CAP made concrete: Raft chooses C over A during a partition. The minority refuses to make progress rather than risk diverging.
🔑 Why "majority" is load-bearing. Every safety property above leans on the fact that any two majorities of the same node set must overlap (the same pigeonhole as quorums). Two leaders can't both win an election because they'd need two disjoint majorities, which can't exist. A committed entry can't be lost because any future majority must include a node that has it. Majority quorum is the single primitive consensus is built from.
Vocabulary to pin to memory, because the rest of distributed systems is written in it: leader / follower / candidate, term, log index, commit index, quorum, read-repair, anti-entropy, hinted handoff, partition key vs primary key, rebalancing, split-brain.
📎 Borrowed on credit: messaging and the log. Several mechanisms here — at-least-once delivery, redelivery, ordered logs replicated to followers — are the same machinery that underpins message queues and log-based streaming. We're using them today only to reason about a datastore. Their full treatment as a communication substrate (durable queues, consumer groups, the partitioned commit log) is Chapters 26 and 27. For now, just notice the shapes recur.
4. Under the hood: how the primary lab actually does this
Theory earns its keep when you can point at the config knob that implements it. Let's open the boxes, starting with the primary lab — Postgres and Node/TS — then look at the leaderless and consensus mechanics, then the JVM contrast that teaches.
Single-leader in practice: Postgres streaming replication
Postgres ships every change first to its write-ahead log (the WAL — the on-disk durability log you saw earlier). Streaming replication is, at heart, shipping that WAL to replicas and having them replay it. The replica is replaying the leader's exact timeline — picture two from §2 made literal.
The sync/async dial is one setting, synchronous_commit, and it maps cleanly onto §3's spectrum:
synchronous_commit value → when does COMMIT return?
──────────────────────── ─────────────────────────
off ack before even the leader's WAL is flushed (fastest, riskiest)
local ack when leader's WAL is flushed locally (async to replicas)
remote_write ack when a replica has RECEIVED the WAL (semi-sync-ish)
on ack when a replica has FLUSHED the WAL (synchronous, durable)
remote_apply ack when a replica has APPLIED & visible (strongest, slowest)
Your lag metric lives in pg_stat_replication: the replay_lag column tells you how far behind each replica is applying. That number is the dashboard line you alert on (§5). There's also a choice between physical replication (ship the raw WAL byte-for-byte — replica is an exact clone) and logical replication (ship decoded row-level changes — slower but enables selective replication, cross-major-version upgrades, and replicating into a different schema, e.g. feeding a search index).
Read routing in Node/TS, and fixing the read-your-writes bug
Here's the connection layer that creates page two's bug — and then three ways to fix it. The naive version simply sends writes to the primary and reads to a replica pool:
// The naive setup that produces the stale-read bug.
class Db {
constructor(private primary: Pool, private replicas: Pool) {}
write(sql: string, params: unknown[]) {
return this.primary.query(sql, params); // writes → leader
}
read(sql: string, params: unknown[]) {
return this.replicas.query(sql, params); // reads → lagging follower (!)
}
}
A clinician does write("UPDATE patients SET legal_name=$1 WHERE id=$2", ...), then a read(...) that lands on a replica 600 ms behind. Stale name. Three fixes, weakest-but-cheapest to strongest:
Fix 1 — time-windowed sticky-to-primary. After a user writes, route that user's reads to the primary for the next few seconds (longer than your worst-case lag). Crude but effective and trivial to implement: stamp a "wrote at" time in the session, and if now - wroteAt < lagBudget, read from primary.
read(userId: string, sql: string, params: unknown[]) {
const wroteAt = this.session.lastWriteAt(userId);
const withinWindow = wroteAt && (Date.now() - wroteAt) < this.LAG_BUDGET_MS;
const pool = withinWindow ? this.primary : this.replicas;
return pool.query(sql, params);
}
Fix 2 — LSN-gated replica reads (the precise one). Postgres exposes a log sequence number (LSN) — a monotonic position in the WAL. On a write, capture the primary's current LSN and stash it in the user's session/cookie. On a read, ask a replica for its current replay LSN; only serve from that replica if replica_lsn >= user_write_lsn, otherwise fall back to the primary (or another replica). This serves stale-tolerant reads from replicas and guarantees the user sees their own write, without globally forcing primary reads. It's read-your-writes implemented exactly, at the cost of one extra check. (If you live in React Query: it's the same instinct as refusing to show a cached entry until you know it's fresh past a version you're holding.)
Fix 3 — annotate known write-then-read flows. Some flows are always "write then immediately read it back" (the demographics-edit page). Just mark those read paths primary-only and stop guessing.
A real production system often pushes this routing below the app, into a proxy — PgBouncer, ProxySQL, or Vitess — so the application speaks to one endpoint and the proxy decides primary vs replica. App-side routing is simpler to start; proxy-side routing centralizes the policy and keeps it out of every service. Either is defensible; pick one deliberately rather than letting both half-exist.
Leaderless mechanics: read-repair, anti-entropy, hinted handoff
Leaderless systems (Cassandra, DynamoDB) have no leader to keep replicas honest, so they use three background and inline repair mechanisms:
- Read-repair: on a read that touches several replicas, if one returns a stale value, the coordinator writes the fresh value back to the laggard as part of serving the read. Reads heal the data they touch.
- Anti-entropy: a background process continuously compares replicas (often via Merkle trees, so it can find the divergent ranges cheaply) and syncs differences. This catches data that's rarely read and so never repaired by reads.
- Hinted handoff: when a write's target replica is temporarily down, a healthy node stores the write as a "hint" and replays it to the target once it recovers — so a brief outage doesn't drop the write.
The R/W/N dial from §3 is exposed directly to the application as a consistency level per query: Cassandra's QUORUM (a majority across all replicas) or LOCAL_QUORUM (a majority within the local datacenter, avoiding cross-region latency) is you choosing R and W at call time.
Partitioning and rebalancing mechanics
Routing a key to a node needs a partition map — and the interesting question is where that map lives. Options: gossiped peer-to-peer among the nodes (Cassandra), held in a coordination service (§5), or owned by a routing tier (Vitess for sharded MySQL). A consistent-hash lookup with virtual nodes, in pseudocode:
// Placement: each physical node claims V positions on a 2^32 ring.
function buildRing(nodes: string[], vnodes = 150): Map<number, string> {
const ring = new Map<number, string>();
for (const node of nodes)
for (let i = 0; i < vnodes; i++)
ring.set(hash32(`${node}#${i}`), node); // many points per node = even spread
return ring;
}
// Lookup: walk clockwise from hash(key) to the first ring position.
function owner(ring: Map<number, string>, key: string): string {
const points = [...ring.keys()].sort((a, b) => a - b);
const h = hash32(key);
const point = points.find(p => p >= h) ?? points[0]; // wrap around the ring
return ring.get(point)!;
}
Now rebalancing, where the real engineering is. Two production-grade strategies, both designed to avoid the mod N catastrophe:
- Fixed number of logical partitions. Decide up front on a large fixed count — say 256 partitions — far more than you'll ever have nodes. You never recompute hashes; you only reassign whole partitions to nodes. Adding a node means handing it a few of the 256 partitions. Because partition identity never changes, a key's partition is stable forever; only the partition's home moves. (This is Kafka's model and Elasticsearch's shard model.)
- Dynamic splitting. Range partitions split in two when they grow too big and merge when they shrink, with the system moving the halves around (HBase, CockroachDB). More automatic, more moving parts.
🛑 Why
hash mod Nis essentially un-rebalanceable. TheNinmod Nis the node count, so changing the node count changes the function, so nearly every key relocates at once — a data and cache-miss storm that can take the cluster down precisely when you were trying to grow it. The fixed-logical-partition trick sidesteps this by making the hash target a partition number (fixed) rather than a node number (variable). Decouple "which partition" (immutable) from "which node hosts that partition" (movable), and rebalancing becomes a metadata change instead of a data apocalypse.
Raft, walked concretely
Here is a leader failure, start to finish, so the §3 invariants become a story:
term 5, leader = A A B C D E (E partitioned off, lagging)
A appends entry @idx 9 → replicate to majority {A,B,C} → COMMITTED
A crashes.
── followers' election timers fire; B's randomized timeout fires first ──
B increments term → 6, becomes CANDIDATE, requests votes
B's log is up-to-date → C and D grant votes → B has majority → LEADER(6)
B appends new entries with term=6; followers reconcile via log-matching
── E rejoins: its uncommitted entries (never reached majority) get
OVERWRITTEN by B's log; committed entry @9 survives (it had a majority) ──
The load-bearing moves: randomized election timeouts break symmetry so two candidates rarely tie; a candidate wins only on a majority vote; the new leader's log is reconciled outward via log matching; entries that were committed (reached a majority) survive any election, while entries that hadn't (only on a minority) can be safely discarded. And on a partition, the minority side stalls — it can't reach a majority, so it makes no progress and therefore can't diverge. CP, exactly as the CAP framing predicts.
The JVM contrast that actually teaches
You will almost never write consensus. You will constantly depend on it. The clearest example is Apache Kafka (Chapter 27's star, borrowed early here):
-
Kafka is the same synchronous-quorum idea from §3 wearing different names. Map the jargon back to the concepts you already have:
- in-sync replicas (ISR) = the followers currently caught up (within a bound) — the healthy quorum candidates.
acks=all= "don't tell the producer OK until every caught-up follower has the write" — the synchronous ack from §3.min.insync.replicas= "refuse the write entirely unless at least this many replicas are caught up" — the W floor from §3.
A Kafka topic-partition has one leader replica and that ISR set; wire those three settings together and you have exactly synchronous-quorum replication tuned for streaming throughput — same invariants, different vocabulary.
-
Who decides which replica is leader and tracks the ISR? Historically ZooKeeper, which runs the ZAB consensus protocol; in modern Kafka, KRaft, which runs Raft. Same job — agree on cluster metadata and leadership — two consensus engines under the hood.
🧭 The transferable lesson, said plainly: you depend on consensus; you don't implement it. A Spring service doesn't run Raft — it talks to Kafka, etcd, or ZooKeeper, each of which runs consensus for it. Writing your own Raft for application logic is almost always a mistake (§7). The skill is knowing it's there, knowing what it costs, and reaching for a battle-tested implementation. Note also the JVM-specific hazard you saw earlier: a stop-the-world GC pause can freeze a leader long enough to lose its lease while it still believes it's leader — the split-brain seed §5 must fence against.
🛑 What we deliberately did not explain. The full proof of Raft's safety (the paper does it properly), the internals of Merkle-tree anti-entropy, CRDTs as a principled multi-leader conflict-resolution family, and the precise WAL record formats Postgres ships. We located each on the map and named the mechanism; we didn't derive it. That's the right altitude for a theory chapter — enough to choose and operate, not enough to reimplement.
5. In production: the parts the tutorials skip
The mechanisms above are the easy 20%. The operational 80% is the hard part, and it's where systems actually break.
Failover is the hard part, not replication. Copying WAL to a replica is solved and boring. Promoting a replica when the leader dies is where the dragons live, and it has four steps, each a hazard:
- Detect the leader is dead — via timeout, which cannot distinguish dead from slow. A GC pause or a network blip looks identical to death, so detection produces false positives.
- Pick the most-caught-up replica to promote — because with async replication, replicas are at different LSNs and promoting a behind one loses more data.
- Redirect clients to the new leader — connection strings, DNS, or a proxy must all learn the new truth.
- Fence the old leader so that if it was only slow and wakes up still believing it's leader, it can't accept writes — STONITH ("shoot the other node in the head") or fencing tokens (a monotonically increasing epoch number; the storage layer rejects any write carrying an old token).
🛑 The split-brain invariant. Never auto-failover without fencing. If you promote a new leader while the old one is merely paused (not dead) and unfenced, you now have two leaders both accepting writes, producing two divergent histories that cannot be cleanly merged — the worst outcome in all of data management. Majority quorum for leadership plus fencing tokens is the non-negotiable defense. "I was leader five seconds ago, so I still am" is the assumption that ends careers. And accept the corollary: async replicas can lose acknowledged writes on promotion (the leader acked writes the promoted replica never received) — decide, per table, whether that data-loss window is tolerable. For a signed encounter or an accepted claim, it is not.
Choosing a partition key is a one-way door. The partition key bakes itself into every query, every join, every index, every migration. Repartitioning a live table is a project — dual-write to old and new schemes, backfill historical data, verify, cut over, decommission — measured in weeks, not hours. So choose the key against three criteria: (a) it spreads load evenly, (b) it co-locates data you query together (so common queries hit one partition), and (c) it matches your highest-volume access pattern. Get it wrong and you live with scatter-gather forever or sign up for the repartition project.
Cross-partition queries are the tax you pay for partitioning. Any query that isn't scoped to a single partition's key — a join across partitions, a global aggregation, an ORDER BY over all data — requires scatter-gather: fan the query out to every partition, then merge the results. It's slow, it paginates badly, and (the killer) it's only as fast as the slowest partition you touched. Avoid these by denormalizing, or by maintaining secondary indexes / materialized views shaped for the query. On secondary indexes specifically: local indexes (one per partition) make writes fast but reads a scatter-gather; global indexes (term-partitioned across nodes) make reads fast but writes cross-partition and slow — which is why DynamoDB's global secondary indexes are eventually consistent. There's no free lunch; pick which side pays.
Operating replication day to day. Monitor replay_lag with an alert threshold and an SLO ("replicas lag ≤ 2 s; page if any replica > 5 s"). Cap how stale a replica is allowed to be before you remove it from the read pool automatically. Take backups from a replica to spare the primary the I/O. And the one everyone skips:
🏭 Untested failover is broken failover. A failover path that has never been exercised in production will not work the first time you need it — DNS TTLs you forgot, a client that caches the old leader, a fencing token that was never wired up. Run game days: deliberately kill the primary in production (or a production-faithful environment) on a schedule and watch the system promote, redirect, and recover. The teams that survive 3 a.m. outages are the ones who rehearsed them at 3 p.m.
Coordination services and their non-obvious cost. etcd, ZooKeeper, and Consul are the consensus-backed control planes you reach for: leader election, cluster configuration, service discovery, distributed locks. They're invaluable for exactly those jobs. But internalize the cost:
🛑 Every write to a coordination service is a consensus round. That means every write pays a majority round-trip latency and the cluster has a hard write-throughput ceiling — these systems are built for low write volume on a control plane, not for data on the hot path. Put a per-request distributed lock through ZooKeeper and your throughput collapses to "one consensus round per request." And because everything depends on the coordination service, an unavailable coordination cluster takes down everything that depends on it. Treat coordination services as low-write control planes you consult occasionally — never as a database, and never on the per-request hot path.
📎 Borrowed on credit: horizontal scaling of the app tier. This chapter scales data. Scaling the stateless application tier — many identical app instances behind a load balancer, autoscaling on load, the statelessness that makes any instance answer any request — is a different toolbox, and it's Chapter 29's. We lean on the result (a stateless app fleet talking to this replicated, partitioned datastore) without building it here.
The Pulsely increment: replicas and partitions, reasoned not defaulted
Now we do the chapter's increment for real. Two questions: which Pulsely read paths can tolerate stale data, and how should each domain table be partitioned.
First, the read-routing decision — for every read path, "replica OK" or "primary only":
Read path Freshness need Route
─────────────────────────────────── ────────────────────── ────────────
Auth: validate session/token read-your-writes primary (or LSN-gated)
Patient demographics after own edit read-your-writes primary (or LSN-gated)
Open appointment slots (booking) must be fresh primary (consistent)
Current meds / allergies at point must be fresh (safety) primary
of care
Order/claim just submitted read-your-writes primary / LSN-gated
Another provider's worklist browse stale OK (≤ ~2 s) replica
Panel size / roster counts stale OK (seconds) replica
Clinical search results stale OK replica / search tier
RPM trend dashboard (historical) stale OK (seconds) replica
The pattern: anything a user is about to read immediately after writing it themselves, and anything clinically safety-critical (open slots for the no-double-booking engine, the current med list and allergies at the point of care, active orders), goes to the primary or through LSN-gated read-your-writes. Everything that's aggregate or historical viewed casually — a colleague's worklist, a panel count, an RPM trend chart — can tolerate a couple of seconds of lag and belongs on replicas. That's most read volume, which is exactly why replicas are worth it.
Now partition keys, per domain table — for the day each outgrows one machine:
Table Partition key Strategy Hot-spot risk / cross-partition tax
───────────────── ──────────────────── ───────── ───────────────────────────────────
patients patient_id (hashed) hash even; lookups by id single-partition
encounters patient_id (hashed) hash co-locates a patient's chart timeline;
"all encounters for a PROVIDER" =
scatter-gather
appointment_slots provider_id (hashed) hash ultra-high-volume provider = hot key;
co-locates a provider's schedule
observations(RPM) patient_id (hashed) hash a device streaming 1/sec = hot key
(bucket by time); per-patient trend
reads stay single-partition
claims patient_id (hashed) hash co-locates a patient's billing;
"all claims for a PAYER" = scatter-gather
worklist/inbox provider_id (hashed) hash per-provider worklist single-partition
alerts patient_id (hashed) hash even; naturally per-patient
Two design tensions fall out, and naming them is the senior move. Hot keys: appointment_slots keyed by provider_id exposes an ultra-high-volume-provider hot partition, and observations keyed by patient_id exposes a hot key whenever one device streams continuously — perfect hashing can't help (§3's skew invariant), so we handle it at the app layer (time-bucket the streaming key into sub-keys like patient#hour, a read-through cache in front of the hot slot table, per-key rate limits). Cross-partition tax: keying claims and encounters by patient_id makes a patient's history fast but "all claims for a given payer" or "all encounters for a given provider" a scatter-gather — so if those cross-cutting queries are high-volume, we maintain a second, provider-keyed (or payer-keyed) materialized view rather than scatter-gathering live. Notice we chose patient_id over a hash of encounter_id: a raw-encounter_id hash spreads perfectly but co-locates nothing, forcing scatter-gather for the most common access pattern (opening a patient's chart). We trade a little skew risk for a lot of query locality. That trade is the whole art.
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
Read-your-writes broken.
Signature: a clinician saves a change, immediately reloads, and sees the old value; irreproducible in single-node staging.
Fix: their post-write read hit a lagging replica. Route that user's reads to the primary for a lag-sized window, or gate replica reads on replica_lsn ≥ the user's write LSN. Don't "fix" it by sending all reads to the primary — that throws away the replica you paid for.
Monotonic-read violation (time runs backwards). Signature: a value reads fresh, then on a later refresh reads older, as the two reads bounce between replicas of different freshness. Fix: pin a given user/session to one replica (sticky routing) so successive reads can't regress, or read by explicit version so the client can reject a lower one.
hash mod N resharding outage.
Signature: you add one node to grow capacity and the cluster melts — near-total cache miss, data movement storm, latency through the roof.
Fix: never make node count a term in your placement function. Use consistent hashing, or a fixed pool of logical partitions you reassign without recomputing hashes.
Hot partition from sequential keys.
Signature: range-partitioned by created_at or an autoincrement ID, and every new write hammers the single node that owns the highest range while the others idle.
Fix: don't range-partition on a monotonically increasing key. Hash the key, or salt/composite the prefix (e.g., (bucket, created_at)) so new writes spread across nodes — at the cost of giving up the global time-ordered scan.
Hot key from a single red-hot entity.
Signature: one continuously-streaming monitoring device or one ultra-high-volume provider saturates its single partition while the cluster's aggregate CPU looks fine.
Fix: hashing can't split a single key. Split it in the application (fan the key into key#0..key#K, e.g. time-bucket the device stream), front it with a read-through cache, or rate-limit per key. Treat skew as a data problem you own.
Split-brain after failover. Signature: after a partition or a GC pause, two nodes both believe they're leader, both accept writes, and you have two irreconcilable histories. Fix: require a majority quorum to win leadership, and fence the old leader (fencing tokens / STONITH) so a merely-slow old leader can't write after waking. Never auto-failover without fencing.
Synchronous replication stalls all writes. Signature: one replica gets slow or hangs, and suddenly every write on the primary blocks, because it's waiting for that specific replica to confirm. Fix: use semi-synchronous — require any 1 of K replicas, not a named one — or set a confirmation timeout that drops to async (with a loud alert) rather than freezing the product on one sick node.
Treating quorum reads as linearizable.
Signature: "we set R + W > N, so reads are always the latest" — and yet stale/conflicting reads still appear.
Fix: R + W > N guarantees overlap, not recency under concurrency. Add read-repair, accept residual staleness, or use real consensus for the paths that genuinely need linearizability.
Coordination service on the hot path. Signature: a per-request distributed lock or config read via ZooKeeper/etcd, and throughput mysteriously caps far below the hardware's capacity. Fix: every coordination write is a consensus round. Move coordination off the request path — cache the config, use optimistic concurrency or DB-level locks for per-request serialization, and reserve the coordination service for genuine low-write control-plane decisions.
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand.
Single-leader ↔ multi-leader ↔ leaderless. Single-leader gives you simplicity and no write conflicts — one node orders everything — at the cost of a write bottleneck and a failover event. Multi-leader gives you write-locality and cross-region availability, paid for with mandatory conflict resolution and convergence complexity. Leaderless gives you tunable consistency and high write-availability, paid for with real operational complexity and per-call correctness parameters. Default to single-leader. Move toward multi-leader or leaderless only when a single write node provably can't meet your write-availability or geographic-latency goals — and when you do, write the conflict-resolution policy down first. For Pulsely, single-leader Postgres with read replicas is correct until proven otherwise.
Synchronous ↔ asynchronous replication.
Synchronous buys zero data loss and costs latency plus a stall risk on slow replicas; asynchronous buys low latency and availability and risks losing acknowledged writes on failover. This is a per-table decision, not a cluster-wide one: synchronous (or semi-sync) for claims and signed encounters, where a lost write is money or the medico-legal record; asynchronous for RPM trend rollups and roster counts where losing the last few milliseconds on a freak crash is survivable. Reverse toward more synchrony the day a failover data-loss incident becomes a headline.
Range ↔ hash partitioning. Range buys scan locality (great for a patient's chart timeline and for time-series — "give me this patient's last week of vitals") and risks hot spots from monotonic keys. Hash buys even load distribution and destroys scan locality. Choose hash when hot partitions from sequential keys dominate your pain; choose range when scan-heavy queries dominate your traffic. Many systems end up with a composite: hash the high-cardinality prefix to spread load, range within it to keep local scans.
R/W quorum tuning.
Read-heavy workloads favor W=N, R=1 (pay on the rare write, read instantly); write-heavy favor W=1, R=N; balanced favors a majority on both. Stronger quorums (more nodes that must respond) cost latency and availability — the more nodes that must agree, the more likely one is slow or down. Tune to the workload, and remember the quorum bounds overlap, not absolute freshness.
Few large partitions ↔ many small ones. Few large partitions are simpler to operate but rebalance coarsely and carry a big blast radius (lose one, lose a lot). Many small logical partitions (the fixed-256 trick, with virtual nodes) rebalance smoothly and isolate failures, at the cost of more metadata and per-partition overhead. Default to many small logical partitions — the operational smoothness is worth the overhead almost every time.
DIY consensus ↔ buy a coordination service. Never roll your own Raft for application logic — it's a multi-year, correctness-critical undertaking, and the bugs are the subtle, data-eating kind. Pay the latency and operational cost of etcd/ZooKeeper/Consul only for genuine control-plane coordination (leader election, config, discovery). Reverse this only at extreme scale where the coordination dependency itself becomes the bottleneck — and even then you adopt a proven system, you don't write one.
🚫 A framing this book rejects. "We'll just vertically scale the primary forever." It is seductive because it requires no distributed-systems thinking — until you hit the largest box money can buy (page one of §1) and discover you've also been running a single point of failure the whole time. The other two seductive non-answers: "two-phase commit across every shard on every write" (a blocking protocol whose availability collapses under exactly the partitions CAP guarantees) and "a distributed lock for every operation" (a consensus round-trip per request, §5's throughput killer). Each feels like it sidesteps the hard problem. Each just relocates the hard problem to 3 a.m.
8. Security & scale notes
Security and scale are properties of everything; here's where this chapter's ideas touch each.
Every replica is a full copy of your data — and a full copy of your breach surface. A read replica isn't an abstraction; it's another machine holding all the PHI, all the charts, all the claims, all the everything. Encrypt it at rest, restrict its network, and audit access to it exactly as strictly as the primary — a forgotten, unencrypted "just a read replica" is a complete, reportable PHI breach waiting to be found. The same goes for data you replicate into a search index or cache: each replicated copy widens the blast radius of any single compromise.
Replication streams cross network boundaries and must be encrypted. WAL shipping and inter-node replication often cross availability zones or regions. An attacker who can tap the replication stream reads every change to your database in real time — every new observation, every note, every claim, a firehose of plaintext PHI if you let it be. Replication traffic must be TLS-encrypted and mutually authenticated (the transport machinery you've already met, applied between your own nodes). "It's internal traffic" is not a security model, and under HIPAA it's not a defensible one.
Never let a client supply the raw partition route. When partitioning carries tenant isolation — partition by clinic/org, and a tenant's data lives on its partition — the partition key must be derived server-side from the authenticated principal, never taken from a client-supplied parameter. Let a client name the partition (or the tenant id) directly and you've handed them cross-tenant reads: one org's charts served to another org's staff — a reportable breach, and the trust-boundary lesson now with shards.
The coordination service is a total-compromise target. Whoever controls leader election controls the cluster — they can elect a malicious leader, rewrite config, or poison service discovery. Lock down etcd/ZooKeeper with strict ACLs and mutual TLS, and treat a compromise of the coordination tier as a compromise of everything that depends on it. It is the keys to the kingdom in one box.
Now scale, where this chapter's mechanisms have sharp, non-linear edges:
🔑 Hot partitions cause localized brownouts invisible in aggregate. Cluster-wide CPU can read a comfortable 40% while one shard is melting at 100% and timing out — because the average hides the outlier. You must monitor per-partition, not just cluster-wide, or the dashboard will swear everything's fine while a tenth of your patients get errors on their vitals upload. This is the saturation-is-a-chain-property lesson, sharpened: the chain now has parallel lanes, and one lane can be on fire while the aggregate looks calm.
Quorum systems degrade non-linearly. In an N=3 replica set, losing one node is a shrug — you still have a majority, reads and writes continue. Losing the second collapses both: no majority, no leader, no progress. The cliff between "fine" and "down" is one node wide, and it's invisible until you step off it. Provision and alert for the margin to the cliff, not the current health.
Scatter-gather amplifies tail latency. A query that fans out to K partitions completes only when the slowest of the K responds — so every partition you touch raises your p99, because you're now exposed to the worst tail among K independent samples (a preview of the tail-latency math to come). Touch 20 partitions and a 1-in-100 slow partition becomes a near-certainty on every query. Minimize fan-out; it's a latency multiplier, not just a cost adder.
And the cruelest timing of all: replica lag grows under write spikes — exactly the moment you most want to offload reads onto replicas (§3). The tool you're reaching for is weakest precisely when you reach for it. Design for that: have a degraded mode (serve from primary, shed non-critical reads) for when lag blows past its SLO, rather than discovering the coupling during the incident.
9. Interview lens & exercises
Interview questions
Backend interviews probe whether you reason about distribution or merely recite its vocabulary. The same question separates levels by the quality of the narration.
"You added a read replica and clinicians see stale data after editing a patient's demographics — diagnose and fix."
- Junior answer: "add caching" or "just always read from the primary." The first makes it worse; the second throws away the replica you added.
- Senior answer: names it as a read-your-writes violation from replication lag, then distinguishes the fixes by precision — per-user routing-to-primary for a lag-sized window (cheap, crude) vs. LSN-gated replica reads (precise, serves stale-tolerant traffic from replicas while guaranteeing the writer sees their write) — and adds the operational piece: monitor
replay_lagwith an SLO and a degraded mode. Same bug, narrated as a tradeoff space.
"How would you shard a 1 TB observations (RPM vitals) table, and what breaks?"
- Junior: "hash the ID mod number-of-servers" — no rebalancing story, no query-pattern analysis.
- Senior: picks the partition key from the dominant access pattern (patient_id, so a patient's chart and vitals stay single-partition), then immediately names what breaks: provider- or payer-side rollups become scatter-gather (and proposes a provider-keyed materialized view), hot keys from a high-frequency streaming device need app-level time-bucketing, and
mod Nwould make rebalancing a cluster-wide outage so they'd use fixed logical partitions. Crucially, calls the key choice a one-way door with a multi-week repartition cost.
"Explain R + W > N and when it still gives you a stale read."
- Junior: recites the formula as if it guarantees strong consistency.
- Senior: derives the overlap / pigeonhole guarantee in one sentence, then immediately qualifies it — concurrent writes racing through the overlap, sloppy quorums, and read-repair timing mean it bounds staleness probabilistically, not absolutely, and it is not linearizability. The qualification is the signal; anyone can state the formula.
"When do you actually need consensus (Raft) vs. when is plain replication enough?"
- Junior: "use ZooKeeper for everything" or "consensus makes it consistent."
- Senior: consensus for the single-decider problems — leader election, cluster config, exactly-one-leader — and plain async replication for read-scaling where staleness is tolerable. Then the warning: consensus is expensive (a majority round-trip per write), so it belongs on a low-write control plane, never on the per-request hot path, and you consume it (Kafka/etcd) rather than implement it.
"Walk me through a leader failure in a Raft cluster."
- Junior: "a new leader is picked" — no mention of majority or commit.
- Senior: election timeout fires → candidacy in a new term → majority vote wins → log reconciliation via log-matching → committed entries (those that reached a majority) survive while uncommitted ones can be overwritten → and on the minority side of a partition, no progress at all (CP). Narrates why a majority is what makes it safe.
Exercises & the Pulsely increment
Do these with a real local Postgres where noted, then a text file. Fluency, not perfection.
-
Reproduce-and-fix read-your-writes. Stand up a Postgres primary plus one async replica locally. Write a Node/TS data layer that routes reads to the replica, then a flow that updates a patient's demographics and immediately reads it back. Demonstrate the stale read (add artificial replica delay if needed). Then fix it with LSN-gated routing — capture the write LSN, only read from the replica when its replay LSN has caught up — and prove the stale read is gone. You'll never again be confused about why "it works in staging."
-
Consistent-hash lab. Implement a consistent-hash ring with virtual nodes in TS. Distribute 100,000 keys across 4 nodes, then add a fifth node and measure the fraction of keys that move. Repeat with naive
hash mod N. Chart the two: ~1/N moved vs. ~80% moved. The chart is the argument you'll make in every future sharding design review. -
Pulsely partition design (the increment). Produce the per-domain table — for
patients, encounters, appointment_slots, observations, claims, worklist, alerts(and clinicalsearch) — listing the chosen partition key, the strategy (range/hash), the expected hot spots, and the cross-partition queries you'd be forced into. Then mark every read path as "tolerates stale (replica OK)" or "must be fresh (primary only)." Defend, in one sentence each, why open-slot availability ≠ RPM trend chart ≠ roster count. (§5 is your worked solution — try it before you read it back.) -
Write ADR-024. Decide and record Pulsely's data topology. Recommended decision: single-leader Postgres + N async read replicas, with synchronous (or semi-sync) commit for
claimsand signedencountersand async for the rest; read-routing via LSN-gated read-your-writes with stale-tolerant paths on replicas; partition keys per table as in your exercise-3 table; and fixed logical partitions (notmod N) for the rebalancing approach. Record the rejected options with reasons: multi-leader (no geo or write-availability need yet that justifies conflict resolution), leaderless (operational complexity unwarranted at current scale), andhash mod N(un-rebalanceable). An ADR that doesn't record what you rejected and why is just a config file with feelings.
Key takeaways
- Three orthogonal mechanisms, never conflated: replication (same data, N copies — survive node death, scale reads), partitioning (different data per node — scale writes and storage), consensus (agree on one ordered history — behave like one honest machine). Ask which axis a proposed fix actually moves.
- Replication models are defined by who may accept a write: single-leader (no conflicts, one bottleneck — the right default), multi-leader (write-locality, mandatory conflict resolution), leaderless (consistency is a runtime R/W/N parameter).
- Replication lag is normal; unbounded lag is the bug. It breeds read-your-writes, monotonic-read, and consistent-prefix anomalies — and it grows under write spikes, exactly when you lean on replicas.
R + W > Nguarantees read/write overlap by pigeonhole — but not linearizability. Quorums bound staleness probabilistically; real recency under concurrency needs consensus.- Partitioning is routing that becomes migration.
hash mod Nis un-rebalanceable (changing N remaps nearly everything); use consistent hashing or fixed logical partitions so adding a node moves ~1/N of keys. No hashing fixes a hot key — skew is a data property you handle in the app. - Consensus = electing a temporary dictator by majority quorum (Raft): one leader per term, commit-on-majority, minority partitions stall (CP). You depend on it (Kafka/etcd/ZooKeeper), you don't implement it.
- Failover, not replication, is the hard part: detect (timeouts lie), promote the most-caught-up replica, redirect, and fence the old leader against split-brain. Untested failover is broken failover.
- Choose a partition key from your dominant access pattern — it's a one-way door. Cross-partition queries are scatter-gather (slowest-partition-bound, tail-amplifying); avoid with co-location and materialized views.
← Previous: Ch 23 — Distributed Systems Theory I · Up: Part V overview · Master TOC · Next: Ch 25 — Idempotency & Delivery Semantics →