Interview Study Guide

Guide / System design Fundamentals

8. Distributed systems theory

Created · Updated · 4 min read

8.1 The fallacies to assume against#

The network is unreliable, latency is not zero, bandwidth is finite, topology changes, clocks drift, and nodes pause (GC, VM migration) for seconds without knowing it. Every design decision below exists because of these.

8.2 Consensus and leader election#

  • Consensus = several nodes agree on one value (who is leader, the order of log entries) despite failures. Needs a majority (quorum): a 5-node cluster tolerates 2 failures; always use odd sizes (3, 5).
  • Raft (etcd, Consul, CockroachDB, Kafka KRaft): leader election with randomized timeouts and terms; the leader replicates log entries; an entry is committed once a majority stores it. Paxos is the older equivalent; ZooKeeper uses ZAB.
  • Use: you rarely implement it; you use etcd/ZooKeeper for leader election, config, service discovery, and distributed locks with fencing.
  • Cost: every write needs a majority round trip → higher latency, especially across regions.

8.3 Distributed locks#

  • Redis SET key value NX PX 30000: simple lease; release with a Lua script that checks the value is yours. Fine for efficiency (avoid duplicate work), not safe for correctness: a GC pause can outlive the lease and two holders act at once; async replication can lose the lock on failover.
  • Redlock (majority of independent Redis nodes) is debated; Martin Kleppmann’s critique: without fencing it’s still unsafe.
  • Fencing tokens: the lock service hands out a monotonically increasing token; the storage rejects writes with an older token. This makes a stale holder harmless.
  • Correctness-critical locks: etcd/ZooKeeper leases, or a DB row lock (SELECT ... FOR UPDATE) / advisory lock. Better still, design so you don’t need a lock (unique constraints, conditional updates, single-writer partitions).

8.4 Time and ordering#

  • Wall clocks drift and NTP can jump backwards → never order events across machines by timestamp alone; last-write-wins with skewed clocks silently drops writes.
  • Lamport clocks: a counter giving a causal order (if A → B then L(A) < L(B)), but can’t detect concurrency.
  • Vector clocks: one counter per node; can detect concurrent writes (used by Dynamo-style stores for conflicts).
  • Hybrid logical clocks (CockroachDB) and TrueTime (Spanner, bounded uncertainty with commit-wait) give globally ordered timestamps.
  • Monotonic clocks for measuring durations within a process.

8.5 Unique ID generation#

OptionPropertiesTrade-off
DB auto-incrementSimple, orderedSingle point of contention; leaks volume; breaks with sharding
UUIDv4Random, no coordination128-bit, random inserts fragment B-tree indexes
UUIDv7 / ULIDTime-ordered + randomIndex-friendly; preferred modern default
Snowflake (64-bit)41 bits ms timestamp + 10 bits machine + 12 bits sequence = 4,096 IDs/ms/nodeNeeds unique machine IDs; clock going backwards must be handled
Ticket server / range allocationEach node leases a block of IDs (1–1000)Gaps on restart; central allocator to keep available

Short-URL codes: base62 of a Snowflake/counter ID (7 chars = 62^7 ≈ 3.5 trillion).

8.6 Consistent hashing#

Place nodes and keys on a hash ring; a key belongs to the next node clockwise. Adding/removing a node moves only ~1/N of keys (vs nearly all with mod N). Virtual nodes (100–200 points per physical node) even out distribution and let bigger machines take more vnodes. Used by Cassandra, DynamoDB, Memcached clients, CDNs, load balancers. Alternatives: rendezvous (highest-random-weight) hashing; jump consistent hash.

8.7 Failure detection and membership#

Heartbeats with timeouts (too short → false positives under load; too long → slow failover), phi-accrual detectors (Cassandra), gossip protocols to spread membership state in large clusters. A node that is merely slow is the hardest case: is it dead or not? This is why fencing and idempotency matter.

8.8 Probabilistic data structures#

  • Bloom filter: “definitely not present” or “maybe present”; tiny memory. Use for cache penetration, “has this URL been crawled”, LSM-tree reads.
  • HyperLogLog: count distinct items (unique visitors) with ~0.8% error in 12 KB.
  • Count-Min Sketch: approximate frequencies (top-K trending hashtags, heavy hitters).
  • Geohash / quadtree / H3: spatial indexing for “nearby drivers/restaurants”.
  • Merkle trees: detect which data ranges differ between replicas (anti-entropy repair) cheaply.
Finished this page?Mark it done to track your progress across the guide.
Pritam Ghosh · System design & AI engineering study notes