Distributed Systems
What changes when one program becomes many machines that can each fail alone. Learn to reason about lost messages, lying clocks, replicas, shards and consensus, and to build systems that stay correct anyway.
- Advanced
- 4 units, 12 lessons, 148 exercises
- Diagrams, small Python
- Builds on Networking, Databases, Concurrency
Unit 01 · 3 lessons
When machines disagree
Reason about lost messages, lying clocks and safe retries
- 01Partial failure
No reply tells you almost nothing
- 02Clocks lie
Order events without trusting the time
- BOSSThe safe retry
Backoff, jitter and idempotency keys
Read the unit guide
A program on one machine either works or crashes as a whole. A system of many machines can be half broken: one node is down, one is slow, one link drops messages, and the rest carry on. That is partial failure, and the caller usually cannot tell which kind it is facing.
The only failure detector is the timeout, and a timeout is a guess. No reply can mean the request was lost, the server is slow, the server crashed, or the work was done and the reply was lost. Never treat "no reply" as "it did not happen".
Clocks do not rescue you. Every machine's clock drifts, so timestamps from different machines cannot order events. Logical clocks can: a Lamport clock is a counter that ticks on every event and jumps past any number it receives, so a cause is always numbered below its effect. Vector clocks keep one counter per node and can also tell when two events are concurrent.
Because failures are ambiguous, the standard move is to retry, and retries need manners: exponential backoff so a struggling server gets room, jitter so clients do not return in waves, a cap and a limit on attempts, and a circuit breaker that stops calling a service that keeps failing.
A retry may run the work twice, so make twice harmless. An idempotent operation has the same effect once or many times. For everything else, send an idempotency key and have the server remember the keys it has handled. Delivery is at-most-once or at-least-once; "exactly once" always means at-least-once plus deduplication.
The pitfall is writing a network call as if it were a function call. Assume every call can be lost, slow, repeated or answered out of order, and decide in advance what the code does in each case.
Unit 02 · 3 lessons
Copies
Keep the same data on several machines and survive losing one
- 01One leader
Writes to one node, copies on the rest
- 02Quorums
No leader: overlap reads with writes
- BOSSPick two, sort of
What a partition forces you to give up
Read the unit guide
Replication keeps copies of the same data on several machines, so that losing one loses nothing and reads can be spread out. The hard part is writes: every copy has to end up with the same data.
The common design has one leader. All writes go to it, it records them in a log, and followers apply the same log in the same order. Synchronous replication waits for a follower before saying OK: safe, slower, and stuck if that follower is gone. Asynchronous replication says OK first: fast, but a crash can lose writes that were acknowledged.
Followers lag. A user can write, read from a lagging follower and not see their own write, or watch data move backwards between two reads. The fixes are routing rules: read your own writes from the leader, and keep each user on one follower. When the leader dies a follower is promoted (failover). If the old leader was only slow, two leaders can exist at once (split brain).
Leaderless stores use quorums instead. With N replicas, a write needs W confirmations and a read asks R replicas. If W + R > N, every read overlaps the latest write in at least one replica. The store keeps working with N minus the larger of W and R replicas down. Stale replicas are fixed by read repair.
The CAP theorem says that during a network partition a node must either answer with what it has (available, possibly stale) or refuse (consistent, unavailable). With no partition, the daily trade is latency against consistency, which PACELC adds. Consistency itself is a scale, from linearizable (acts like one copy) down to eventual.
The pitfall is "last write wins" on timestamps. It settles conflicts by silently discarding a write, and clock skew can make it discard the newer one.
Unit 03 · 3 lessons
Splitting data
Spread data that is too big for one machine, and move it safely
- 01Shards
Range or hash, and which key to split on
- 02Consistent hashing
Add a node without moving everything
- BOSSAdd a node at 3 a.m
Move shards while serving traffic
Read the unit guide
Replication copies all the data to every machine. When the data or the write load outgrows one machine, it must be split: each machine holds one part, called a shard or partition, and each shard is then replicated.
A rule maps every key to its shard. Range partitioning keeps neighbouring keys together, so range scans are cheap, but a key that only grows, like a timestamp, sends all new writes to one shard. Hash partitioning spreads keys evenly and gives up range scans. Neither helps with one hugely popular key: all of its requests land on one shard.
Pick the partition key for the most frequent query, so that query touches one shard. Anything else becomes scatter-gather: ask every shard and merge. Queries on other columns need secondary indexes, either local (cheap writes, reads ask every shard) or global (reads ask one place, writes update two).
hash % N breaks when N changes: almost every key moves. Consistent hashing places nodes and keys on a ring, and a key belongs to the next node clockwise, so adding a node moves only one arc. Virtual nodes put each machine on the ring many times, which evens out the load. Many stores instead hash into a fixed number of partitions and keep a partition-to-node map, moving whole partitions.
Rebalancing happens while the system serves traffic. Copy the data and forward new writes, flip the map only when the new node has caught up, delete the old copy last, and throttle the copy. Clients and nodes holding an old map must be redirected, which is why maps carry version numbers.
The pitfall is the operation that spans shards. A transfer between two shards has no single machine that can commit or undo both halves. That is the subject of the next unit.
Unit 04 · 3 lessons
Agreeing
Get machines to decide one thing, once, despite failures
- 01Why agreement is hard
Majorities, odd clusters and fencing tokens
- 02Raft, traced
Elections, the log and what committed means
- BOSSOne order, three services
Two-phase commit, sagas and the outbox
Read the unit guide
Many problems reduce to getting machines to agree on one thing: who the leader is, what the next entry in a log is, whether a transaction committed. Consensus algorithms solve this so that no two nodes ever decide differently, and a decision is reached whenever a majority of nodes is up and can talk.
Majorities are the key. Two majorities of the same cluster always share a node, so two leaders cannot both be elected in one term. A cluster of 3 survives one failure and 5 survives two; 4 and 6 add cost without adding tolerance. A leader that was paused may not know it has been replaced, so each election gets a higher term number, and storage rejects requests that carry an older one: a fencing token.
Raft is consensus built around a replicated log. A follower that hears no heartbeat becomes a candidate, raises the term, votes for itself and asks for votes. Each node votes once per term, and never for a candidate whose log is behind its own. The leader appends client commands to its log and sends them to the followers. An entry is committed when a majority has stored it, and only then is the client answered. Committed entries survive every later election; uncommitted ones may be overwritten.
Consensus keeps copies of one dataset in agreement. A transaction across different services is another problem. In two-phase commit a coordinator collects a yes from every participant and then orders the commit. It is atomic, but participants hold locks and are stuck if the coordinator dies after they vote.
A saga avoids the locks: each step commits locally, and a failure triggers compensating actions for the completed steps in reverse order. The outbox pattern makes "save to the database and publish an event" reliable by writing the event in the same local transaction and letting a relay publish it, at least once.
The pitfall is believing a node knows its own status. A paused leader, an expired lock holder and a replaced coordinator all feel healthy from the inside. Put the check where the damage would happen.
Learn Distributed Systems on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.