Distributed SystemsVol. 5 · Part V
0 / 0

Shelves / Distributed Systems

DS·79

Distributed Systems Projects

Eight build-it-yourself projects that turn the tiffin centre's single backend into a small distributed system: an event backbone, an order saga, idempotent payments, a replicated store, coordination with fencing, global rate limiting, a failure-injection harness and a Jepsen-style consistency check, each with milestones, measurable definitions of done and stretch goals.

12 topics · ~7 min read · 5-question quiz
Updated Suggest a correction

How to approach the projects

One system, made distributed one step at a time

The labs in this volume isolate one mechanism each. These projects combine them in one system: the tiffin centre whose frontend, backend and database Volumes 2–4 built, now split into a few services that must keep working when parts of it fail. Run everything locally with Docker Compose (or the binaries the labs used): PostgreSQL, Redis, a broker (Kafka, Redpanda or NATS JetStream), etcd and Toxiproxy between every pair of services, so any link can be slowed or cut on demand.

# Project Main chapters Roughly
1 The event backbone: outbox to broker to consumers 65–68 1 week
2 The order saga with compensations 73, 74 1–2 weeks
3 Idempotent payments API and client 68, 74 1 week
4 A replicated key-value store with tunable quorums 69–71, 75 2 weeks
5 Leader election, leases and fencing 72, 77 1 week
6 Global rate limiting and load shedding 76 1 week
7 A failure-injection harness and resilience patterns 78 1–2 weeks
8 A Jepsen-style consistency checker 69, 72, 75 2 weeks

New to distributed systems? Do them in order; each reuses the previous one's pieces. Experienced? Skim 1–3 and treat the stretch goals of 4–8 as the assignment.

The working method

  1. Write the definition of done first: every project lists checks that can be measured. Copy them into a checklist before writing code.
  2. Reproduce the failure before the fix: a duplicate charge, a lost event, a split brain, an oversell. A test that can't fail proves nothing.
  3. Inject faults deliberately: every check that says "survives X" means you ran X with Toxiproxy, kill -9, iptables or a clock step, and recorded the result.
  4. Count, don't eyeball: invariants are checked by scripts (rows, sums, duplicates, ordering violations), not by looking at logs.
  5. Write a README per project with the design, the alternatives you rejected, and the measurements.

The eight projects

Project 1: the event backbone

Goal. Order placement writes the order and an OrderPlaced event through a transactional outbox; a relay publishes to a broker; three consumers (kitchen display, loyalty points, analytics) process events independently.

Milestones. Outbox table and relay (polling first, then CDC with Debezium if you use Kafka) → topic or stream keyed by order ID with a deliberate partition count → three consumer groups with manual commits after processing → an inbox (dedup) table per consumer → a dead-letter destination with a replay script → consumer lag metrics.

Done when. A script places 10,000 orders while killing the relay and each consumer at random (kill -9, 20 times in total); afterwards every order has exactly one event in each consumer's effects (0 missing, 0 duplicated effects), every order's status events were applied in order, and a poison message lands in the DLQ after 3 attempts without blocking others.

Stretch. Replace polling with Debezium and compare end-to-end latency; add a schema registry with a backward-compatible schema change rolled out while traffic runs; replay six months of events into a new read model.

Project 2: the order saga

Goal. An orchestrated saga for an order: reserve stock, authorise payment, assign a delivery slot, capture payment, with a compensation for each step.

Milestones. Saga state table and orchestrator → idempotent step and compensation handlers in each service → timeouts and retries per step → persisted resume after orchestrator crash → a status API showing each saga's current step → a semantic lock ("pending") for reserved stock.

Done when. 2,000 sagas with 10% declined payments, 5% unavailable delivery slots and the orchestrator killed 30 times all reach a terminal state (CONFIRMED or CANCELLED); stock, payments and slots reconcile exactly (a script proves it); no customer is told "sold out" while stock is only pending.

Stretch. Rebuild it on Temporal (or another durable execution engine) and compare code size and failure behaviour; rewrite as choreography and document what becomes harder to observe.

Project 3: idempotent payments

Goal. A payments API that is safe to retry, and a client that retries correctly.

Milestones. Idempotency-Key support with request fingerprints, stored responses, in-progress conflict handling and 24-hour expiry → per-account key scoping → recovery for keys stuck in progress after a crash → a client SDK with timeouts, exponential backoff with jitter, a retry budget and key reuse across retries → a fake card network with its own idempotency keys.

Done when. With Toxiproxy adding random 0–2 s latency and 5% connection resets, 5,000 payments produce exactly 5,000 charges at the fake card network; concurrent duplicate requests return one 201 and the rest 409 or replays; killing the API mid-request 50 times leaves no stuck keys after the recovery job runs.

Stretch. Publish the API's retry contract (which status codes are retriable, headers, key lifetime) as documentation and test it with a contract test suite.

Project 4: a replicated key-value store

Goal. A small Dynamo-style store over HTTP or gRPC: N replicas as separate processes, consistent hashing, tunable W and R, version vectors, read repair and hinted handoff.

Milestones. Single node with versioned values → replication to N nodes on a hash ring → quorum reads and writes with configurable W and R → version vectors and sibling values for concurrent writes → read repair → hinted handoff → a Merkle-tree anti-entropy job.

Done when. With N = 3, R + W > N gives zero stale reads in 10,000 write-then-read pairs while one replica is down; R = W = 1 shows measurable staleness; concurrent writes from two clients are detected as siblings (never silently lost); after a replica is down for 5 minutes under load, anti-entropy brings it to zero differences.

Stretch. A G-counter and OR-set CRDT type; LWW with hybrid logical clocks and a measurement of lost updates under clock skew; membership changes without downtime.

Project 5: coordination with fencing

Goal. A nightly invoice job that runs on exactly one of three instances, and a storage layer that rejects stale leaders.

Milestones. Leader election on etcd with leases and clean resignation → fencing tokens (the lease key's revision) passed with every write → a fencing_token check in PostgreSQL (UPDATE … WHERE token <= $1) → watch-based configuration for the job's settings → metrics for leadership changes.

Done when. With instances killed, paused (kill -STOP longer than the lease) and partitioned 50 times during runs, the invoice table shows each invoice generated exactly once, every write from a deposed leader was rejected and logged, and failover time stays within TTL + 1 s.

Stretch. Shard ownership: 64 shards spread over instances with leases per shard, rebalanced on membership change; compare with Kubernetes Lease objects.

Project 6: global rate limiting and shedding

Goal. Per-customer API limits enforced across four API instances, plus overload protection.

Milestones. A Redis token bucket in Lua with RateLimit and Retry-After headers → tiers (free, paid, internal) and weighted endpoints → local fallback buckets when Redis is unreachable (decide fail-open or fail-closed, and document why) → an adaptive concurrency limit per instance → priority shedding (checkout before analytics).

Done when. A load test shows each customer within 2% of their limit regardless of how the load balancer spreads them; at 2× capacity, checkout p99 stays under its SLO while low-priority traffic is shed; with Redis killed, the API keeps serving within the fallback limits.

Stretch. A sliding-window counter variant with a measured error rate; limits at the edge (Envoy global rate limit service) compared with in-process limits.

Project 7: a failure-injection harness

Goal. A repeatable harness that runs fault scenarios against the system and checks invariants and SLOs.

Milestones. Toxiproxy between every service pair → scenarios as code (latency, bandwidth, resets, partitions, process kills, clock steps) → timeouts, bulkheads, circuit breakers and fallbacks added where scenarios fail → a report per run: which invariants held, latency and error rates per endpoint, alerts fired.

Done when. At least 12 scenarios run unattended in CI-like fashion; each produces a pass/fail result with evidence; for each initial failure you have a fix and a rerun showing it passing (for example, "slow delivery service no longer takes down checkout: p99 0.4 s, health checks green").

Stretch. Metastable failure reproduction (a retry storm that persists after the trigger), then its fix with retry budgets; hedged requests for a fan-out endpoint with a measured tail improvement.

Project 8: a Jepsen-style consistency checker

Goal. Test a real store's consistency claims under faults: record histories of concurrent operations and check them.

Milestones. A client generator recording invoke/ok/fail/info events with monotonic timestamps → a fault scheduler (partitions with iptables, kills, clock steps) → a linearizability checker for a register (use Porcupine, or write a small Wing–Gong search) → a checker for set and counter workloads → runs against etcd with linearizable and serializable reads, and against a Redis primary/replica pair.

Done when. The checker finds the stale-read anomaly in etcd serializable reads under partition and finds none in linearizable reads over 20 runs; it detects lost writes after a Redis failover; every finding includes the minimal failing history.

Stretch. Elle-style transactional anomaly checking against PostgreSQL at different isolation levels; a TLA+ model of your saga or election protocol checked with TLC.

Tracking your progress

Portfolio checklist

Keep one repository with the services, Compose files, fault scenarios, invariant checkers and a README per project. In distributed systems the evidence is the result of injected failures: "10,000 orders, 20 random kills, 0 missing and 0 duplicated effects; 2,000 sagas, 30 orchestrator crashes, books reconciled exactly; 50 stale-leader writes rejected by fencing; customers within 2% of limits across 4 instances; checker found etcd serializable stale reads in 20/20 partition runs and 0 linearizable violations" is the kind of line that makes a portfolio credible.

Mapping to mastery levels

Completing projects 1–3 with their checks puts you at L2 across the volume. Doing their stretch goals and explaining every anomaly you reproduced is L3–L4. Designing and defending projects 4–8 (replication and conflict strategy, coordination with fencing, platform-wide limits, a resilience harness, consistency verification) is L5 work, the level that staff-level system design interviews and production on-call both test.