Workbench / Volume 1 Companion: Foundations of Computing
V1·11
Mastery Projects
Companion to Volume 1, chapter 11: how the warm-ups and the ten projects connect to the chapters before them; new angles (an apprentice's masterpiece, an annotated chess game as a reference implementation, a building inspector's checklist); what the reference implementations quietly simplify, tested by running them: an allocator that hands out a zero-byte block for a request of 18 exabytes, an HTTP server that grows to 618 MB on one hostile request line, and a key-value store whose compaction and recovery drop durability guarantees; the theory behind the projects (safety and liveness, specification against implementation, quorum arithmetic); how glibc's malloc and Go's net/http guard against the same failures; four debugging drills; interview questions on presenting and defending projects.
Understanding it better
Concept map
Chapter 11 turns the volume into practice: five warm-ups, then ten projects grouped here by where they live. Inside one process: an allocator, a shell, a thread pool and an interpreter. On disk: a key-value store and a file indexer. On the network: an HTTP server, a DNS client, a chat server and a replicated key-value service. Each project draws on several earlier chapters, and the method (hostile tests, measurement, a project log) is the same for all of them.
The links worth remembering:
- Each project is two or three chapters made concrete. The allocator is chapter 3's free lists on chapter 7's memory with chapter 8's
mmap; the key-value store is chapter 3's hash index over chapter 6's checksummed records with chapter 8'sfsync. If a project feels hard, the gap is usually in one of those chapters, which tells you what to reread. - The reference implementations are teaching code, not production code. They show the idea clearly, and each has limits that production code must handle (Gaps 1–3 find three by running them). Learning to see those limits is the senior skill the chapter is building towards.
- The method matters more than the project. A project with hostile-input tests, measurements at two sizes and a log of decisions teaches more, and presents better in an interview, than a bigger project with none.
Explain it differently
1. A project is an apprentice's masterpiece. In the old guilds, an apprentice became a master by producing a "masterpiece": one complete work, judged by masters, that proved they could do the whole job unsupervised. These projects play that role: not exercises in one technique, but whole, small systems where every chapter's ideas meet and interfere. The test isn't "does it run" but "would a master accept it": does it handle bad input, failure and load, and can you defend every decision?
2. A reference implementation is an annotated chess game. A grandmaster's annotated game teaches more than a rule book, but only if you play through it actively: stop at each move, predict the next one, and ask "what if the opponent had played differently?". Copying the moves teaches nothing. Read references the same way: before each function, predict how it will work; after it, ask what input would break it (Gaps 1–3 are three such "what ifs" with answers).
3. Hostile-input testing is a building inspector's checklist. The builder checks that the door opens. The inspector checks what happens when it's slammed a thousand times, when the power fails, when someone leans on the railing. Every project in the chapter has its inspector's list: too-large inputs, malformed inputs, slow inputs, crashes mid-operation, concurrent callers. Chapter Exercises P1–P10 are those lists; the gaps below are items the references themselves would fail.
4. A project log is a pilot's flight log. Pilots write down every flight: conditions, decisions, problems, times. Years later, the log is evidence of experience that no certificate can show. A project log with "tried X, measured Y, chose Z because…" is the same evidence for an engineer, and it's exactly what an interviewer asks for when they say "tell me about a hard technical decision" (Interview prep Q5).
5. Scoping is packing for a trek. Everything you add, you carry the whole way. A project that tries to be a complete database never finishes; one that implements an append-only log with an index, crash recovery and compaction, measured, finishes and teaches all of chapter 8. Decide the "summit" (the one property you'll prove) before you start, and cut everything that doesn't get you there.
6. Production-shaped means the boring parts are done. The interesting part of a key-value store is the log and the index. The production-shaped part is limits, error handling, durability ordering, metrics, configuration, graceful shutdown and documentation. Most real engineering time goes into the second list, and most portfolio projects skip it, which is why doing even some of it stands out.
Gaps and misconceptions
The three gaps below come from running the chapter's own reference implementations with inputs they don't expect.
What the reference implementations simplify
1. The allocator trusts the requested size, and arithmetic on it can wrap. The reference allocator rounds every request up to a multiple of 16 with n = (n + ALIGN - 1) & ~(ALIGN - 1). For a huge request, that addition overflows size_t and wraps to 0. Calling the chapter's my_malloc with a size like one computed from an overflowing count * itemSize (real output):
my_malloc(SIZE_MAX - 3) returned a pointer (!)
the block it handed out holds 0 bytes
the next allocation starts 48 bytes after it
Asked for 18 exabytes, it returned a valid-looking pointer to zero usable bytes, with the next block's header 48 bytes later. A caller writing into "its" memory overwrites other allocations' headers: heap corruption, which in real allocators has been the root of many security exploits. glibc's malloc refuses any request above PTRDIFF_MAX before rounding, and calloc checks n * size for overflow (Code walkthrough). The general lesson, from the Companion to chapter 06: arithmetic on sizes from outside must be checked before it's used.
2. The HTTP server limits header size, but only after reading the whole line. The reference Go server sets maxHeaderBytes = 8 << 10 (8 KB) and reads each line with bufio.Reader.ReadString('\n'). ReadString keeps reading until it finds a newline, however long that takes; the size check runs on the line afterwards. One client sending 300 MB with no newline (real measurement of the server's resident memory):
RSS before: 4.79297 MB
sent 300 MB in one request line, no newline
RSS after: 324.852 MB
RSS 6 s later: 617.98 MB
One connection made the server grow from 5 MB to 618 MB (the buffer roughly doubles as it grows, so memory peaks at about twice the input). A few such connections exhaust a small server's memory, although its 5-second deadline (also in the reference) eventually closes the connection. The limit existed; it was applied at the wrong point. Go's own net/http caps how many bytes the connection reader will return before parsing (Code walkthrough), and the TiffinBox build's stage 9 checks the length of each line as it reads it. A limit must be enforced while reading, not after.
3. The key-value store's crash safety has two holes the text doesn't mention. The chapter rightly explains why compaction fsyncs the new file before renaming it. Tracing its system calls during compaction:
[pid 5559] fsync(6) = 0
[pid 5559] renameat(AT_FDCWD, "orders.log.compact", AT_FDCWD, "orders.log") = 0
after compaction: 34200 bytes (91% smaller), live keys 900, order:999={"state":"v9999"}
There's no fsync of the directory after the rename, so after a power cut the directory may still point at the old file, or (on some filesystems) at neither; the Companion to chapter 08's walkthrough explains why the directory entry needs its own fsync. The second hole is in recovery:
recovery: discarding torn/corrupt tail at offset 17100 (checksum mismatch)
after bit flip at offset 17100: recovered 450 keys (everything before the corruption)
A single flipped bit in the middle of the log made recovery discard everything after it: half the keys, silently, each of which had been written and synced. Treating every bad record as a "torn tail" is right for the last record and wrong for any other; the TiffinBox build's stage 8 distinguishes the two and refuses to start rather than lose acknowledged data. "Recover" must not mean "delete what you can't explain".
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "The reference implementation is the answer." | It's one clear answer to a simplified problem; finding its limits is part of the exercise. | Gaps 1–3 |
| "A size limit in the code means the input is bounded." | Only if it's checked before or while reading, not after. | Gaps 2; drill D2 |
| "fsync before rename makes the swap durable." | The rename itself needs the directory fsynced. | Gaps 3; drill D3 |
| "Recovery that keeps the valid prefix is safe." | Only for a torn tail; mid-log corruption needs a stop, not a truncation. | Gaps 3; drill D3 |
| "A bigger project is a better project." | A finished, tested, measured small project beats an unfinished large one. | Explain it differently 5 |
| "If it passes my tests, it works." | Your tests encode your assumptions; hostile tests encode an attacker's. | Explain it differently 3 |
Theoretical gaps: the ideas behind the projects
1. Safety and liveness: the two kinds of correctness. Every property of a system is (a combination of) a safety property, "nothing bad ever happens" (the allocator never hands out overlapping blocks; the store never returns a value that wasn't written), and a liveness property, "something good eventually happens" (every request gets a reply; a leader is eventually elected). Safety violations have a finite counterexample you can point at; liveness violations only show up as waiting forever. Tests are good at safety; liveness needs timeouts, progress metrics and, in distributed systems, careful reasoning (Raft guarantees safety always and liveness only when the network behaves). Stating both kinds for each project makes its tests sharper.
2. Specification against implementation. A project is easier to build and test when you write down what it must do, separately from how: "get(k) returns the value of the most recent completed put(k, v), or nothing if the last operation on k was delete". That one sentence defines correctness for the key-value store under any implementation, tells you what to test, and makes design changes (an LSM tree instead of a hash index) safe. Stage 5's executable specification table is the same idea for the order lifecycle.
3. Quorum arithmetic. In the replicated key-value service, with N replicas, writes acknowledged by W and reads querying R: if R + W > N, every read quorum overlaps every write quorum in at least one replica, so a read sees the latest acknowledged write (with versions to pick it). N = 3, W = 2, R = 2 tolerates one failure for both reads and writes. Overlap is necessary but not sufficient for linearizability (concurrent writes, read repair and clock-free versioning all matter), which is why Chapter Exercises P10 partitions the cluster and S4 explains linearizability.
4. Amortised cost in the projects. Compaction rewrites the whole log, an O(n) operation, but it runs after O(n) writes, so its cost per write is O(1) amortised (the Companion to chapter 03's theoretical gap 2). The thread pool's queue, the hash index's resizing and the allocator's coalescing are all amortised designs. The catch is the same in each: amortised cost says nothing about the one unlucky request that triggers the O(n) step, so production systems spread the work (incremental compaction, background threads).
5. The end-to-end principle in the projects. The chat server's TCP connection is reliable, yet a message can still be lost (the server crashes after reading it, before broadcasting). The DNS client's UDP has no reliability, so the client retries. The replicated store's replicas acknowledge writes, yet the client must still retry with an idempotency key if the reply is lost. Each project re-learns that only the endpoints can guarantee an operation happened once (the Companion to chapter 09, theoretical gap 2).
6. Deliberate practice. Research on expertise (Ericsson) found that experts improve through practice aimed at specific weaknesses, with immediate feedback, just beyond current ability: not through repetition of what they can already do. The projects work that way only if used that way: choose the project that exercises your weakest chapter, define the "beyond my ability" goal (crash safety, a measured target), and get feedback (tests, measurements, a reviewer). Building the same CRUD app again is repetition, not practice.
Applying it
Code walkthrough
Production code guards against exactly the failures Gaps 1 and 2 found. Two excerpts: glibc's malloc (glibc 2.39, via the GitHub mirror) and Go's net/http (Go 1.24, src/net/http/server.go).
glibc: checking sizes before rounding
static __always_inline size_t
checked_request2size (size_t req) __nonnull (1)
{
if (__glibc_unlikely (req > PTRDIFF_MAX))
return 0;
and in calloc:
if (__glibc_unlikely (__builtin_mul_overflow (n, elem_size, &bytes)))
{
__set_errno (ENOMEM);
return NULL;
}
with the callers treating 0 as failure:
size_t tbytes = checked_request2size (bytes);
if (tbytes == 0)
{
__set_errno (ENOMEM);
return NULL;
}
Read it against Gaps 1:
- Reject before rounding. Any request above
PTRDIFF_MAX(half the address space) is refused before the rounding arithmetic runs, sorequest2sizecan never wrap. A pointer difference must fit inptrdiff_t, so no valid object can be larger anyway. - Multiplication overflow is checked with a compiler builtin.
__builtin_mul_overflow(n, elem_size, &bytes)computes the product and reports whether it overflowed, in one or two instructions. Before such checks,calloc(huge, huge)in several C libraries returned a small block, a well-known class of vulnerability. - Failure is a distinct, documented result:
NULLwitherrno = ENOMEM, never a "valid" pointer to the wrong size.
The reference allocator needs two lines to match: if (n > PTRDIFF_MAX) return NULL; before rounding (drill D1).
Go's net/http: a read limit on the connection itself
const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
func (s *Server) initialReadLimitSize() int64 {
return int64(s.maxHeaderBytes()) + 4096 // bufio slop
}
c.r.setReadLimit(c.server.initialReadLimitSize())
and inside the connection reader that every read goes through:
if cr.hitReadLimit() {
cr.unlock()
return 0, io.EOF
}
...
if int64(len(p)) > cr.remain {
p = p[:cr.remain]
}
Read it against Gaps 2:
- The limit is on the bytes the connection will deliver, not on the parsed result. Before reading a request's head, the server sets a budget of
MaxHeaderBytes + 4096. Every read shrinks the slice it asks for so it can't exceed the remaining budget, and when the budget is gone, the reader reports end-of-file. The header parser above it may useReadString-like functions freely, because no line can ever be longer than the budget. - The default is 1 MB, generous compared with the reference's 8 KB, but bounded. A hostile client can make the server buffer at most about 1 MB per connection, and connection limits multiply that by a known number.
- After the head is parsed, the server switches to the body's own limit (
Content-Length, or aMaxBytesReaderthe handler installs).
The pattern generalises: wrap the input in a reader that enforces the budget, and let the parsing code stay simple. The TiffinBox build's stage 9 used the same idea for time (DeadlineInputStream).
Read it yourself
- Why does glibc compare with
PTRDIFF_MAXrather thanSIZE_MAX? - Go's limit makes the reader return EOF when the budget runs out. What does the client see?
Debugging drills
D1. The allocator that says yes to everything
A program using the reference allocator reads a record count from a file and calls my_malloc(count * sizeof(struct order)). A malicious file with a huge count crashes the program later, in unrelated code. A reproduction:
my_malloc(SIZE_MAX - 3) returned a pointer (!)
the block it handed out holds 0 bytes
the next allocation starts 48 bytes after it
Find both bugs (in the caller and in the allocator), and fix both.
D2. One client makes the server swap
Under a security scan, the reference HTTP server's host started swapping, and other services on it slowed down. The scan opened a few connections and sent long lines with no newline. A reproduction:
RSS before: 4.79297 MB
sent 300 MB in one request line, no newline
RSS after: 324.852 MB
RSS 6 s later: 617.98 MB
The server has maxHeaderBytes = 8 << 10. Explain why it didn't help, and fix the server.
D3. Half the store vanished after a disk error
A user of the reference key-value store reported that after a disk hiccup, a restart "recovered" with half the keys missing, and nothing was logged except one line. A reproduction (one flipped bit at offset 17,100 of a 34,200-byte log):
recovery: discarding torn/corrupt tail at offset 17100 (checksum mismatch)
after bit flip at offset 17100: recovered 450 keys (everything before the corruption)
Explain why this is wrong, and design a recovery that's both safe and honest. Then find the second durability gap in the same store.
D4. "It worked on my machine" for a project demo
You're presenting the chat server project. On your laptop it handles 50 clients. In the interview, the interviewer connects a client that reads nothing, and after a while every other client's messages stop arriving. Chapter Exercises P8 explores slow consumers; this drill is about the demo. What should the project have shown, and how do you answer in the moment?
Career-oriented
Interview prep
Mid level
Q1. "Walk me through a project you built. What was the hardest bug?"
How to get there. Use a structure: the goal in one sentence, the design in three components, one hard bug told as symptom → hypothesis → evidence → fix → what you changed so it can't recur. Use real numbers. Interviewers are checking whether you understand your own system and how you debug.
Q2. You have two weeks to build something that demonstrates backend skills. What do you build, and how do you decide?
How to get there. Show scoping: pick a small system with one hard property, plan the evidence you'll produce, and cut features. The method (Explain it differently 5) is what's being assessed.
Senior level
Q3. Here's a reference implementation of a key-value store (the chapter's). Review it as if it were a pull request for production use.
How to get there. Review in layers, most severe first: correctness and durability, security and limits, concurrency, operability, then style. Name concrete issues with consequences and fixes, and separate blockers from suggestions.
Q4. Your team built an internal tool as a quick project and now three teams depend on it. How do you decide what it needs before it's "production"?
How to get there. Turn "production-ready" into a checklist tied to consequences of failure: who's affected, how badly, how fast you'd know, and how fast you'd recover. Then prioritise by risk.
Staff level
Q5. How would you use projects like these to grow engineers on your team?
How to get there. Design a programme, not a list: match projects to individual gaps, define evidence of growth, build in review and feedback, and connect it to real work. Address time and incentives honestly.
Q6. A candidate presents a distributed key-value store with Raft as their project. How do you, as the interviewer, find out whether they really understand it?
How to get there. Probe reasoning under change rather than recall: failure scenarios, invariants, trade-offs, and their own testing. Distinguish someone who followed a tutorial from someone who could debug the system.