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).
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).
| Problem | Technique | What it costs | Where you meet it |
|---|---|---|---|
| One machine dies, or cannot keep up with reads | Replication: copies on several machines, one leader takes writes | Copies lag; a reader can see the past | Postgres streaming replication, MySQL, MongoDB |
| You want to write in several places | Multi-leader, or leaderless with quorums (N, R, W) | Conflicting writes; someone must decide which wins | Cassandra, DynamoDB global tables, CouchDB |
| "Did my write happen? Will others see it?" | Consistency models: linearisable, sequential, causal, eventual | Stronger means more waiting and less availability during failures | Every database's docs; CAP and PACELC |
| Machines must agree on one leader or one order | Consensus: Raft or Paxos over a majority | A round trip to a majority per decision; no progress without a majority | etcd (Kubernetes), Consul, Kafka KRaft, Spanner, DynamoDB |
| A paused process still thinks it is in charge | Leases and fencing tokens | The storage must check a number on every write | ZooKeeper zxid, etcd revision, Chubby sequencers |
| A retry after a lost reply runs the work twice | Idempotency at the end points (at-least-once plus deduplication) | A stored key per operation, checked in the same transaction as the effect | Payment APIs, Kafka's idempotent producer, every job queue |
| The data or write rate outgrows one machine | Partitioning (sharding) by key range or hash; consistent hashing | Hot keys; moving data when machines are added; queries across shards | Every large database; Notion, Figma, Instagram, Discord |
| Ordering events when clocks disagree | Logical clocks (Lamport, vector, hybrid) or bounded clocks (TrueTime) | Metadata on every message, or waiting out the uncertainty | CockroachDB, Spanner, Dynamo, Cassandra's last-write-wins |
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.
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).
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 belief | What actually happens, and what you do about it |
|---|---|
| 1. The network is reliable | Packets are dropped, links are cut, switches are misconfigured. Every call needs a timeout and a plan for "unknown outcome". |
| 2. Latency is zero | A 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 infinite | Copying a big table to a new replica, or rebalancing shards, can saturate links and slow live traffic. Throttle background copies. |
| 4. The network is secure | Anything on the wire can be read or forged unless encrypted and authenticated (TLS between services, not only at the edge). |
| 5. Topology does not change | Machines come and go, IP addresses move, autoscaling adds nodes. Discover peers dynamically; never hard-code addresses. |
| 6. There is one administrator | Your 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 zero | Serialising data costs CPU, and cross-zone and cross-region traffic is billed per GB (egress prices in Numbers to know). |
| 8. The network is homogeneous | Different 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).
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.
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).
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.
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.
The leader can confirm a write to the client before or after followers have it:
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.
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.
| Mode | Commit waits for | Reads that missed the write | Commit, median | Commit, p99 |
|---|---|---|---|---|
| Asynchronous (default) | primary's own flush | 1,993 of 2,000 (99.65%) | 0.150 ms | 0.588 ms |
Synchronous, on | replica has flushed WAL | 1 of 2,000 (0.05%) | 0.244 ms | 0.821 ms |
Synchronous, remote_apply | replica has replayed it | 0 of 2,000 | 0.266 ms | 0.859 ms |
| Asynchronous + client waits for position | primary's flush; the reader waits for replay | 0 of 2,000 | 0.206 ms | 0.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.
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.
Illustrative positions and timing; the stale-read rate and the wait are the measured ones beside section 3's table.
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.
-- 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 trueIf 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:
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.
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.
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.
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:
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).
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 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).
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).
"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:
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.
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.
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+".
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
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.
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):
| Class | Meaning | Abadi's examples (2012) |
|---|---|---|
| PA/EL | Give up consistency both under partition and for speed | "The default versions of Dynamo, Cassandra, and Riak" |
| PC/EC | Never give up consistency; pay in availability and latency | "Fully ACID systems such as VoltDB/H-Store and Megastore", BigTable and HBase |
| PA/EC | Consistent normally, available under partition | MongoDB (as of 2012) |
| PC/EL | Fast normally; under partition it does not reduce consistency further | Yahoo'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.
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 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.
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.
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.
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).
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).
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?
Illustrative amounts and timing; the tokens 33 and 34 are Kleppmann's.
Real evidence that this matters:
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.
Illustrative amounts and key.
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.
k-7f3, that names this one charge, and will reuse it on every retry.k-7f3 with its result into a table with a unique key.k-7f3 again: the operation has a name the end can recognise.k-7f3 fails on the unique key, so payments returns the result it stored the first time. One charge, and the app finally hears "ok, balance 90". At-least-once delivery plus this check is the exactly-once effect.The recipe, wherever the end is (a payment service, a database, a job handler):
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).
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.
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.
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.
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.
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.
| System | Replication | Partitioning | Default read, and the stronger option | Agreement |
|---|---|---|---|---|
| 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 key | Eventually consistent by default, "half the cost of strongly consistent reads"; ConsistentRead=true on tables and local indexes (served by the leader); global indexes always eventual | Multi-Paxos per partition; leader holds a renewed lease |
| DynamoDB global tables (docs) | Multi-region, multi-active | As above, per region | MREC (default): replicated "typically within a second"; MRSC: "synchronously replicated to another Region before the write returns", strong reads on any replica | As above |
| Spanner (Corbett et al. 2012; docs) | Paxos groups, typically across zones or regions | Key ranges (splits) moved between Paxos groups | External consistency (strict serialisability) by default; stale reads at a chosen timestamp are cheaper | Paxos per group, 2PC across groups, TrueTime commit wait |
| Cassandra (docs) | Leaderless, replication factor per keyspace | Consistent hashing on a token ring with virtual nodes | Per query: ONE, QUORUM, LOCAL_QUORUM, ALL, ...; conflicts settled by last-write-wins timestamps | Paxos only for lightweight transactions (compare-and-set) |
| etcd (docs v3.6; Jepsen 2020) | Raft, every member a full copy | None (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 stale | Raft; heartbeat 100 ms, election timeout 1,000 ms by default |
| Kafka (4.0 release, 18 Mar 2025) | Each partition has a leader and followers | Topics split into partitions by key | Consumers 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 work | KRaft (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 primary | Optional 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.
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.
| Date | System | Finding | Lesson |
|---|---|---|---|
| 2014-06-09 | etcd 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-30 | etcd 3.4.3 | Key-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 pauses | Locks need fencing tokens |
| 2020-05-15 | MongoDB 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.8 | Defaults matter; read the concern levels |
| 2020-06-12 | PostgreSQL 12.3 | Serialisable was not serialisable (G2-item); "repeatable read" is snapshot isolation | Even mature single-node databases have isolation bugs |
| 2020-06-23 | Redis-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-19 | MySQL 8.0.34 | Repeatable Read allows lost update and more; RDS MySQL clusters "routinely violate Serializability" | Know what your isolation level allows |
| 2024-08-08 | jetcd 0.8.2 | The 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-29 | Amazon RDS for PostgreSQL 17.4 | Multi-AZ clusters show Long Fork: replicas apply commits in WAL order, the primary in lock order | A replica can disagree with its primary on order, not only on freshness |
| 2025-12-08 | NATS 2.12.1 | Lost 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-16 | MariaDB 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 Galera | Replication 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.
Times are estimates for a careful first read. Links checked 2026-10-04; the Raft cluster and the consistency histories that used to be tabs are now inside the Reading tab (sections 5 and 7).
The from-zero overview: one request to an LLM chat product as it grows from 1 user to 10 million. Its Step 2 introduces replicas, sharding and CAP in one paragraph each; this page is their depth. Tabs: Scale simulator (watch the database and replicas saturate), Numbers to know (round trips, fsync, disk; used here for the 2 ms, 69 ms and 78 ms figures), Case files (GitHub 2018, AWS DynamoDB DNS 2025, Discord 2023, Notion 2021, Instagram 2012, cited above). About 21 min.
Timeouts, retries with backoff and jitter, retry budgets, circuit breakers, SLOs, incidents: what to do about the "unknown outcome" of a timeout. About 40 min.
Delivery semantics (at-most-once, at-least-once, exactly-once processing), Kafka, the outbox pattern for dual writes, backpressure and dead-letter queues. About 33 min.
The service behind the API: request lifecycle, the data layer, async and workers, graceful shutdown (idempotency keys on the API are Service APIs, section 4). About 27 min.
Load balancing, caching, queueing and load testing: how many replicas and shards you need. About 39 min.
Logs, metrics, traces: how you would see replication lag, elections and stale reads in production. About 39 min.
Worked designs where these choices are made end to end. About 41 min.
LLM services end to end: where gateways and GPU autoscaling fit, tenancy, batch paths, caching, rollouts, the degradation ladder. About 28 min.
Unit, property-based, data and model tests, and CI, with real pytest code. About 46 min.
Readable code, abstractions, refactoring in small tested steps, code review, library design. About 42 min.
Storage engines, indexes, MVCC, isolation levels in depth, database families. Its Transactions and concurrency and Scaling a database pages own isolation inside one database and read replicas and sharding in practice.
TCP, TLS, HTTP/2 and gRPC: the messages this page assumes.
Kubernetes (which keeps all its state in etcd) and the schedulers built on it.
A different kind of distributed system: many GPUs in lockstep, where the failure story (checkpoints, restarts) shares this page's vocabulary.
Kleppmann and Riccomini, O'Reilly, March 2026. The anchor book: its middle part (replication, sharding, transactions, what goes wrong in distributed systems, consistency and consensus) is this page at full length. About 15 to 20 h for the whole book; 6 h for those chapters.
The clickable map from eventual to strict serializable, each model with its definition, examples and availability. About 20 min.
Jeff Hodges, 2013. The mindset in one essay. About 20 min.
Breadth-first interview coverage of everything above. About 2 h for the core sections.
Free notes: models, clocks, broadcast, replication, quorums, Raft, consistency, CRDTs. A rigorous, compact course. About 6 h, more with the exercises.
A narrated animation of Raft elections and replication, a gentle complement to the Raft cluster in section 7. About 10 min.
USENIX ATC 2014 (extended version). Figure 2 is the whole algorithm on one page. About 1.5 h.
2016. Leases, GC pauses, fencing tokens, and why Redlock depends on timing. About 25 min.
2020. A model Jepsen report: what was strict serializable, why locks are unsafe, and the fencing fix. About 40 min.
2002. The CAP proof; the definitions are the point. About 45 min.
2017. CAP from its author, with Google's incident data. About 20 min.
IEEE Computer, 2012. PACELC and the classification table. About 20 min.
SOSP 2007 (leaderless, consistent hashing, vector clocks, sloppy quorums) and USENIX ATC 2022 (what DynamoDB actually became: Multi-Paxos per partition). Read them as a pair. About 1 h each.
OSDI 2012. Paxos groups, TrueTime, commit wait, 2PC over Paxos. About 1.5 h.
CACM 1978. Happened-before and logical clocks. About 40 min.
ACM Queue, 2014. A catalogue of real partitions and what they did (not re-read for this page; the site refuses automated fetches). About 30 min.
Every report since 2013; read the one for the database you run. 30 to 60 min each.
src/ (sh src/build.sh). Measurements: src/measure_replication.py. Checks: src/recompute.py with src/check_recompute.mjs, src/check_raft.mjs. Old page kept verbatim in src/live.md, mapped in src/coverage.json.