blog.spqw.net

Systems design, understood

39 texts for the Systems Design 2.0 course, each written as a cascade: an equation you can hold in your head, one sentence, one paragraph, the explanation, the orders of magnitude to keep, and a field note about an open-source implementation that hit the same wall. Read in order, since every text only assumes the ones above it. 137 minutes of reading in total.

Level 0 · Foundations

  1. The cost of a read is the number of tripsA read costs one trip per distinct block it touches. Bytes inside the block are nearly free.cost(read) ~ distinct blocks visited
  2. A write's cost depends on where its bytes landAn append is one sequential trip; an in-place update costs one trip per page it rewrites, plus a redo record so a crash can finish the job.write = pages touched + redo record

Level 1 · Primitives

  1. What an index isAn index is a redundant copy of your data in a second order, kept true at the cost of every write, so it can only ever move cost from one query to another.copy(order) -> write tax
  2. The commit record is the transactionA commit is durable when its log record reaches stable storage, and separating compute from storage works only because the log is the one artifact that crosses the network.durable(commit) = fsync(WAL record)

Level 2 · One machine, many copies

  1. Isolation protects rows, not invariantsEvery isolation level is a statement about what a reader may see in a row; an invariant spanning several rows, or an absence of rows, is outside that vocabulary, which is why write skew and phantoms survive snapshot isolation.lock(row) x invariant(set) = unsafe
  2. When optimistic concurrency beats pessimistic lockingBlocking is a latency bet and aborting is a throughput bet, so contention picks the winner.abort_cost x conflict_rate >= lock_wait
  3. Serial execution removes the problem class, not the bottleneckRunning one transaction at a time on one core makes serializability free by deleting interleaving, but it converts every microsecond of latency into a system-wide throughput ceiling and pushes the constraint down to the disk.throughput = 1 / transaction_time
  4. Columnar storage: the unit of fetchColumn layout changes the unit of fetch rather than the speed of the disk, so it makes different reads fast.fetch unit -> which queries are cheap
  5. Schema evolution is a reader problemA format is compatible only when every reader can decode bytes it did not write, so evolution is a rule about ignoring unknown fields and defaulting absent ones.compatible = ignore_unknown + default_missing
  6. Replication buys read throughput and charges you in stalenessA replica is a cheaper copy of a write that may not have arrived yet, and the bill comes due as staleness on reads or as latency on writes.committed iff copies >= N/2 + 1
  7. Read-your-writes is a routing decision, not a database settingRead-your-writes is a per-read routing promise: the application sends a user's reads only to replicas that have applied that user's writes, and only the product can say which reads need that guarantee.route(read) = replica where pos >= w
  8. Why the edge exists: CDN distance versus object store restA CDN is a geographically distributed cache that shortens the trip to static bytes, while an object store is the far rung where those bytes rest because nobody needs them quickly.latency = distance x round_trips
  9. What TCP and UDP promise, and what they costOrdered delivery is state you pay to keep, so TCP buys a handshake and per-connection bookkeeping while real-time systems buy loss instead.ordering = handshake + state
  10. Why connection count, not request count, decides the designConcurrency is arrival rate times hold time and every socket is server-side state, so the balancer, the broker and the long-poll choice are all answers to the same arithmetic.connections = rate x hold time
  11. When splitting a monolith pays: resource and failure profiles, not nounsA monolith makes every binary carry every workload, so split only where two features saturate different resources or need different blast radii, and only where the network hop that follows is affordable.split -> gain >= hop_cost

Level 3 · Many machines, one truth

  1. Two writers that never saw each other need a merge rule, not a clockMulti-leader replication makes concurrent writes structural; delivery order is not causal order; last-write-wins silently discards a write. A version vector is what proves two writes were concurrent at all.vv(A) >= vv(B) -> A saw B
  2. What a CRDT assumes, and what it will not give youA CRDT is a merge function with three algebraic properties, not a data type that avoids conflicts; convergence follows from the algebra, and the bill arrives as state size and permanent tombstones.merge(x, y) = merge(y, x)
  3. What a quorum guaranteesQuorums buy overlap, not order. Consensus buys order.R + W > N -> overlap
  4. Why "eventually" has no clockAnti-entropy bounds repair in work, never in wall time, so any latency promise has to be bought on the read path.staleness ~ downtime + handoff + divergence
  5. Why partitions fail before nodes doA partitioning scheme is a plan for moving ranges; no scheme is a plan for one key that everyone wants at once.throughput = max(partition load)
  6. Where a secondary index puts its costA local index makes the write cheap and the read a fan-out; a global index makes the read cheap and the write a distributed transaction.scatter_read = max(shard_i), i in 1..N
  7. Why two-phase commit blocksTwo-phase commit distributes the work but centralises the decision, so the coordinator's death suspends every participant that already voted yes.yes-vote + unknown decision -> blocked
  8. Linearizability is a promise about one client's real-time viewLinearizability is a promise about real time made to one client, and it has to keep holding when that client's next request lands on a different node.write.end < read.start -> read >= write
  9. Why consensus needs a logA vote picks an author and a log fixes what was written and in what order; only where those two majorities overlap does an acknowledged write become unlosable.unlosable >= majority(vote) ∩ majority(log)
  10. Why coordination is a small serviceConsensus costs one leader, one majority round trip and one ordering for every write, so you buy exactly one of those and keep everything that scales out of it.write = leader x majority x order
  11. Spanner buys certainty by paying for it in waitingSpanner does not know what time it is. It measures how wrong its clock might be and delays every commit until no timestamp in that error bar could reorder a causally dependent write.now >= ts + eps -> visible
  12. Why \"SQL vs NoSQL\" is a cost question, not a categoryNormalisation trades locality for truth, and denormalisation pays that bill back at write time.joins(read) + copies(write) ~ constant
  13. What a database's defaults reveal about how it will failDefault isolation, index structure and quorum numbers are the database's real opinions; the feature list is only what it will do if you pay.default = architecture; feature = option
  14. What a cache really cachesA cache stores a past answer and a claim about its freshness, so eviction is a correctness lever, not housekeeping.hit_rate x saved_trips > miss_cost
  15. Invalidation is the staleness tradeNo cache policy keeps the cache and the database in sync; each one picks a stale window, a blast radius, and who pays for the refill.policy -> bet(wrong x window x readers)

Level 4 · Scale out

  1. Why batch processing is a scheduling problem wearing a data-processing costumeThe computation is a few lines of code; placement, failure and re-execution are what actually make a batch system.attempts = tasks + retries
  2. What a shuffle costs, and why you should price a join before you write itA join across machines is a network partition, and its price is the bytes that must be re-sent to make equal keys meet.bytes_crossed = small_side x node_count
  3. Why Spark existsMapReduce materialised at every stage boundary; Spark materialises only at shuffles, where data must cross the network.materialisations ~ wide dependencies, not stages
  4. What a broker decouplesA broker buys you two things and neither is about the message: it collapses the connection mesh into a star, and it lets each side consume at its own rate.N x M -> N + M
  5. Why time is the hard part of streamingAn unbounded input has no end, so an answer requires a boundary you impose, and events do not respect the boundary you chose.watermark >= window_end + allowed_lateness
  6. Why search isn't a B-treeA query arrives as a term, not a value, so the index must be keyed by token and hold the documents that contain it; ordering on the whole string cannot prune a substring match.token -> postings = doc IDs
  7. Why time-series is a compression problemAppend-only, time-ordered ingestion puts similar values next to each other and lets a whole chunk be dropped, while columnar layout decides which bytes you read.order -> similar neighbours -> cheap drop
  8. Why a hop is a pointer and a join is an index lookupIndex-free adjacency removes the index from inside the traversal, not the traversal itself, so the graph model wins on short walks from a known node and loses on whole-graph scans and high-degree nodes.hop ~ 1 pointer dereference
  9. Why nearby is a string problemInterleaving two coordinates into one sortable string turns proximity into a prefix range, but a radius is a disc, so the index only nominates candidates.z = interleave(lat, lon)