Distributed systems fundamentals: replication, partitioning, consistency, consensus

Reading: 46 min, plus 10 in closed details. What changes when data lives on more than one machine, from zero: partial failure, time and order, replication, quorums, the consistency ladder, CAP and PACELC, Raft, fencing, exactly-once and partitioning, on the parent's LLM chat product. Child of Topic: swe-and-system-design. Sources linked inline; data as of October 2026.

The idea in one screen

Machines that share data can only talk by messages, and a missing reply never tells you what happened; every technique on this page (replicas, quorums, consensus, fencing, idempotency) is a way to stay correct anyway, paid for in latency or availability.

The running example is the parent page's LLM chat product (Topic: swe-and-system-design): users, their chats, the messages in each chat, and each user's paid credit balance. Ana sends "hello" and her page refreshes. The question the whole page answers: which copy does that refresh read, and is "hello" in it? Fig. 1 is one chat product, four jobs: split the data, copy each piece, choose what a read may see, agree on who is in charge (illustrative layout).

  1. Split the data. Partitioning: users are split over shards, so no machine holds everything. Each tinted plate is one key range; the app servers route each request to its shard.
  2. Copy each piece. Replication: each shard has a leader that takes writes and followers that replay its log, a little behind. The dots are the log streaming from leader to followers.
  3. A write lands on one leader. Ana's "hello" goes to shard 2's leader, which appends it to its log at position 101 and streams it on. Follower 1 has replayed it; Follower 2 is still behind (the dashed slot).
  4. Choose what a read may see. Consistency: a read that lands on a lagging follower can miss Ana's own "hello"; a consistency model says whether that is allowed.
  5. Agree on who is in charge. Consensus: a small Raft group (etcd) decides which node leads each shard; leases and fencing tokens stop an old leader that has not noticed.

You need: nothing beyond a database and an HTTP request. The parent page's Numbers to know tab holds the round-trip times used here (0.5 ms in a data centre, 69 ms across the US).

ProblemTechniqueWhat it costsWhere you meet it
One machine dies, or cannot keep up with readsReplication: copies on several machines, one leader takes writesCopies lag; a reader can see the pastPostgres streaming replication, MySQL, MongoDB
You want to write in several placesMulti-leader, or leaderless with quorums (N, R, W)Conflicting writes; someone must decide which winsCassandra, DynamoDB global tables, CouchDB
"Did my write happen? Will others see it?"Consistency models: linearisable, sequential, causal, eventualStronger means more waiting and less availability during failuresEvery database's docs; CAP and PACELC
Machines must agree on one leader or one orderConsensus: Raft or Paxos over a majorityA round trip to a majority per decision; no progress without a majorityetcd (Kubernetes), Consul, Kafka KRaft, Spanner, DynamoDB
A paused process still thinks it is in chargeLeases and fencing tokensThe storage must check a number on every writeZooKeeper zxid, etcd revision, Chubby sequencers
A retry after a lost reply runs the work twiceIdempotency at the end points (at-least-once plus deduplication)A stored key per operation, checked in the same transaction as the effectPayment APIs, Kafka's idempotent producer, every job queue
The data or write rate outgrows one machinePartitioning (sharding) by key range or hash; consistent hashingHot keys; moving data when machines are added; queries across shardsEvery large database; Notion, Figma, Instagram, Discord
Ordering events when clocks disagreeLogical clocks (Lamport, vector, hybrid) or bounded clocks (TrueTime)Metadata on every message, or waiting out the uncertaintyCockroachDB, Spanner, Dynamo, Cassandra's last-write-wins
The habit to take away
Start from the invariant, the thing that must never happen ("never spend the same credit twice", "a sent message never vanishes for its sender"), then pick the weakest guarantee that still protects it, per piece of data. The sidebar's chat order can be a second stale; the credit balance cannot. The parent page's How a senior engineer reasons section says the same.

New terms on this page

Partial failure: some machines or links work, others do not, and nobody can be sure which.
Replica, leader, follower: one copy; the copy that takes writes; the copies that replay its log.
Replication lag: how far a follower is behind its leader.
Quorum: enough replicas that any two such sets overlap (R + W > N, or a majority).
Consistency model: the set of histories a system may show its clients.
Linearisable: behaves like one copy, in real-time order.
Consensus: machines agreeing on one value or one log while some fail.
Lease, fencing token: permission that expires; a number that grows with each grant, checked by the storage.
Idempotent: doing it twice has the same effect as doing it once.
Partition (shard), and network partition: a slice of the data; a split in the network. Two different things with one name.
Who owns the neighbours. Retry policy, timeouts and circuit breakers: Reliability engineering. Idempotency keys as an HTTP API feature: Service APIs (section 4). Queues, delivery guarantees, Kafka's exactly-once and the outbox: Queues, streams and async work. Isolation levels and transactions inside one database: Transactions and concurrency; read replicas and sharding a real database: Scaling a database. Collective communication between GPUs: Distributed training.

1. Why it is hard: messages, silence, pauses and clocks

One database server has one copy of the truth, and the parent page's advice stands: "a bigger machine and one Postgres go a long way". You leave it for four reasons, each pointing at a different technique: it dies (fix: replication), too many reads (replication again, or a cache), too many writes or too much data (copies do not help, every copy takes every write; fix: partitioning), and users far away (light in fibre needs about 59 ms to cross the Atlantic and back, and Azure measures 78 ms East US to UK South, Numbers to know; fix: replicas near users, which puts the copies far from each other). Every fix puts data on machines that can only talk by message.

Partial failure: silence has four causes

A program on one computer mostly works or crashes. A distributed system has a third state, partial failure: some machines or links work and others do not. The app server sends "save hello" to the database and hears nothing. Predict before you click: in how many of these four cases did the write happen?

The only tool the app server has is a timeout: wait so long, then assume failure. It cannot say what failed, and in two of the four cases (slow, reply lost) the write did happen, in a third (crashed) it may have. That single fact drives most of this page: it is why retries need idempotency, why a "dead" leader may still be alive (leases and fencing), and why Kafka's documentation says of a producer that sees a network error: "it cannot be sure if this error happened before or after the message was committed" (Kafka 4.2 design docs).

Choosing the timeout has no free answer. Too short, and a slow but healthy node is declared dead, a replacement takes over, and two think they are in charge. Too long, and every real failure means a long wait. etcd defaults to a 100 ms heartbeat and a 1,000 ms election timeout, and its docs say the election timeout "must be at least 10 times the round-trip time" (etcd v3.6 tuning).

The app server's view is identical in all four; the database's is not

Partitions, pauses and clocks

  • Network partitions are real. A network partition is a split: two groups of machines each up but unable to reach each other. GitHub, 21 October 2018: maintenance cut the US East Coast data centre off for 43 seconds; automation promoted West Coast replicas to leaders, both coasts held writes the other lacked, and repair took 24 hours and 11 minutes (GitHub post-incident analysis; "gh-2018-10" in the parent's Case files).
  • A process can stop without knowing it stopped. A garbage collector's "stop the world" phase, a virtual machine being live-migrated, swapping, a laptop lid closing: when the program resumes, its code continues from the next line as if no time passed. If it held a lock or a lease (permission that expires), that permission may have been given to someone else. This is the scenario behind fencing tokens.
  • Clocks lie. Every machine's quartz clock drifts. Spanner budgets a worst-case drift of "200 microseconds/second" between synchronisations every 30 seconds (Corbett et al., OSDI 2012), so even Google's machines can be 200 µs/s × 30 s = 6 ms apart before correction. NTP (Network Time Protocol) corrects clocks and can step them backwards. So a computer has two clocks: the time-of-day clock (wall clock; comparable across machines only roughly, and it can jump) and the monotonic clock (only moves forward, meaningless across machines, the right tool for a duration or a timeout). The rule: measure durations with the monotonic clock; never order events across machines by their wall clocks unless the system bounds the error (next section).
The eight fallacies, failure models, and two real records (optional)

In the 1990s L. Peter Deutsch and others at Sun Microsystems listed the false assumptions that programmers new to distributed systems "invariably make" (Wikipedia, with the original list):

The false beliefWhat actually happens, and what you do about it
1. The network is reliablePackets are dropped, links are cut, switches are misconfigured. Every call needs a timeout and a plan for "unknown outcome".
2. Latency is zeroA round trip is about 0.5 ms inside a data centre and 69 ms across the US. Ten sequential calls across regions is most of a second: batch, parallelise, keep chatty calls local.
3. Bandwidth is infiniteCopying a big table to a new replica, or rebalancing shards, can saturate links and slow live traffic. Throttle background copies.
4. The network is secureAnything on the wire can be read or forged unless encrypted and authenticated (TLS between services, not only at the edge).
5. Topology does not changeMachines come and go, IP addresses move, autoscaling adds nodes. Discover peers dynamically; never hard-code addresses.
6. There is one administratorYour system spans a cloud provider, a DNS provider, other teams' services. Their changes are your outages (the parent's Case files hold several).
7. Transport cost is zeroSerialising data costs CPU, and cross-zone and cross-region traffic is billed per GB (egress prices in Numbers to know).
8. The network is homogeneousDifferent hardware, kernels, MTUs and client versions behave differently. Test across the mix you really run.

The models people reason in. Papers and docs state which failures they tolerate. Crash-stop: a node works correctly until it halts for good. Crash-recovery: it may halt and come back with what it saved to disk (most databases assume this). Byzantine: a node may lie or behave arbitrarily (blockchains; rarely inside one company). On timing: synchronous (delays have a known bound), asynchronous (no bound at all), and the realistic middle, partially synchronous (usually bounded, sometimes not). The consensus algorithms below are safe in the asynchronous model and make progress only when the network behaves for a while.

Google, 2017. Eric Brewer's analysis of Spanner incidents put the network category "under 8%", and "Nor was a Spanner quorum ever on the minority side of a partition", but "We did see individual data centers or regions get cut off from the rest of the network" (Brewer, Spanner, TrueTime and the CAP Theorem, 14 Feb 2017). Even on Google's private network partitions happen; they are just not the most common failure.

Cloudflare, 1 January 2017. At the leap second "a number went negative when it should always have been, at worst, zero", because Go's time.Now() "does not guarantee monotonicity", and DNS resolutions failed for some customers (Graham-Cumming, Cloudflare blog). Go added "transparent monotonic time support" in version 1.9 later that year (Go 1.9 release notes).

2. Time and order without a shared clock

Last-write-wins, leases and "which happened first?" all need an order of events across machines, and wall clocks cannot give it reliably. Two ways out: give up physical time and track cause and effect (logical clocks), or keep physical time but bound its error (hybrid and bounded clocks).

Leslie Lamport (1978) defined happened-before (→): a → b if a came before b on the same machine, or a is sending a message and b is receiving it, or there is a chain of these. If neither a → b nor b → a, the events are concurrent: neither could have influenced the other.

  • A Lamport clock is one counter per machine: add one at every event; put the counter on every message; on receiving, set yours to max(yours, received) + 1. It satisfies Lamport's "Clock Condition. For any events a, b: if a→b then C(a) < C(b)", and he points out the converse fails: "we cannot expect the converse condition to hold as well" (Lamport, CACM 1978). A smaller number does not mean "happened before"; it may be concurrent.
  • A vector clock keeps one counter per machine: add one to your own entry at every event; on receiving, take the element-wise maximum, then add one to your own. Now a → b exactly when a's vector is ≤ b's in every entry (and differs somewhere); if each is larger somewhere, they are concurrent. The cost is one number per participant on every message. Dynamo used vector clocks to keep concurrent versions of an item side by side for the application to merge (the shopping cart that keeps both additions); Cassandra chose last-write-wins timestamps instead.
  • Hybrid logical clocks (Kulkarni et al., 2014) pair the wall-clock time with a small logical counter: they capture causality like a Lamport clock while staying close to real time, and fit in a 64-bit timestamp ("HLC captures the causality relationship like logical clocks ... Moreover HLC fits in to 64 bits NTP timestamp format", Kulkarni et al.). CockroachDB uses them.
  • TrueTime (Google Spanner) returns not a time but an interval, [earliest, latest], guaranteed to contain the true time, from GPS receivers and atomic clocks in every data centre. In 2012 the uncertainty ε was "typically a sawtooth function of time, varying from about 1 to 7 ms over each poll interval" (the 6 ms climb is the drift budget above). Spanner then waits out the uncertainty before making a commit visible (commit wait), so any transaction that starts after another finished gets a larger timestamp. That is how it offers external consistency, under which "the system behaves as if all transactions run sequentially" (Spanner docs, TrueTime and external consistency). Better clocks mean shorter waits.
Clock bounds in CockroachDB and on AWS (optional)

CockroachDB still needs synchronised clocks: when a node's clock is off from at least half the others "by 80% of the maximum offset allowed, it spontaneously shuts down. This offset defaults to 500ms", with 250 ms recommended for new clusters (CockroachDB operational FAQs).

In November 2023 AWS announced "microsecond-level clock accuracy on supported Amazon EC2 instances" and ClockBound, an open-source daemon that reports the time with an error bound, TrueTime-style (AWS Compute Blog, 16 Nov 2023).

Lamport numbers order everything, so they cannot say "concurrent"; vectors can

Predict: event b1 has Lamport number 3 and c1 has 1. Did c1 happen before b1? Tap the two events, then switch to vectors.

Click (tap) two events to compare them. Three machines A, B, C; arrows are messages. The labels are computed by the rules above; src/recompute.py recomputes them.

3. Replication: keeping copies

Replication means keeping a copy of the same data on several machines, each copy a replica. It answers a dead machine, too many reads and far-away users. Copying data that never changes is trivial; all the difficulty is in changes. There are three ways to organise who accepts changes.

Single leader (leader and followers)

One replica is the leader (also called primary or master): every write goes to it. It records each change in an ordered log (Postgres calls it the write-ahead log, WAL: every change is written there before the tables are touched, which is also how it survives a crash). The other replicas, followers (secondaries, standbys, read replicas), receive that log and replay it in the same order, so they pass through the same states. Reads may go to any replica. This is Postgres streaming replication, MySQL replication, MongoDB replica sets and Kafka partitions; it is what the parent page called a read replica.

Synchronous or asynchronous: when does the leader say "saved"?

The leader can confirm a write to the client before or after followers have it:

  • Asynchronous: confirm after the leader's own disk has it. Fast, and a slow follower never slows writes. Cost: if the leader dies, writes its followers had not received are lost, even though the client was told "saved".
  • Synchronous: confirm only after a follower has it too. A confirmed write survives the leader's death. Cost: every commit waits a round trip to the follower, and if that follower is down, writes stop (so real setups wait for "any one of several").

Postgres makes this one setting, synchronous_commit, and its documentation is exact about what each value waits for (PostgreSQL 18 docs, synchronous_commit). With no synchronous standby named, only the leader's flush counts. With one named in synchronous_standby_names: on waits until the standby has "flushed it to durable storage"; remote_apply waits until it has "applied it, so that it has become visible to queries on the standby(s)". Those are different moments, and the difference is exactly the stale-read question. So it was measured.

Measured for this page: asynchronous replication missed 1,993 of 2,000 immediate reads, even on one laptop

A real primary and a real streaming replica (PostgreSQL 16.2 from the pgserver wheel, built with pg_basebackup), on one Apple M1 Pro laptop over TCP loopback, 4 October 2026. In each mode: 2,000 single-row inserts on the primary; right after each commit returns, read that row on the replica. Script src/measure_replication.py, output src/inputs/replication_local.json; takes about a minute.

ModeCommit waits forReads that missed the writeCommit, medianCommit, p99
Asynchronous (default)primary's own flush1,993 of 2,000 (99.65%)0.150 ms0.588 ms
Synchronous, onreplica has flushed WAL1 of 2,000 (0.05%)0.244 ms0.821 ms
Synchronous, remote_applyreplica has replayed it0 of 2,0000.266 ms0.859 ms
Asynchronous + client waits for positionprimary's flush; the reader waits for replay0 of 2,0000.206 ms0.684 ms

How to read it. Even with both copies on one machine, asynchronous replication missed nearly every immediate read: the write became visible on the replica a median 0.236 ms later (worst 6.8 ms), but the read was faster. Synchronous on is not read-your-writes: it guarantees the write is durable on the replica, not visible there, and one read in 2,000 still slipped through the gap between flush and replay. Only remote_apply, or the client waiting for the replica to reach its own write position (median extra wait 0.105 ms, p99 0.624 ms), closed it.

What does not transfer to production (optional)

here the "network" is loopback and macOS fsync returns before the drive truly flushes (see the parent's Numbers to know), so every commit is unrealistically cheap. With the replica in another availability zone, each synchronous commit adds at least one round trip (Microsoft targets under about 2 ms between zones); across the US, 69 ms. Lag grows the same way, so stale reads get more likely, not less.

The same write, four ways of reading it back: two failures and their fixes

Illustrative positions and timing; the stale-read rate and the wait are the measured ones beside section 3's table.

What lag does to readers: the before and after

Asynchronous followers are behind by some amount, the replication lag: usually milliseconds, sometimes seconds or minutes when a follower is overloaded or recovering. Three anomalies follow, and each has a standard fix. The animation plays each mode as a step list; pick a mode to replay it.

  1. Three copies, in step. One leader takes every write and appends it to its log; two followers replay that log. All three hold Ana's earlier message "hi" (log position 100).
  2. Ana sends "hello". The write goes to the leader, which appends it at position 101 and flushes it to its own disk.
  3. The leader says "saved" at once. With asynchronous replication (Postgres's default), the commit returns after the leader's own flush. The followers have not seen 101 yet. Ana's screen shows "hello ✓".
  4. The change streams to the followers. Follower 1 receives and replays 101. Follower 2 is a little behind (busy, or further away): 101 is still in flight. That gap is replication lag.
  5. Ana's page refreshes: "hello" has vanished. The read is load-balanced to Follower 2, which has replayed only up to 100. It answers honestly with what it has. To Ana the message she just saw saved is gone: a read-your-writes violation.
  6. A moment later it is back. Follower 2 replays 101 and the next refresh shows "hello". The copies did converge (eventual consistency), but Ana saw the past in between. On a laptop this gap is a fraction of a millisecond and still caught 99.65% of immediate reads (measured, above).
  • Read-your-writes (read-after-write): a user always sees their own writes. Fixes: read data the user may have just changed from the leader (for example, for one minute after their last write), or remember the log position of their last write and have the replica wait until it has replayed that far. The cost is a short wait on the reads that need it, and the session must carry a position.
    The Postgres version, as the measurement ran it (optional)
    In Postgres the position wait is two functions:
    -- on the primary, right after the write commits
    SELECT pg_current_wal_insert_lsn(); -- e.g. 0/3000148, keep it in the session
    -- on the replica, before reading
    SELECT pg_last_wal_replay_lsn() >= '0/3000148'::pg_lsn; -- wait until true
    This is exactly what the measurement's fourth row ran.
  • Monotonic reads: once a user has seen some state, they never see an older one. Fix: send each user's reads to the same replica (hash the user id), as in the animation.
  • Consistent prefix reads: if writes happened in an order, readers see them in that order. In the chat, Ben asks "lunch?" and Ana answers "yes". If the two messages are stored on different machines with different lag, a third user can see "yes" before "lunch?". Fix: keep things that are causally related (one chat's messages) on the same partition, so one log orders them; the general tool is causal ordering.

Failover: when the leader dies

If the leader dies, a follower must be promoted to leader and clients must switch to it: failover. Done by hand it takes minutes; done automatically it is fast and dangerous, for three reasons:

  1. Is it really dead? Only a timeout says so (the four silences above). A leader that was merely slow or cut off comes back still believing it is the leader: two leaders accepting writes, split brain. Preventing this is what consensus and fencing are for.
  2. Lost writes. With asynchronous replication, the promoted follower may lack the last writes the old leader confirmed. Those confirmed writes are gone, and if the old leader returns its extra writes conflict with the new history.
  3. Across regions. GitHub's 2018 outage is all three in one: 43 seconds of partition, automatic promotion of the other coast's replicas, writes on both sides, and a 24-hour repair because GitHub "chose data integrity" over a fast fail-back (GitHub). Afterwards it stopped automatic promotion across regions.
Who actually promotes a Postgres follower (optional)

In practice, Postgres itself never promotes anything; tools such as Patroni do it. Patroni "supports a variety of distributed configuration stores like ZooKeeper, etcd, Consul or Kubernetes" (Patroni 4.1 documentation): consensus-backed stores that decide which single node holds the leader key at any moment. Managed services (Amazon RDS Multi-AZ, Cloud SQL) do the same internally.

Multi-leader: writes in several places

With users on several continents, you may want a leader in each region so writes do not cross an ocean. Each leader accepts writes and replicates them to the others. The price is write conflicts: Ana renames a chat to "Trip" on her phone (Europe leader) while her laptop renames it to "Holiday" (US leader). Both succeed locally; when the changes meet, something must choose. Options: last write wins (keep the one with the later timestamp; simple, silently discards the other, and clocks can lie), merge both values, ask the user, or use data types designed to merge automatically (CRDTs, conflict-free replicated data types: counters, sets and text that merge the same way whatever the order). Avoid multi-leader unless you need it; the usual trick is to route all writes for one item (one user, one chat) to one "home" leader, which avoids most conflicts.

Leaderless: any replica takes writes

Amazon's Dynamo paper (2007) made the third style famous: no leader at all. The client (or a coordinator acting for it) sends each write to several replicas and each read to several replicas, and counts answers. Cassandra, Riak and ScyllaDB work this way. Its central idea, the quorum, is the next section.

Go deeper. Read replicas in a real database (routing, lag monitoring, Long Fork): Scaling a database; WAL shipping, logical replication and MVCC in Topic: databases; the parent's Case files for GitHub 2018 and Discord 2023 in full.

4. Quorums: N, R and W

In a leaderless system each piece of data is stored on N replicas. A write is sent to all N and counts as successful once W of them confirm. A read asks replicas and waits for R answers, then takes the newest version among them (every value carries a version). The rule that makes this work is one line:

R + W > N
N
replicas that hold each item
W
replicas that must confirm a write
R
replicas a read must hear from

If R + W > N, every read set and every write set share at least R + W − N replicas, so at least one replica the read hears from has the latest successful write. This overlapping set is a quorum. Amazon's Dynamo paper: "The common (N,R,W) configuration used by several instances of Dynamo is (3,2,2)" (DeCandia et al., SOSP 2007).

  1. N = 3 copies of each item. Every replica holds version v1 of the value (say, Ana's chat title). The client, or a coordinator acting for it, talks to all three.
  2. A write confirmed by W = 2. The write of v2 is sent to all three and counts as successful once two confirm (r1 and r2). r3 has not got it yet, and nothing waits for it.
  3. A read that hears from R = 2. Drawn at its worst: the read hears from r2 and r3, the two replicas it is least lucky with. R + W = 4 > 3, so at least one of them (r2, glowing) holds v2, and the read keeps the newest version it hears.
  4. Cassandra ONE / ONE: R + W = 2 ≤ 3. W = 1 and R = 1. The write reaches only r1; the read hears only from r3, which the write never reached, and returns v1 although the write "succeeded".
  5. QUORUM with 5 copies: (5, 3, 3). Three of five for writes and three of five for reads still overlap in at least one replica (r3), and writes keep working with N − W = 2 replicas down, reads with N − R = 2.

Try any N, R and W

Predict: with N = 3, can W = 1 and R = 2 ever miss the latest write? Set it and see; the read is drawn picking the worst replicas it could.

The knobs trade against each other: lower W makes writes faster and keeps them working with more replicas down (N − W may be down), lower R does the same for reads (N − R).

Cassandra's consistency levels, read repair and anti-entropy (optional)

Cassandra exposes this per query as consistency levels: "QUORUM: A majority (n/2 + 1) of the replicas must respond", ONE, ALL, LOCAL_QUORUM (a majority in the local data centre) and others, and its docs call them "a version of Dynamo's R + W > N consistency mechanism" (Apache Cassandra docs, Dynamo architecture). Replicas that missed a write catch up by read repair (a read that sees an old version writes the new one back) and by anti-entropy: background comparison of Merkle trees, hash trees that let two replicas find differing ranges without sending all the data (Dynamo, Table 1).

R + W > N is not the same as strong consistency
It guarantees overlap, not linearisability (defined below). Abadi: by increasing R + W such systems "gain more consistency at the expense of latency (although they cannot achieve full consistency as defined by Gilbert and Lynch, even if R + W > N)" (Abadi, IEEE Computer, Feb 2012). The gaps: two concurrent writes, settled by timestamps (Cassandra uses "a simpler last-write-wins model where every mutation is timestamped", so a skewed clock picks the winner); a write that reached fewer than W replicas reports failure but is not rolled back where it landed; and a sloppy quorum, Dynamo's choice under failures, accepts writes on replicas outside the usual N ("hinted handoff") so the overlap no longer holds.

Discord, which read and wrote "with quorum consistency level" on Cassandra, also found that one slow replica in a busy partition slowed everyone ("discord-2023" in the parent's Case files).

Overlap is guaranteed only when R + W > N

5. Consistency models: the ladder from linearisable to eventual

"Consistent" is used loosely. A consistency model is a precise promise: Jepsen defines it as "a safety property which declares what a system can do. Formally, a consistency model defines a set of histories that a system can legally execute" (Jepsen, Consistency). A history is what clients observed: who called which operation, when it started, when it returned, and what it returned. To make each model concrete, take one value x (say, the title of Ana's chat, encoded as a number), initially 0. Each bar below is one operation, from the moment the client sent it to the moment the answer came back; w(1) writes 1 and r→0 is a read that returned 0.

Now the models, strongest first. Each one is a rule for which histories are allowed:

  • Linearisability (Herlihy and Wing, 1990): "every operation appears to take place atomically, in some order, consistent with the real-time ordering of those operations: e.g., if operation A completes before operation B begins, then B should logically take effect after A" (Jepsen, Linearizability). Picture each operation taking effect at one instant somewhere inside its bar. History 2 fails (the write ended before the read began, so the read must see 1). History 4 fails too, and it is the subtle one: both reads overlap the write, so either answer alone would be fine, but once client 2 has seen 1 and returned, nobody may see 0 afterwards. Linearisability is what makes a system behave like one copy; it is what you need for a lock, a leader, a unique username or "never spend the same credit twice". It is the "strong consistency" of the parent page.
  • Sequential consistency (Lamport, 1979): all operations appear in one total order that every client agrees on, and each client's own operations are in that order in the order it issued them, but the order need not match real time. Histories 2 and 4 both pass: put the read of 0 before the write. A client may be behind, but everyone sees the same story.
  • Causal consistency: operations that are causally related must be seen by everyone in that order; unrelated (concurrent) ones may be seen in different orders by different clients. Jepsen's example is a chat: Attiya asks "shall we have lunch?", Barbarella says "yes" and Cyrus "no"; "no participant ever observes 'yes' or 'no' prior to the question 'lunch?'", but they may disagree on the order of "yes" and "no" (Jepsen, Causal). Its great property: it can stay available during a partition, as long as each client sticks to the same server.
  • Eventual consistency: if writes stop, all copies eventually return the same value. It promises nothing about what you read meanwhile, not even your own write. DynamoDB's default read is this: "the responses might not reflect the results of a recently completed write operation" (DynamoDB read consistency).

Between causal and eventual sit the session guarantees from the replication section: read-your-writes, monotonic reads, and two more (monotonic writes: one client's writes are applied in order; writes follow reads: a write made after reading something is ordered after it). They are cheap and they fix most of what users notice.

One history, five models: the ladder lights up what each model allows

Predict: history 4, "A new value, then an old one": both reads overlap the slow write, so is it linearisable? Pick it, then tap any read bar to change what it returned and watch the rungs flip.

Strongest at the top: Jepsen's map of consistency models places linearisable above sequential above causal above read-your-writes; eventual is a convergence promise and sits at the bottom. Availability per rung is Jepsen's: linearisability and sequential consistency "cannot be totally or sticky available"; causal and read-your-writes are "sticky available" (every node can make progress during a partition "so long as clients never change which server they talk to").

How the verdicts are computed (optional)

Linearisable and sequentially consistent are checked by brute force in your browser: try every ordering of the operations, keep those that respect each client's own order (and, for linearisability, real time: if one operation ended before another began, it must come first), and accept if in one of them every read returns the latest preceding write. With at most six operations that is at most 720 orderings. src/recompute.py runs the same check in Python for every preset. Causal, read-your-writes and eventual verdicts are written by hand for the presets, with the reasoning shown; once you edit a read they show "?" rather than guess.

Linearisable is not serialisable

Two words sound alike and are different. Linearisability is about single operations on one object and respects real time. Serialisability is about transactions (groups of reads and writes on many objects): the result equals some one-at-a-time order of the transactions, but not necessarily the real-time order. Strict serialisability is both: Jepsen describes it as "serializability's total order of transactional multi-object operations, plus linearizability's real-time constraints" (Jepsen, Strong Serializability). Spanner calls its version external consistency (below). Isolation levels inside one database are taught in Transactions and concurrency; transactions across machines get a short section here.

Correction to the old page
The old page grouped "Sequential / causal: causally related ops are ordered everywhere; concurrent ops may interleave differently". That sentence describes causal consistency only. Sequential consistency is stronger: everyone sees the same single order, concurrent operations included. History 6, "Two observers disagree", separates them: allowed under causal, forbidden under sequential.
The sources behind the correction, and causal+ (optional)

Jepsen: under sequential consistency "operations appear to take place in some total order, and that that order is consistent with the order of operations on each individual process" (Jepsen, Sequential). The old page's "Causal+ is the sweet spot for geo-replicated data" is an opinion; it is the argument of the COPS paper that introduced causal+ (causal plus convergence) for wide-area stores (Lloyd et al., SOSP 2011), and Jepsen notes "Most 'causally consistent' systems actually provide these stronger properties, such as RTC or causal+".

6. CAP read correctly, and PACELC

CAP is the most quoted and most misquoted result in the field. Eric Brewer conjectured it in 2000; Seth Gilbert and Nancy Lynch proved it in 2002 (Gilbert and Lynch, 2002). Their theorem, in their terms: in an asynchronous network where messages can be lost, it is impossible to implement a read/write object that guarantees both

  • Consistency, meaning precisely linearisability ("atomic" consistency), and
  • Availability, meaning every request received by a non-failing node gets a response (not "the system is mostly up"),

in all executions, including those where the network Partitions. The proof is the picture below: split the replicas into two groups that cannot talk; a write lands in one group; a read arrives in the other. To be available the second group must answer, and it cannot know the new value, so it answers with the old one and breaks linearisability. To stay linearisable it must refuse, and so it is not available.

What CAP does not say
  • Not "pick two of three". You cannot opt out of partitions; they happen. The real statement: during a partition, a system that keeps linearisability must refuse some requests. Brewer himself: "you only need forfeit something during an actual partition" (Brewer, 2017).
  • Its C and A are narrow. A system that is neither linearisable nor CAP-available (most real databases in some configuration) is not "breaking" CAP; CAP simply says nothing about it. Causal consistency can be available under partition; linearisability cannot.
  • "CA" is a label for "we assume partitions are rare". Brewer on Spanner: "It is technically a CP system", yet "effectively CA" because Google's network makes partitions so rare that users do not write code for them; he cites Chubby at "an average availability of 99.99958%" and Spanner incidents with the network category "under 8%".
  • It says nothing about latency, which is what you trade every day. That is PACELC.

During a partition the far replica can answer stale or refuse; without one, it can answer fast or wait

Predict: with no partition at all, is there still a trade-off? Try the two "no partition" modes.

Illustrative balances; the 69 ms is the parent page's US cross-country round trip (Numbers to know).

PACELC (Daniel Abadi, 2012): if there is a Partition, choose Availability or Consistency; Else, in normal running, choose Latency or Consistency, because keeping copies in step means waiting for them (Abadi, IEEE Computer, Feb 2012). Abadi's own classification (2012, of the default settings):

ClassMeaningAbadi's examples (2012)
PA/ELGive up consistency both under partition and for speed"The default versions of Dynamo, Cassandra, and Riak"
PC/ECNever give up consistency; pay in availability and latency"Fully ACID systems such as VoltDB/H-Store and Megastore", BigTable and HBase
PA/ECConsistent normally, available under partitionMongoDB (as of 2012)
PC/ELFast normally; under partition it does not reduce consistency furtherYahoo's PNUTS

In our product: Ana's chat list is PA/EL territory (serve from a nearby replica, slightly stale is fine). Her credit balance is PC/EC (the spend must go through one linearisable place, and if that place is unreachable the spend is refused). One product, two choices, one per invariant.

7. Consensus: Raft step by step

Why it is needed

Several jobs above quietly assumed that the machines agree on something: which node is the leader (or failover makes two), which machine owns which shard, the order of writes in the log. Consensus is the problem of getting several machines to agree on one value, or one sequence of values, such that: everyone who decides decides the same thing; the decided value was actually proposed by someone; and the group keeps deciding as long as a majority is up and can talk.

Why a majority? Two majorities of the same group always share at least one member, so two conflicting decisions can never both collect one. With 2f + 1 machines you survive f failures: 3 machines survive 1, 5 survive 2. An even size buys nothing (4 machines still survive only 1, because the majority is 3). This is the quorum idea again, used for agreement rather than for reading values.

It is harder than it sounds. In 1985 Fischer, Lynch and Paterson proved that in a fully asynchronous network no deterministic algorithm can guarantee to reach agreement if even one process may crash (FLP, JACM 1985): you cannot tell a crashed process from a slow one. Practical algorithms therefore promise safety always (never two different decisions) and progress only when the network behaves for long enough, using timeouts to suspect failures. Paxos (Lamport) was the first widely used one; Raft (2014) was designed to give the same result while being easier to understand and build: "It produces a result equivalent to (multi-)Paxos, and it is as efficient as Paxos", and "Results from a user study demonstrate that Raft is easier for students to learn than Paxos" (Ongaro and Ousterhout, USENIX ATC 2014).

Raft, step by step

Raft keeps a replicated log: an ordered list of commands that every machine applies in the same order, so every machine computes the same state (a key-value map, the cluster's configuration). Everything below quotes or follows the paper.

  1. Roles. Each server is a follower, a candidate or the leader. Normally there is one leader and the rest are followers. Clients talk to the leader.
  2. Terms. "Time is divided into terms of arbitrary length, numbered with consecutive integers. Each term begins with an election". A term is a logical clock: every message carries the sender's term, and a server that sees a higher term immediately adopts it and steps down to follower. A leader from an old term is therefore ignored as soon as it talks to anyone.
  3. Heartbeats and the election timeout. The leader sends periodic heartbeats (empty AppendEntries messages). A follower that hears nothing for its election timeout assumes the leader is gone, adds one to its term, becomes a candidate, votes for itself and asks the others for votes (RequestVote). The timeout is random, "chosen randomly from a fixed interval (e.g., 150–300ms)", so usually one follower times out first and wins before others start.
  4. Voting. Each server votes for at most one candidate per term, first come first served. A candidate with votes from a majority becomes leader. This gives the first guarantee: "Election Safety: at most one leader can be elected in a given term." If the vote splits, nobody wins, the term ends, and new random timeouts break the tie.
  5. The election restriction. A server refuses its vote to a candidate whose log is less up to date than its own (compare the term of the last entry first; if equal, the longer log wins). Since a committed entry is on a majority, and a winner needs a majority of votes, every new leader already has every committed entry ("Leader Completeness").
  6. Log replication. A client command becomes a new entry (index, term, command) appended to the leader's log and sent to followers with AppendEntries. Each AppendEntries also carries the index and term of the entry just before the new ones; "If the follower does not find an entry in its log with the same index and term, then it refuses the new entries." The leader then backs up and resends earlier entries until the follower's log matches, overwriting a follower's conflicting uncommitted entries. Result: "if two logs contain an entry with the same index and term, then the logs are identical in all entries up through the given index."
  7. Commit. Once an entry from the leader's current term is stored on a majority, it is committed: it will never be lost or changed. The leader applies it, answers the client, and tells followers the new commit index in later messages. One subtle rule: a leader never counts replicas to commit an entry from an older term (the paper's Figure 8 shows such an entry can still be overwritten); it commits its own term's entry, which commits everything before it.
  8. Reads. A read served by a leader that has silently been replaced returns stale data. Raft's fix: a new leader first commits a blank entry, and "the leader exchange[s] heartbeat messages with a majority of the cluster before responding to read-only requests" (or relies on a time-based lease, if clocks are trusted). Getting this wrong is a classic bug (etcd 0.4.1, 2014; details below).

Fig. 3 runs the page's own Raft model (it follows the paper's Figure 2) on five servers, with random election timeouts of 150 to 300 ms, heartbeats every 50 ms and message delays of 12 to 24 ms, in simulated time. Each step plays one stretch of the run: dots are messages (purple for vote requests and votes, blue for AppendEntries and their replies), each server's log is a stack of slabs coloured by term, see-through until that server knows the entry is committed, and the glass column beside a follower is its election timer draining.

  1. Five followers, no leader. All five start as followers in term 0, each with its own random election timeout. Nobody sends heartbeats, so the first timer to run out starts an election: S1's, at 227 ms.
  2. A split vote, then a leader. S1, S2, S4 and S3 all time out within 14 ms and each asks for votes in term 1; the votes split, nobody reaches 3 of 5, and new random timeouts break the tie. In term 2, S3 collects votes from a majority (3 of 5, counting its own) at 444 ms, appends a no-op entry and commits it once a majority stores it. Its heartbeats now reset everyone's timers, so no one else runs.
  3. Client writes commit. The client sends x=1, then x=2 and x=3, to the leader. Each is appended, sent in AppendEntries, and committed as soon as 3 of 5 servers have stored it; only then may the leader answer "done". Followers learn the new commit index from the next heartbeat (their slabs turn solid).
  4. Crash the leader. S3 crashes. Followers stop hearing heartbeats; the first whose timer runs out, S2, starts an election for term 3 and wins it 224 ms after the crash (the paper measured a median of 287 ms with 5 ms of randomness, and 35 ms with 12 to 24 ms timeouts). The election restriction made sure the winner already had every committed entry.
  5. Writes continue; the old leader catches up. With one server down, 3 of the 4 remaining still form a majority of 5, so x=4 commits. Then S3 restarts as a follower with its log from disk and its old term; the first message from the leader carries a higher term, so it adopts it, and the AppendEntries consistency check sends it the entries it missed.
  6. A split, with the leader on the small side. The network splits S2 (the leader) and S1 away from the other three. A client sends x=5 and x=6 to S2: it appends them as entries 7 and 8 but can reach only 2 of 5 servers, so they never commit (its commit index stays at 6) and the client never hears "done". On the majority side S4 times out and wins term 4. Two servers now call themselves leader, but only one can commit: that is why Raft is safe during a split.
  7. Heal: uncommitted entries are overwritten. S4 commits x=7. Then the network heals. S2 receives a message with term 4 and steps down; its entries x=5 and x=6 conflict with the new leader's log and are overwritten on S2 and S1. Nothing promised was lost: those writes were never acknowledged, so their client must retry (safely, if they are idempotent).
  8. Lose the majority. S1, S2 and S4 go down. The two survivors, S3 and S5, keep timing out and starting elections (their terms climb from 4 to 11 in 1.5 s of simulated time), but neither can collect 3 votes, so there is no leader and no writes, and a client write is refused. Raft chooses consistency over availability: a minority never decides anything.

Break it yourself

The same model runs live beside this paragraph, on the same seed, and nothing moves until you press Play or Next event. Tap a server to select it, then crash or restart it, or split it off from the others (servers you split off can still talk to each other); send client writes and watch whether they commit. The log table and the event list show exactly what happened.

How the simulation is checked, and what it leaves out (optional)

The model is checked by src/check_raft.mjs: 300 random runs of crashes, restarts, splits and writes, asserting after every event that no term has two leaders and that no committed entry ever differs between servers or changes, and that a write commits once the network heals (0 failures). Fig. 3's trace (seed 11, eight stretches) gets the same checks on every one of its recorded states. Simplifications, stated plainly: no log compaction or snapshots, no membership changes, a client write goes to the newest reachable leader, and a restarted server forgets its commit index until the leader tells it (as in the paper, where it is volatile state).

How fast elections are, and a real stale-read bug (optional)

The paper crashed the leader of a five-server cluster repeatedly (broadcast time about 15 ms). With timeouts of 150 to 150 ms (no randomness), elections "consistently took longer than 10 seconds" because of split votes; "Adding just 5ms of randomness helps significantly, resulting in a median downtime of 287ms"; with 12 to 24 ms timeouts "it takes only 35ms on average to elect a leader (the longest trial took 152ms)". The timing rule they give is broadcastTime ≪ electionTimeout ≪ MTBF (mean time between failures), with broadcast "0.5ms to 20ms, depending on storage technology", so "the election timeout is likely to be somewhere between 10ms and 500ms". Production systems are more conservative: etcd's defaults are a 100 ms heartbeat and a 1,000 ms election timeout.

Stale reads in practice. Jepsen found etcd 0.4.1 got this wrong in 2014: it "exhibited stale reads by default" because it "performed reads on any leader, locally"; etcd 3.0 "made linearizability the default for all operations except for watches" (Jepsen, etcd 3.4.3, 2020-01-30).

What consensus costs
Every committed write waits for a round trip to a majority plus a disk flush on each (a durable log entry). Throughput is limited by one leader. A minority side of a partition cannot write at all (that is CAP's "C over A"). So you put small, critical state through consensus (who is leader, which shard lives where, configuration, locks), and keep bulk data in systems that use consensus only to pick a leader. etcd stores "a small volume of infrequently-updated state (by default, up to 8 GB)" (Jepsen, 2020). Never write your own consensus; use etcd, ZooKeeper or Consul, or a database that embeds Raft or Paxos.

Break it yourself: crash, restart and split servers, and the committed entries never change

Selected S1 (tap a server):
leadercandidatefollowercrashedvote messagesappend (log) messages

Logs

One row per server; each cell is a log entry (its term above, its command below). Green cells are committed on that server; outlined cells are not (yet).

What just happened

8. Leases and fencing tokens

Most systems do not run consensus on every write. They use it to elect one leader, then let that leader work alone. To make "one leader" survive crashes, leadership is a lease: permission that expires after a fixed time (the TTL, time to live) unless renewed. If the leader dies, the lease runs out and someone else takes it. DynamoDB works this way per partition: its replication group "uses Multi-Paxos for leader election and consensus", and "Once elected leader, a replica can maintain leadership as long as it periodically renews its leadership lease" (Elhemali et al., USENIX ATC 2022).

The trap is the pause from section 1. A lease holder that freezes does not know its lease ran out. When it wakes, it carries on writing as if it were still the leader. Martin Kleppmann's 2016 analysis of the Redlock algorithm walks through this with a garbage-collection pause and gives the fix (Kleppmann, How to do distributed locking, 2016-02-08): every time the lock is granted, the lock service hands out a number that only grows, a fencing token, and the storage rejects any write carrying a token lower than one it has already seen: "the storage server remembers that it has already processed a write with a higher token number (34), and so it rejects the request with token 33." Predict before stepping: in the "lease only" run, what is Ana's balance at the end, and what should it be?

  1. Worker 1 gets the lease. Worker 1 must charge Ana 10 credits. It takes the lease (TTL 10 s) and receives token 33. It reads her balance: 100.
  2. Worker 1 freezes. A long garbage-collection pause stops Worker 1 mid-task. It still has "100" in memory and believes it holds the lease. It cannot notice time passing.
  3. The lease expires; Worker 2 takes it. The lock service has not heard from Worker 1 for 10 s, so the lease expired. Worker 2, which must charge Ana 60 credits, takes the lease and receives token 34.
  4. Worker 2 writes 100 − 60 = 40. Correct so far: the storage now holds 40.
  5. Worker 1 wakes and writes 100 − 10 = 90. Its code continues from the next line. Without a check, the storage accepts the write: the balance is 90 and the 60-credit charge has vanished; it should end at 30 (100 − 60 − 10). Two workers both "held the lock".

Illustrative amounts and timing; the tokens 33 and 34 are Kleppmann's.

Real evidence that this matters:

  • Jepsen, etcd 3.4.3 (2020-01-30): "etcd locks are fundamentally unsafe". With "two-second leases TTLs, five concurrent processes, and process pauses every five seconds, we could reliably induce the loss of ~18% of acknowledged updates", and short TTLs of 1 to 3 seconds "generally failed to provide mutual exclusion after only a few minutes of testing, even in healthy clusters". The fix Jepsen names: "users can use the revision of their lock key as a globally ordered fencing token" (Google's Chubby calls these sequencers; in ZooKeeper, Kleppmann suggests the zxid).
  • AWS, 19 October 2025: two DynamoDB DNS automation workers raced; a slow one had checked its plan was newer than the live one, but "The check that was made at the start of the plan application process ... was stale by this time", and it overwrote a newer plan, leaving the regional endpoint with an empty DNS record for hours (AWS summary; "aws-2025-dns" in the parent's Case files). A check made on old information is not a check; the store itself must reject the older write, which is exactly what a fencing token does.
Correction to the old page
The old page advised taking a lease from etcd or ZooKeeper and to "keep the lease TTL well above GC pauses". A long TTL makes the failure rarer, not impossible: a pause can always outlast it, and Jepsen showed mutual exclusion failing even "in healthy clusters". The old page's next sentence is the real fix and is kept: fence every write with a monotonically increasing token, checked by the storage. Jepsen adds that this gives isolation but "does not guarantee atomicity": a holder that dies halfway through a multi-step update still leaves a half-done state.

Kleppmann's other useful distinction: a lock for efficiency (stop two workers doing the same job twice; an occasional double is harmless) can be simple, even a single Redis key; a lock for correctness (two writers would corrupt data) needs consensus plus fencing.

One charge, one lost reply, one retry: only a key checked at the end stops the double charge

Illustrative amounts and key.

9. Idempotency and exactly-once: an end-to-end property

Go back to the fourth silence: the database saved the charge and the reply was lost. The client cannot tell this from "request lost", so it has two choices. Never retry, and some charges silently never happen (at-most-once); or retry until it hears "done", and some charges happen twice (at-least-once). No protocol on the wire removes that choice, because the sender never learns which silence it got. What can happen exactly once is the effect: deliver at least once, and make the receiver recognise a repeat. An operation is idempotent when doing it twice has the same effect as doing it once ("set the title to Trip" is; "add 10 credits" is not).

Where the repeat is recognised matters, and that is the end-to-end argument (Saltzer, Reed and Clark, ACM Transactions on Computer Systems, 1984): "The function in question can completely and correctly be implemented only with the knowledge and help of the application standing at the end points of the communication system." On duplicates specifically: "even if the network suppresses duplicates, the application itself may accidentally originate duplicate requests, in its own failure/retry procedures. These application level duplications look like different messages to the communication system, so it cannot suppress them" (Saltzer, Reed and Clark).

Predict: the gateway in the middle drops duplicate messages. Does that save Ana from a double charge when her app retries? Compare the middle mode with the last one.

  1. Ana's app sends the charge. The app asks for a 10-credit charge. Nothing identifies this operation except its content.
  2. Payments charges: 100 becomes 90. The charge is applied and the reply sent.
  3. The reply is lost; the app's timeout fires. The fourth silence: the charge happened, and the app cannot know it. It retries, as it must.
  4. The app retries. The retry looks exactly like a new charge.
  5. Charged twice: 90 becomes 80. Payments has no way to tell a retry from a second purchase. Ana paid 20 credits for one request.

The recipe, wherever the end is (a payment service, a database, a job handler):

  • The originator names the operation. The client generates a unique idempotency key once, before the first attempt, and sends the same key on every retry. A key minted by a middle hop is a new key per attempt, which is the middle mode above.
  • The end records the key with the effect, atomically. Insert the key and apply the charge in one transaction (a unique constraint on the key does the checking). If they are separate steps, a crash between them leaves a charge with no key, or a key with no charge. On a repeat, return the stored result instead of running again.
  • Or make the operation idempotent by shape: "set to X" instead of "add X", a conditional write on a version number (compare-and-set), or a fencing token, which is the same idea applied to who may write.

Read "exactly-once" claims with this in mind. Kafka's transactions give exactly-once only while input and output are both Kafka topics; any external side effect needs its own deduplication, which Queues, streams and async work shows in detail. Retries done for you are the usual source of the duplicate: Jepsen found that the official etcd Java client "incorrectly retries non-idempotent requests which may have actually succeeded" (Jepsen, jetcd 0.8.2, 2024-08-08). How many times to retry, with what backoff, is Reliability engineering; the HTTP shape of an idempotency key (header, expiry, the stored response) is Service APIs (section 4).

10. Partitioning: splitting the data

Replication copies everything everywhere, so it cannot help when the data or the write rate outgrow one machine. Partitioning (sharding; each piece is a partition or shard) gives each machine a slice. Each slice is usually also replicated, so a real cluster is partitioned and replicated: DynamoDB keeps every partition as three replicas in three availability zones (Elhemali et al., USENIX ATC 2022). The design question is which machine holds which key.

By key range or by hash

  • Key-range partitioning: shard 1 holds users A to F, shard 2 G to M, and so on, like volumes of an encyclopedia. Range queries ("all messages in this chat between Monday and Friday") hit one shard. Danger: keys that arrive in order all land on the same shard; partitioning messages by timestamp sends every new message to the last shard.
  • Hash partitioning: run the key through a hash function and use the hash to pick the shard. Keys spread evenly whatever their pattern. Cost: range queries must ask every shard.

The obvious way to turn a hash into a shard is hash(key) mod N. It is a trap: add one machine (N to N + 1) and almost every key's remainder changes, so almost all data must move. Consistent hashing fixes this. Place each machine at several random points on a circle of hash values; a key belongs to the first machine point clockwise from its own hash. Adding a machine only takes over the arcs just before its points, about 1/(N + 1) of the keys. Each machine gets many points (virtual nodes, Dynamo's "tokens") so its share is even. More is not free: the Cassandra docs warn that every token adds ring neighbours, so "The more tokens you have, the higher the probability of an outage" when several machines fail at once (Cassandra docs). The widget hashes 10,000 real keys with a real hash function and adds one machine. Predict: with 4 machines, what share of keys moves under hash mod N?

Keys are the strings user:0 to user:9999; the hash is 32-bit FNV-1a followed by MurmurHash3's 32-bit finalizer (plain FNV-1a placed similar names such as node-0-vn-1 and node-0-vn-2 next to each other, clumping a machine's points); machine m's points are the hashes of node-m-vn-v. Every figure is recomputed by src/recompute.py and matches the page's JavaScript.

Adding one machine: mod N moves almost everything, the ring moves about 1/(N + 1)

Hot keys, rebalancing, and finding the right shard

  • Hot keys. Hashing spreads keys, not load. One celebrity user, or one busy Discord channel, is one key on one shard. Discord's fix was to stop sending the same query a thousand times (request coalescing) before buying a bigger database ("discord-2023" in Case files). Other fixes: add a random suffix to a hot key so it spreads over several shards (reads must then gather all of them), or cache it.
  • Rebalancing. Rather than consistent hashing, many databases create many more partitions than machines from day one and move whole partitions when machines are added: Instagram created thousands of logical shards on a few Postgres servers in 2012, and Notion split its Postgres into 480 logical shards on 32 physical databases in 2021, choosing 480 because it divides evenly over 40 or 48 hosts later ("insta-2012" and "notion-2021" in the parent's Case files). Moving data is slow and loads the network, so it is throttled and usually triggered by a person or a careful controller.
Secondary indexes and routing across shards (optional)
  • Secondary indexes. Looking a chat up by id is one shard; "all chats mentioning Lisbon" is all of them. A local index (one per shard) makes writes cheap and reads ask every shard; a global index is itself partitioned and kept up to date asynchronously. In DynamoDB, "All reads from GSIs and streams are eventually consistent" (DynamoDB read consistency).
  • Routing. Someone must know the map from key to shard: the client library (Cassandra drivers), a routing tier (Vitess, MongoDB's mongos), or any node that forwards. The map itself must be agreed, which is a job for consensus.

Choose the shard key so the common queries hit one shard and related data lands together: for the chat product, by user (or by workspace, as Notion did). It is among the most expensive decisions to change later.

11. Transactions across machines

A transaction groups several reads and writes so they succeed or fail together (atomicity) and so concurrent transactions do not see each other's half-done work (isolation). Inside one database, the isolation levels (read committed, snapshot isolation, serialisable), write skew and what Postgres and MySQL really give are taught in Transactions and concurrency. What is distributed is the commit itself.

When one transaction touches two partitions, or a database and a message queue, no single machine can commit it. Two-phase commit (2PC) uses a coordinator: phase 1 asks every participant "can you commit?" (each makes the change durable but invisible and promises to obey); phase 2 tells all to commit, or all to abort. Its weakness: a participant that has said yes must wait, holding locks, until it hears the decision, so a dead coordinator blocks everyone. Spanner's answer is to make each participant and the coordinator a Paxos group, so none of them is a single machine: "Running two-phase commit over Paxos mitigates the availability problems" (Corbett et al., OSDI 2012). The everyday version of this problem is the dual write: save a row in Postgres and publish an event to Kafka; a crash between the two leaves them disagreeing. The standard fix, the transactional outbox, is taught in Queues, streams and async work.

Go deeper. 2PC inside sharded Postgres (Citus) and cross-shard queries: Scaling a database. Jepsen's consistency map links every model and anomaly to its definition.

12. What real systems choose, and what testing found

Every production system is a particular combination of the choices above. Read a database's documentation with these questions: how is it replicated, how is it partitioned, what does a default read promise, and what happens in a partition? Facts from the documents linked, as of October 2026 unless dated.

Eight systems: replication, partitioning, default read, agreement (optional reference)
SystemReplicationPartitioningDefault read, and the stronger optionAgreement
PostgreSQL (docs v18)Single leader, WAL streaming; asynchronous unless synchronous_standby_names is set, which accepts FIRST n (...) or ANY n (...) (wait for any n standbys)None built in (one machine holds everything; sharding is added by the application or extensions)A standby may be behind; remote_apply or waiting for the LSN gives read-your-writes (measured above)None inside; failover via Patroni and etcd/Consul/ZooKeeper, or the cloud provider
DynamoDB (Elhemali et al., ATC 2022; docs)Each partition: 3 replicas in 3 zones; a write is acknowledged "once a quorum of peers persists the log record"Hash of the partition keyEventually consistent by default, "half the cost of strongly consistent reads"; ConsistentRead=true on tables and local indexes (served by the leader); global indexes always eventualMulti-Paxos per partition; leader holds a renewed lease
DynamoDB global tables (docs)Multi-region, multi-activeAs above, per regionMREC (default): replicated "typically within a second"; MRSC: "synchronously replicated to another Region before the write returns", strong reads on any replicaAs above
Spanner (Corbett et al. 2012; docs)Paxos groups, typically across zones or regionsKey ranges (splits) moved between Paxos groupsExternal consistency (strict serialisability) by default; stale reads at a chosen timestamp are cheaperPaxos per group, 2PC across groups, TrueTime commit wait
Cassandra (docs)Leaderless, replication factor per keyspaceConsistent hashing on a token ring with virtual nodesPer query: ONE, QUORUM, LOCAL_QUORUM, ALL, ...; conflicts settled by last-write-wins timestampsPaxos only for lightweight transactions (compare-and-set)
etcd (docs v3.6; Jepsen 2020)Raft, every member a full copyNone (small data, "by default, up to 8 GB")Linearisable by default since 3.0; "serializable" reads from a local member are faster and may be staleRaft; heartbeat 100 ms, election timeout 1,000 ms by default
Kafka (4.0 release, 18 Mar 2025)Each partition has a leader and followersTopics split into partitions by keyConsumers read from the leader (follower fetching optional); delivery semantics, and share groups (Kafka 4.2's queue-style consumption, where several consumers share one partition and acknowledge records one by one), in Queues, streams and async workKRaft (Raft-based controller quorum); 4.0 is "the first major release to operate entirely without Apache ZooKeeper" (Kafka 4.0 announcement)
MongoDB (Jepsen 2020)Replica sets, single primaryOptional sharding by a shard key (mongos routes)Tunable read and write "concerns"; see the Jepsen finding below"a homegrown consensus protocol which draws inspiration from Raft"

Sources: PostgreSQL 18 replication settings; DynamoDB read consistency; Elhemali et al. 2022; Spanner docs; Cassandra docs; etcd tuning and API guarantees; Jepsen etcd 3.4.3; Jepsen MongoDB 4.2.6. Cassandra's use of Paxos for lightweight transactions and Kafka's optional follower fetching are standard features not re-read for this page (unconfirmed here).

Jepsen (Kyle Kingsbury and collaborators) runs real databases on real clusters, injects partitions, crashes, pauses and clock skew, records every operation's history and checks it against the promised consistency model: the histories of section 5, at scale. Across twelve years the hard parts it finds are the ones on this page: stale reads after leader changes, locks without fencing, retries of non-idempotent operations, isolation levels that do not mean what their names say, and acknowledgements before durability.

Ten Jepsen findings, 2014 to 2026 (optional reference)

As Jepsen puts it, "we can prove the presence of bugs, but not their absence" (NATS 2.12.1 report). Oldest first; the full list is on Jepsen's analyses page.

DateSystemFindingLesson
2014-06-09etcd 0.4.1"exhibited stale reads by default due to an optimization": reads served locally by a leader that might have been replaced (as recounted in the 2020 report)A Raft read must confirm leadership; fixed (linearisable default since 3.0)
2020-01-30etcd 3.4.3Key-value operations "appear to be strict serializable", watches deliver every change in order; but "etcd locks are fundamentally unsafe", ~18% of acknowledged updates lost with 2 s leases and pausesLocks need fencing tokens
2020-05-15MongoDB 4.2.6"even at the strongest levels of read and write concern, it failed to preserve snapshot isolation"; weak defaults could "lose writes and allow dirty reads". MongoDB then traced the anomalies to a transaction-retry bug, patch scheduled for 4.2.8Defaults matter; read the concern levels
2020-06-12PostgreSQL 12.3Serialisable was not serialisable (G2-item); "repeatable read" is snapshot isolationEven mature single-node databases have isolation bugs
2020-06-23Redis-Raft (dev build)"twenty-one issues", including "stale reads", "split-brain leading to lost updates, and total data loss on any failover"; all but one addressed in later builds"Uses Raft" is not "implements Raft correctly"
2023-12-19MySQL 8.0.34Repeatable Read allows lost update and more; RDS MySQL clusters "routinely violate Serializability"Know what your isolation level allows
2024-08-08jetcd 0.8.2The official Java client "incorrectly retries non-idempotent requests which may have actually succeeded"A retry is only safe if the operation is idempotent (the "reply lost" case)
2025-04-29Amazon RDS for PostgreSQL 17.4Multi-AZ clusters show Long Fork: replicas apply commits in WAL order, the primary in lock orderA replica can disagree with its primary on order, not only on freshness
2025-12-08NATS 2.12.1Lost committed writes and "persistent split-brain" after coordinated crashes, partly from flushing "to disk every two minutes, rather than before acknowledging them"An acknowledgement is only as durable as the fsync behind it
2026-03-16MariaDB Galera Cluster 12.1.2"When all nodes crashed at approximately the same time", it "regularly lost committed transactions", with innodb_flush_log_at_trx_commit = 0, which MariaDB's docs had called "a safer, recommended option" for GaleraReplication is not a substitute for durability when failures are correlated

Neighbours that own the rest: a standby query cancelled by replay conflicts (max_standby_streaming_delay, hot_standby_feedback) is in Running Postgres in production; database families (OLTP, OLAP, key-value, vector) are compared on Topic: databases. The old page's rule of thumb, kept as advice (opinion, not a sourced claim): start with Postgres + S3 + Redis, add a column store when analytics queries hurt, add Kafka when more than two systems need the same events.