skip to content

learn.smmeyer.devsystem-design06

system-design/06

distributed core · deep · ~4h practice

Distributed systems fundamentals

outcome

Reason precisely about partial failure, partitions, coordination, and retry-safe correctness.

Plan a practice session · ~4h including exercises
Read + trace the worked example
30 min
Assignment + constraint variations
140 min
Timed drill + repeated explanations
50 min
Closed-book recall + self-review
20 min

This is a suggested practice budget, including drawing, variations, and repeated drills. Reading is the first block. Split the work across sessions and use the rubric to judge when to move on.

why this matters

Distributed systems are not single-machine systems with more boxes. Messages delay, clocks disagree, nodes fail independently, and observers can hold different but valid views.

coverage

  • Failure model: partial failure, partitions, omission, crash, Byzantine boundaries.
  • CAP precisely: during a partition, choose availability or linearizable consistency for an operation.
  • Consensus: Raft/Paxos intuition, replicated log, quorum, leader election.
  • Coordination: locks, leases, fencing tokens, membership, discovery.
  • Time: clock skew, monotonic clocks, logical time.
  • Avoidance: idempotency, commutativity, CRDT intuition, partitioned ownership.

mental model

Coordination buys a single decision but costs latency and availability under failure.

  1. 1 →Propose

    Candidate value

  2. 2 →Quorum

    Majority agrees

  3. 3 →Commit

    Ordered log

  4. 4 →Apply

    State converges

Read in numbered order: propose → quorum → commit → apply.

lessons

01Partial failure creates uncertainty

If a request times out, the remote node may be down, the network may be slow, the response may be lost, or the operation may have committed. APIs need stable IDs and retriable semantics because certainty is unavailable.

A process that cannot hear from another process cannot immediately distinguish crash from delay. Consider a scheduler whose worker pauses for a minute. Its lease expires and a replacement receives the job; then the old worker resumes. Both may believe they can write. A lease limits authority in time, but a paused process cannot be trusted to notice expiry before acting.

A fencing token gives each new owner a monotonically increasing generation. The storage service remembers the highest accepted generation and rejects older ones. If owner A holds token 7 and owner B obtains 8, A's later write with 7 is refused after 8 has been installed at the protected resource. Every relevant write path must enforce the rule. A token checked only in the client offers no protection from a stale client.

Use wall-clock time for human timestamps and monotonic time for local elapsed durations. Clock adjustments can make wall-clock intervals negative or misleading. Logical clocks express ordering relationships without promising exact physical time. None of these clocks turns a timeout into proof of failure; your protocol still needs an explicit response to uncertainty.

  • Use monotonic clocks for elapsed time
  • Leases expire; stale holders need fencing tokens
  • Health checks are observations, not truth

02CAP is a partition-time statement

When communication between replicas is partitioned, a given operation cannot both always respond and remain linearizable. Systems make different choices by operation; outside partitions, latency/consistency tradeoffs still exist under PACELC.

Imagine replicas in regions A and B with a broken link. A accepts a change that B cannot observe. If B must always answer reads, it can return the old value. If every completed read must reflect the latest completed write, B may have to reject or wait. CAP describes this conflict during a partition; saying “pick any two” without specifying the failed communication and affected operation misses the mechanism.

A system can make different choices for different operations. A product catalog may return a stale description, while reserving the last item must reach the current inventory owner or fail. State whether “consistent” means linearizable access, read-your-writes, monotonic reads, or eventual convergence. These promises are different and have different implementation costs.

Quorum intersection is a useful condition, not a complete protocol. With N = 3, writes to two replicas and reads from two overlap at at least one replica. You still need rules for versions, concurrent writes, failures during a write, and which value a read chooses. Do not infer linearizability merely from R + W > N. Outside a partition, contacting distant replicas also creates latency tradeoffs.

  • Replication alone does not create availability
  • Quorum intersection can preserve a single history
  • Eventual consistency needs conflict and convergence rules

03Coordinate only what must agree

Consensus maintains a fault-tolerant ordered log. It is useful for metadata, membership, and ownership but expensive in every data operation. Scale by partitioning ownership and making operations idempotent or commutative.

Consensus lets replicas agree on a sequence despite some nodes failing. In a leader-based replicated log, the leader proposes entries, replicas persist them, and the protocol decides when an entry is committed. A new leader must preserve committed history. A three-member majority group can continue with one member unavailable, but not with two; membership changes need protocol rules too.

Use agreement for decisions whose conflict would break an invariant: selecting an owner, changing placement metadata, or ordering noncommutative state transitions. Avoid funneling unrelated independent work through one global agreement point. Partition ownership so different keys can progress separately, while retaining a clear rule for operations spanning owners.

Sometimes change the operation instead of adding coordination. Adding independent counts can be made commutative; assigning each tenant a single writer can remove cross-tenant contention. Convergent replicated structures require carefully defined merge semantics, not an arbitrary “last writer wins” patch. Ask what conflicts the business can accept, how duplicates are handled, and whether a merged state still satisfies the invariant.

  • Majority tolerates minority failure
  • Leader election does not prevent stale actors by itself
  • Exactly-once is usually deduplication plus transactions within a boundary

worked example

A lease expires while its old holder is paused

Worker A holds fencing token 41 and pauses. Its lease expires; worker B obtains token 42 and commits new state. A resumes.

  1. A cannot infer current ownership from its old local lease view. Pauses and delayed messages can outlive the lease.
  2. Attach monotonically increasing fencing tokens to writes. The protected store remembers the highest accepted token and rejects A's later token 41.
  3. The store must enforce the check atomically with the write; merely logging a token offers no protection.
  4. For a five-node majority consensus group, three communicating nodes can commit under its protocol. A two-node minority must not independently accept conflicting leader writes.

Design decision: Use the consensus system for authority and enforce fencing at the resource that must be protected.

Limit: R + W > N alone does not implement linearizability. Version ordering, concurrent writers, membership changes, and protocol rules still matter.

Teaching scenario · traffic, prices, and capacity values are illustrative.

lab

interactive lab

Partition + Lease — who may serve, and who must refuse

1 · predict first

N=5, R=3, W=3, split 3 vs 2: which side serves writes? Decide, then check the verdict.

A guess makes the comparison useful. This lab draft lasts until you leave the page.

pedagogical model — values are illustrative, not measured.

assignment

Produce: A partition timeline and a fenced-write protocol for a job scheduler.

Paper, a text editor, or a spreadsheet is enough. Model access and paid services are optional.

  1. Draw two leaders across a pause, lease expiry, and delayed write; mark which write the store accepts.
  2. Use the lab for majority, minority, and node-down cases; explain each outcome without relying on color.
  3. Compare an availability-first status view with a strict job-ownership path, then defend their different consistency contracts.

Change a constraint

  • The backing store cannot enforce fencing tokens.
  • A client must read its own accepted update during a regional partition.

Self-review rubric

  • The stale holder is rejected at the protected resource.
  • The minority has an explicit failure response.
  • The chosen consistency promise names the operation it covers.

If a criterion is missing, revise that part of the artifact before rating your practice below.

Compare a sample artifact after your attempt

One defensible answer under these assumptions. Compare the reasoning and checks with your work; other designs can satisfy the same contract.

The protected storage path can atomically enforce increasing fencing generations. Tokens come from a coordinated ownership protocol.

t0 A owns lease, token 41
t1 A pauses; lease expires
t2 B receives 42 and installs/commits generation 42 at storage
t3 A resumes and submits write(token=41)
t4 storage rejects 41 < highestAccepted(42)

Storage rule: compare generation and mutate protected state atomically.
Same-generation writes also need operation IDs/ordering as appropriate.
Partition: only the side able to establish valid ownership may change it.

Checking a token in the worker is insufficient: the stale worker is the component we cannot trust to notice expiry. Enforce fencing at every protected effect path. If a backing service cannot fence, use a capable gateway or redesign authority; do not claim the lease alone prevents stale effects.

Check your artifact

  • A's delayed write cannot replace B's newer state.
  • The timeline states that generation 42 is installed before A's stale request reaches storage.
  • A read-your-writes promise during partition requires a valid owner/read position or refusal; an arbitrary stale replica cannot satisfy it.

A tempting mistake: A random unique lock ID identifies owners but does not order them. Fencing needs a comparable generation and resource-side enforcement.

cumulative practice

Relay · build and evolve a private file service

Project brief

Keep one design document for Relay, a tenant-aware file service. Start with 100k daily users, ten downloads per user/day, 10k uploads/day, 1 MB typical bodies, 30-day retention, and a 5× download peak. Files are private to workspaces. Treat these as fictional planning assumptions. Later chapters add previews, recovery, regional constraints, compute, and an assistant. Record each change rather than replacing the earlier version; the final review combines the whole packet. These activities share the chapter's existing practice budget.

Keep one project document across this track. Reconstruct earlier reasoning before opening notes, then revise the same artifact. Use part of the assignment and review budget for this work. If you enter mid-course, sketch the earlier decisions first using the linked chapters.

Add to your project: Relay's leased preview ownership and stale-worker trace.

Reconstruct the crash/redelivery case from the preview pipeline. Now worker A pauses, B takes over, and A resumes. Put fencing and idempotency at their respective boundaries and explain whether a lease on its own protects the published preview.

Compare cumulative reasoning after your attempt

Use an increasing ownership generation enforced on the preview metadata publication. After B installs the newer generation, A's old publish is rejected. A stable preview operation ID handles duplicate attempts within valid ownership; it does not replace fencing across owners. Immutable intermediate objects from rejected attempts can be garbage-collected. A lease checked only by workers cannot prevent a paused stale worker from publishing.

Keep your first attempt and revision together. If your answer differs, identify the assumption or mechanism that explains the difference before rating your recall.

senior signal

Use uncertainty language: “After timeout the outcome is unknown, so the client retries with the same operation ID and reads status.”

failure patterns

  • Explaining CAP as ‘pick any two’ during normal operation
  • Using a distributed lock without fencing stale holders
  • Trusting wall clocks for ordering
  • Claiming exactly-once across arbitrary external side effects

knowledge checks

Start with these quick checks, then explain the closed-book questions in your own words.

  1. 01Why does a lease need a fencing token?

    select an option to check your answer

  2. 02Consensus primarily gives replicas…

    select an option to check your answer

closed-book recall

Close the worked example and explain these from memory. Answers are self-reviewed. Drafts stay on this page; save anything you want to keep in chapter notes.

Rate the assignment and recall together

Use the assignment rubric as evidence. Completion is your own judgment; this score schedules practice.

interview drill

Design exclusive ownership for shard workers when processes can pause for 90 seconds and clocks can skew.

  • worker pauses
  • clock skew
  • no double writes
  • fast reassignment
compare a strong approach after your attempt

Store leases in a consensus-backed coordinator, but attach a monotonically increasing fencing token to every ownership grant. The downstream storage rejects writes with older tokens. Renew well before expiry and design idempotent reassignment. The fencing check—not the lock alone—prevents a paused former owner from writing.

Compare decisions and failure behavior, then repeat with a changed constraint. Keep your own wording.

Use the timed mock workspace →

references

Sources offer deeper context. Provider capabilities and API contracts can change; check current official docs before implementing.

notes

saved locally