SD/Lesson 6 of 8/7 min read
Distributed Systems
Fallacies of distributed computing, CAP and PACELC, consistency models, consensus with Raft, leader election, clocks and ordering, two-phase commit, and failure handling patterns.
On this page
Distributed System
A distributed system is a set of computers that communicate over a network and appear to users as one system. We build them for scale, fault tolerance and geographic reach, and pay for it with partial failures: some parts break while others keep running.
Fallacies of distributed computing
Assumptions that are false and cause bugs:
- The network is reliable.
- Latency is zero.
- Bandwidth is infinite.
- The network is secure.
- Topology does not change.
- There is one administrator.
- Transport cost is zero.
- The network is homogeneous.
A remote call can succeed, fail, or time out, and a timeout tells you nothing about whether the other side did the work. That single fact drives retries, idempotency and most of this lesson.
CAP Theorem
In the presence of a network partition (P), a distributed data store must choose between:
- Consistency (C): every read sees the most recent write (linearizability).
- Availability (A): every request to a non-failed node gets a non-error response.
Partitions are not optional in real networks, so the real choice is CP or AP during a partition.
| Choice | Behavior during partition | Examples |
|---|---|---|
| CP | Refuse or error some requests to stay correct | ZooKeeper, etcd, HBase, Spanner |
| AP | Keep serving, possibly stale or conflicting data | Cassandra, DynamoDB (default), CouchDB |
PACELC
PACELC extends CAP: if there is a Partition, choose A or C; Else (normal operation), choose Latency or Consistency.
Strong consistency costs latency even without failures, because replicas must coordinate before replying.
| System | P: A or C | E: L or C |
|---|---|---|
| DynamoDB, Cassandra | A | L |
| MongoDB (default) | C | L |
| Spanner, etcd | C | C |
Consistency models
From strongest to weakest:
Linearizability
Every operation appears to take effect atomically at one instant between its start and end, and all clients see the same order. It behaves as if there were a single copy. Needed for leader election, locks, unique usernames, and account balances.
Strong Consistency
Commonly used to mean linearizability or serializability: after a write completes, every subsequent read returns it.
Other models
- Sequential consistency: all clients see the same order, but it need not match real time.
- Causal consistency: operations that are causally related (a reply after a post) are seen in order by everyone; concurrent ones may differ.
- Read-your-writes, monotonic reads: per-client guarantees (see replication lag).
Eventual Consistency
If writes stop, all replicas eventually converge to the same value. No bound on when, and reads may be stale meanwhile. Fine for likes, view counts, feeds, DNS, and shopping-cart contents with merge rules.
Consensus
Consensus is getting a group of nodes to agree on a value (or a sequence of values, a replicated log) even if some nodes crash. It underlies leader election, distributed locks, configuration stores and strongly consistent replication.
Quorum
A quorum is a majority: with 2f + 1 nodes, the system tolerates f failures. Any two majorities overlap in at least one node, so a new majority always contains someone who saw the last committed decision. That is why clusters have 3 or 5 nodes: 4 nodes tolerate no more failures than 3.
Raft
Raft is a consensus algorithm designed to be understandable (etcd, Consul, CockroachDB, TiKV).
- Leader election: nodes are followers, candidates or leaders. A follower that hears no heartbeat within a randomized timeout becomes a candidate, increments the term, and requests votes. A majority of votes makes it leader.
- Log replication: clients send commands to the leader, which appends them to its log and replicates to followers. An entry is committed once a majority stores it; then it is applied to the state machine.
- Safety: a candidate only wins if its log is at least as up to date as a majority's, so committed entries are never lost.
Terms act as logical clocks: a node seeing a higher term steps down.
Paxos
Paxos is the original consensus protocol (Lamport). Proven correct but notoriously hard to understand and implement; Multi-Paxos runs Google Chubby and Spanner. Raft is equivalent in fault tolerance and is preferred for new systems.
Leader Election
Many systems want exactly one node to do something (schedule jobs, own a shard). Options:
- Use a consensus store: acquire a lease (a lock with a TTL) in etcd or ZooKeeper; renew it with heartbeats.
- Use the database: a row lock or advisory lock.
Split Brain
Split brain happens when two nodes both believe they are leader (a paused old leader wakes up after its lease expired). Protect with fencing tokens: each new leader gets a higher token number, and storage rejects writes carrying a lower token.
Time and ordering
Physical clocks on different machines drift and NTP corrections can make them jump backwards, so timestamps cannot reliably order events across nodes.
Lamport Clock
A counter per node: increment on each event, send it with messages, and on receive set clock = max(local, received) + 1. If A happened before B, then L(A) < L(B). The converse does not hold, so it cannot detect concurrency.
Vector Clock
Each node keeps a vector of counters, one per node. Comparing two vectors tells you whether one event happened before the other or whether they are concurrent (a conflict). Used in Dynamo-style stores to detect conflicting writes.
Google Spanner uses TrueTime (GPS and atomic clocks with bounded uncertainty) and waits out the uncertainty to get globally ordered timestamps.
Two-Phase Commit
Two-phase commit (2PC) makes a transaction atomic across multiple databases.
- Prepare: the coordinator asks every participant to prepare; each durably records the changes and votes yes or no.
- Commit: if all vote yes, the coordinator tells everyone to commit; otherwise to abort.
Problem: it is blocking. If the coordinator crashes after participants voted yes, they hold locks and cannot decide until it recovers. Expensive and fragile across services, so microservices prefer sagas.
Handling failure
Timeouts and retries
Every network call needs a timeout. Retry only idempotent operations, with exponential backoff, jitter and a retry budget, or retries become a self-inflicted DDoS (a retry storm).
Circuit Breaker
A circuit breaker wraps calls to a dependency:
- Closed: calls pass through; failures are counted.
- Open: after too many failures, calls fail immediately without hitting the dependency, giving it time to recover.
- Half-open: after a cool-down, a few trial calls go through; success closes the circuit, failure reopens it.
It stops cascading failures, where a slow dependency ties up all the caller's threads.
Other resilience patterns
- Bulkhead: isolate resources (separate thread pools or connection pools per dependency) so one failing dependency cannot exhaust everything.
- Graceful degradation: serve a reduced experience (cached results, hide recommendations) instead of failing entirely.
- Rate limiting and load shedding: reject excess work early to protect the core.
- Health checks and redundancy across zones and regions.
Quick revision
- Networks fail, reorder and delay; a timeout does not tell you whether the work happened.
- CAP: during a partition choose consistency or availability. PACELC adds latency vs consistency in normal operation.
- Linearizability is the strongest model; eventual consistency only promises convergence.
- Consensus (Raft, Paxos) needs a majority quorum; 2f + 1 nodes tolerate f failures.
- Use leases and fencing tokens for leader election to avoid split brain.
- Lamport clocks give a causal order; vector clocks detect concurrent writes.
- 2PC is atomic but blocking; prefer sagas across services.
- Timeouts, retries with backoff and jitter, circuit breakers and bulkheads contain failures.