Key Formulas & Code Examples
At most 2 of 3: Consistency, Availability, Partition tolerance
Amdahl's Law: Speedup = 1/[(1-P) + P/N]
Little's Law: L = ฮปW (concurrency = throughput ร latency)
Vector Clocks: VC[i] = local counter; happens-before: VCa โบ VCb iff โi: VCa[i] โค VCb[i]
for {
if election_timeout: become_candidate(), term++
if votes > majority: become_leader()
if higher term: step down
}
Core Concepts
Paxos (Lamport) and Raft (Ongaro) ensure distributed systems agree on a single value despite failures. Raft: leader election, log replication, safety. Used in etcd, Consul, TiKV.
Primary-backup: writes go to primary, replicated to backups. Multi-primary: multiple nodes accept writes (conflict resolution needed). Chain replication: writes flow through a chain of replicas.
Distributing data across nodes by key range, hash, or consistent hashing. Enables horizontal scaling. Hotspots and rebalancing are key challenges. Example: user data sharded by user_id % N.
Heartbeats with timeout. Gossiph style: nodes exchange state periodically. Phi accrual failure detector (Hayashibara) outputs suspicion level vs binary detection.
Two-phase commit (2PC): prepare + commit phases. Blocking if coordinator fails. Three-phase commit (3PC) adds pre-commit but adds latency. Modern alternative: Calvin (deterministic), Spanner (TrueTime), sagas (compensating transactions).
Core Definitions
Worked Examples
During a network partition: CP system (HBase, MongoDB): stops accepting writes to maintain consistency. AP system (Cassandra, DynamoDB): continues accepting writes on both sides, reconciles later.
Nodes and keys mapped to a ring. Key k is stored on the next clockwise node. Adding/removing a node affects only adjacent keys โ minimal redistribution. Virtual nodes improve balance.
VCA = [2,1,0], VCB = [1,2,1]. Neither dominates (A[0]>B[0] but B[1]>A[1], B[2]>A[2]). These events are concurrent โ potential conflict requiring application-level resolution.
Practice Problems
Answer: A distributed system can provide at most two of: Consistency (all nodes see same data), Availability (every request gets response), Partition tolerance (system survives network failures). During partitions, choose C or A.
Answer: 2PC: prepare + commit; blocks if coordinator fails during commit. 3PC: adds pre-commit phase; non-blocking but adds an extra round-trip and assumes bounded network delays.
Answer: Election safety: at most one leader per term. Log matching: entries with same index and term are identical. Leader completeness: leader's log contains all committed entries.
Answer: Same result regardless of how many times an operation is executed. Enables safe retries in distributed systems. Implemented via unique request IDs, idempotency keys, or natural idempotency (PUT/DELETE).
Answer: Two nodes both think they're leader during a partition. Prevented by: quorum-based voting (majority), fencing tokens (older epochs rejected), and external coordination (ZooKeeper).