{}DSA Atlas

Distributed Systems Theory

The fallacies of distributed computing, failure models, time and clocks (NTP, Lamport and vector clocks, hybrid logical clocks, TrueTime), consensus with Raft and Paxos, leader election and fencing tokens, quorums, gossip and failure detection, consistency models from linearizable to eventual, CRDTs, and distributed transactions (2PC vs sagas).

Advanced7 interview questions

The eight fallacies of distributed computing

  1. The network is reliable. 2. Latency is zero. 3. Bandwidth is infinite. 4. The network is secure. 5. Topology doesn't change. 6. There is one administrator. 7. Transport cost is zero. 8. The network is homogeneous.

Every design decision in this chapter exists because these are false.

Failure models

ModelMeaning
Crash-stopa node fails and never returns
Crash-recoverynodes crash and restart with durable state (most real systems)
Omissionmessages lost
Byzantinenodes behave arbitrarily or maliciously (blockchains, aerospace)
Network partitiongroups of nodes can't communicate
Gray failurepartially working: slow disk, flapping NIC — hardest to detect

You cannot distinguish a slow node from a dead one (FLP impossibility: deterministic consensus is impossible in a fully asynchronous system with even one crash) — practical systems use timeouts and accept occasional false suspicion.

Time and clocks

P1 P2 P3 1 2 3 1 4 5 1 6 on send: C = C+1 · on receive: C = max(C, msg) + 1
Lamport clocks: if a → b then L(a) < L(b). The converse is not true — vector clocks detect concurrency.
ClockGivesUsed by
Wall clock (NTP)approx. real time, can jumplogs, TTLs (with care)
Monotonic clockdurations on one machinetimeouts, latency measurement
Lamport clocktotal order consistent with causalitysimple ordering
Vector clockdetects concurrent vs causally orderedDynamo, Riak conflict detection
Hybrid logical clockwall-ish time + causalityCockroachDB, MongoDB
TrueTimetime interval with bounded uncertaintySpanner (commit wait)

Consensus: Raft

client leader (term 7)log: 1 2 3 4 [5] follower A1 2 3 4 [5] ✓ follower B1 2 3 4 [5] ✓ follower C (slow)1 2 3 entry 5 committed: stored on 3 of 4 nodes
An entry is committed once a majority stores it; the slow follower catches up later.

Key ideas: terms (logical epochs), randomised election timeouts (avoid split votes), majority quorums (any two majorities intersect, so a new leader always has every committed entry), log matching, snapshots for compaction, and joint consensus for membership changes.

Paxos solves the same problem (Multi-Paxos for a log); it's older and harder to understand; Raft was designed for understandability. ZAB powers ZooKeeper.

Leader election, leases and fencing

lock service client 1 (GC pause) client 2 storagemax token seen = 34 token 33 → client 1 · lease expires · token 34 → client 2 write(token 34) ✓ late write(token 33) ✗ rejected
The resource enforces exclusivity using monotonically increasing tokens.

Use etcd/ZooKeeper/Consul for leader election (leases with keep-alives). Split brain — two nodes both acting as leader — is prevented by majority quorums plus fencing.

Quorums and leaderless replication

Text
N = 3 replicas, W = 2, R = 2   →  W + R = 4 > 3  → every read overlaps the latest write
write v2:  [A: v2] [B: v2] [C: v1]   (C missed it)
read:      ask A + C → see v2 and v1 → return v2, repair C (read repair)

Gossip and failure detection

Gossip protocols: each node periodically exchanges state with a few random peers; information spreads epidemically in O(log n) rounds. Used for membership and failure detection (Cassandra, Consul's Serf/SWIM), and for disseminating cluster state. Phi accrual failure detector outputs a suspicion level instead of a binary alive/dead, adapting to network jitter. SWIM uses indirect pings via other members to reduce false positives.

Consistency models

linearizablesingle copy sequentialone global order causalcause before effect sessionRYW, monotonic eventualconverges someday ← stronger: easier to reason about, more coordination, higher latencyweaker: available under partition, faster →
Choose the weakest model that keeps your invariants and your users sane.

Session guarantees (read-your-writes, monotonic reads, monotonic writes, writes-follow-reads) are often all users actually need.

CRDTs

Python
class GCounter:
    """Grow-only counter: each node increments its own slot; merge = element-wise max."""
    def __init__(self, node_id):
        self.id, self.counts = node_id, {}

    def increment(self, n=1):
        self.counts[self.id] = self.counts.get(self.id, 0) + n

    def value(self):
        return sum(self.counts.values())

    def merge(self, other):
        for node, c in other.counts.items():
            self.counts[node] = max(self.counts.get(node, 0), c)

Distributed transactions

create order reserve stock charge card book courier ✗ refund card release stock cancel order
Sagas undo completed steps with compensations instead of holding distributed locks.
2PCSaga
Atomicityyeseventual (via compensation)
Isolationyes (locks)no — intermediate states visible
Availabilityblocked by any participant/coordinator failurehigh
Latencymultiple round trips holding lockseach step local
Useinside a DB / tightly coupled resourcesmicroservices, long-running workflows

Interview questions

0 / 7 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.