Library

Volume 1 · System Architecture & Distributed Systems

Notebook
Sign in

Section 1

Foundations of Distributed Systems

1,871 words · about 9 min

1.1 What is a Distributed System?

A distributed system is a collection of independent computers that appear to users as a single coherent system.

Key architectural realities:

  • Foundational Theory: Microservices, globally replicated databases, and event-streaming platforms all build upon distributed systems principles.
  • Architectural Trade-offs: Every major design decision—selecting databases, inter-service communication protocols, and multi-region disaster recovery—involves fundamental distributed systems trade-offs.

1.2 Key Properties of Distributed Systems

Property Description
Scalability Ability to handle growing workloads by adding resources
Reliability System continues to function correctly despite component failures
Availability System remains accessible and operational (uptime)
Consistency All nodes see the same data at the same time
Partition Tolerance System continues to operate despite network partitions (dropped/delayed messages between nodes)
Fault Tolerance System masks failures from the end user
Transparency Distribution is hidden from the user (access, location, replication transparency)

1.3 CAP Theorem — Deep Dive

The CAP theorem (Eric Brewer, 2000) states that a distributed data store can only guarantee two of the following three guarantees simultaneously:

  • Consistency ©: Every read receives the most recent write or an error.
  • Availability (A): Every non-failing node returns a response for every request (without guarantee it contains the latest write).
  • Partition Tolerance (P): The system continues to operate despite arbitrary message loss or network partitions.
flowchart TD
    subgraph CAP["CAP Theorem"]
        C["Consistency"]
        A["Availability"]
        P["Partition Tolerance"]
    end

    C --- A
    A --- P
    P --- C

    CA["CA Systems\n• Single-node RDBMS\n• Non-distributed"] -.-> C & A
    CP["CP Systems\n• HBase, ZooKeeper\n• MongoDB majority write\n• Cosmos DB (Strong)"] -.-> C & P
    AP["AP Systems\n• Cassandra, DynamoDB\n• CouchDB\n• Cosmos DB (Eventual)"] -.-> A & P

The Partition Reality:

  • Because physical networks inevitably experience latency spikes, dropped packets, and fiber cuts, Partition Tolerance (P) is mandatory in real distributed networks.
  • In practice, your real design decision is: How does the system behave when a partition happens?
    • CP (Consistency + Partition Tolerance): Sacrifices availability during partitions to prevent split-brain and preserve exact data correctness.
    • AP (Availability + Partition Tolerance): Sacrifices strict consistency during partitions to remain 100% responsive, resolving differences later via eventual consistency.

Practical System Choices:

  • CP Systems:
    • When to use: Non-negotiable data correctness (e.g., financial ledgers, inventory reservation, leader election, distributed locks).
    • Trade-off: Requests may be delayed, rejected, or return errors while partitions persist.
  • AP Systems:
    • When to use: Maximum uptime where slight staleness is tolerable (e.g., shopping carts, social feeds, user telemetry, metrics aggregation, recommendation engines).
    • Trade-off: Clients may temporarily view stale data until convergence.
  • CA Systems:
    • Reality: Only valid for single-node systems or monolithic clusters on fully redundant hardware without network boundaries.

Interview Tip: Don’t just recite the theorem — narrate a trade-off you actually made: “In our retail platform, we chose Cassandra (AP) for user activity tracking and cart updates because availability drove conversion, and a 2-second convergence window was acceptable. Conversely, for the payment ledger and ledger balance deductions, we isolated a CP relational store because double-spending or silent failures were completely unacceptable.”

1.4 PACELC — The CAP Extension You Should Actually Use

CAP only describes behavior during a partition. PACELC (Daniel Abadi) extends this to real-world normal operation:

“If there is a Partition, trade off Availability vs Consistency; Else (normal operation), trade off Latency vs Consistency.”

Why PACELC Matters:

  • Distributed systems operate normally without active partitions over 99.9% of the time.
  • The everyday trade-off architects make on every single API call is Latency vs. Consistency, not Availability vs. Consistency.
System During Partition (P) Normal Operation (E)
Single-node SQL Server / PostgreSQL N/A (no partition tolerance) Consistent (PC)
Cosmos DB — Strong consistency Choose Consistency (PC) Choose Consistency, higher latency (EC)
Cosmos DB — Eventual consistency Choose Availability (PA) Choose Latency, lower latency (EL)
Cassandra Choose Availability (PA) Choose Latency (EL) — fast local reads
MongoDB (replica set, primary reads) Choose Consistency (PC) Choose Consistency (EC)
DynamoDB (eventually consistent reads) PA EL

Interview Framing:

“CAP tells the interviewer I know the theory. PACELC demonstrates that I understand real-world engineering: 99.9% of the time my cluster is healthy, so the decision I am making for each service is balancing write/read latency against strict synchronization.”

1.5 Consistency Models — Full Spectrum

Consistency is not a binary choice between strong and eventual—it is a continuum. Azure Cosmos DB’s five-tier model provides the industry-standard reference:

Model Guarantee Typical Use Case
Strong Every read returns the most recent committed write; linearizable Financial transactions, inventory counts, distributed locks
Bounded Staleness Reads lag writes by at most K versions or T time Leaderboards, near-real-time dashboards
Session A single client always sees its own writes (“read-your-writes”) Shopping cart, user profile edits — default in many systems
Consistent Prefix Replicas never see writes out of order (no gaps, but may be stale) Chat message ordering, activity feeds
Eventual All replicas converge given no new writes — no ordering guarantee Like/view counters, DNS, caching layers

Key Consistency Vocabulary:

  • Linearizability: The strongest guarantee; all operations appear atomic and globally ordered on a shared timeline.
  • Causal Consistency: Causally linked operations are visible to all nodes in identical order; concurrent unrelated operations may arrive out of order.
  • Read-Your-Writes: Client-scoped guarantee ensuring an author immediately sees their own updates.
  • Monotonic Reads: Once an observer observes a version, they will never observe an earlier version on subsequent reads.

1.6 Distributed Consensus — Raft (and Paxos Context)

Distributed systems require consensus algorithms to agree on cluster state (e.g., leader election, log replication) despite hardware crashes and network delays. Raft was explicitly designed to be more understandable than Paxos.

sequenceDiagram
    autonumber
    participant Client
    participant Leader
    participant Follower1 as Follower 1
    participant Follower2 as Follower 2

    Note over Leader,Follower2: Normal Log Replication Flow
    Client->>Leader: Write Request (Command)
    Leader->>Leader: Append entry to local log
    par Replicate to quorum
        Leader->>Follower1: AppendEntries RPC
        Leader->>Follower2: AppendEntries RPC
    end
    Follower1-->>Leader: Ack (Success)
    Follower2-->>Leader: Ack (Success)
    Note over Leader: Majority Quorum Reached (2/3 Nodes)
    Leader->>Leader: Commit entry & apply to state machine
    Leader-->>Client: Success Response
    Leader->>Follower1: Notify Commit Index (Heartbeat)
    Leader->>Follower2: Notify Commit Index (Heartbeat)

Core Mechanics of Raft:

  1. Leader Election:
    • All nodes start in Follower state with randomized election timeouts (e.g., 150ms–300ms).
    • If a follower misses leader heartbeats, it transitions to Candidate, increments the term, and solicits votes.
    • The first candidate to collect a majority vote becomes the Leader and transmits periodic heartbeats.
  2. Log Replication:
    • The client dispatches write operations exclusively to the Leader.
    • The Leader appends entries locally and replicates them via AppendEntries to all followers in parallel.
    • Once a majority quorum acknowledges receipt, the log entry is marked committed.
    • The leader applies the committed entry to its state machine and returns success to the client.
  3. Fault Tolerance Boundaries:
    • Requires a strict majority alive: a cluster of size $N$ can withstand $\lfloor (N-1)/2 \rfloor$ node failures.
    • 3-node cluster survives 1 failure; 5-node cluster survives 2 failures.

Production Systems Using Raft/Paxos-Family Consensus:

  • etcd: Raft consensus (backing Kubernetes control plane state)
  • ZooKeeper: ZAB protocol (Paxos variant, backing Kafka legacy & Hadoop)
  • Consul: HashiCorp Raft
  • CockroachDB & Google Spanner: Multi-Raft / Multi-Paxos for distributed SQL
  • Apache Kafka (KRaft mode): Native Raft replacing ZooKeeper metadata dependencies
// Practical use: leader election for a singleton background worker
// using a distributed lock (Redis/RedLock or a Raft-backed store)
public class LeaderElectionService : BackgroundService
{
    private readonly IDistributedLockProvider _lockProvider;
    private readonly string _lockKey = "leader-election:order-processor";

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            await using var handle = await _lockProvider.TryAcquireAsync(
                _lockKey, timeout: TimeSpan.FromSeconds(30), cancellationToken: ct);

            if (handle != null)
                await DoLeaderWorkAsync(ct);      // I am the leader
            else
                await Task.Delay(TimeSpan.FromSeconds(5), ct); // Someone else is leader
        }
    }
}

1.7 Section 1 — Interview Q&A

Q1: Explain CAP theorem and PACELC. Why does PACELC matter more in practice?

A: CAP says that during a network partition, a distributed data store must choose between consistency and availability — you cannot have both alongside partition tolerance, and in a real network, partitions are unavoidable, so P is effectively mandatory. PACELC extends this by pointing out that CAP only describes rare, abnormal operation (a partition). Most of the time the system is healthy, and the real, constant trade-off is latency vs. consistency. A system like Cassandra is PA/EL — available during partitions, and optimized for low latency during normal operation at the cost of consistency. I use PACELC when justifying database choices because it forces me to reason about both failure-mode behavior and everyday-mode behavior, not just the theoretical partition scenario.

Q2: Give an example of when you’d deliberately choose an AP system over a CP system, and vice versa.

A: For a global shopping cart service, I’d choose an AP system (e.g., Cosmos DB with session consistency, or DynamoDB) because the system must always accept “add to cart” even during a regional network issue — losing a cart addition or showing slightly stale cart state is a minor UX issue, but rejecting the write entirely is a lost sale. For a payment ledger or inventory reservation system, I’d choose a CP system (a strongly consistent relational database, or Cosmos DB in Strong consistency mode) because double-spending money or overselling the last unit of inventory is a correctness violation with real financial and legal consequences — here, I’d rather the system briefly reject a write than allow a stale one to succeed.

Q3: What is linearizability and why is it rarely used in globally distributed systems?

A: Linearizability is the strongest consistency guarantee — every operation appears to take effect instantaneously at some point between its invocation and its response, and all nodes agree on a single global ordering of all operations. It’s rarely used globally because it requires coordination (usually via a leader or consensus protocol) on every write, which means every write pays the cost of a round trip to whichever node/region holds authority — this destroys the low-latency benefit of a globally distributed system. In practice, I scope linearizability to a narrow, critical resource (e.g., a distributed lock or a single aggregate’s writes) rather than applying it system-wide, and use weaker models (session, bounded staleness) everywhere else.

Q4: How does Raft achieve consensus, and what happens if the leader crashes mid-write?

A: Raft elects a single leader via majority vote; the leader is the only node that accepts writes, appends them to its log, and replicates to followers. A write is only considered “committed” once a majority of nodes have durably stored it — only then does the leader acknowledge the client. If the leader crashes after replicating to a majority but before acknowledging the client, the entry is still safe: any new leader elected afterward must have that entry in its log (because election requires votes from a majority, and at least one voter will have seen the committed entry), so the write is not lost — the client might just need to retry to get its acknowledgment. If the leader crashes before reaching a majority, the write is lost, which is why clients should treat un-acknowledged writes as failed and retry idempotently.