Shelves / Foundations of Computing
CS·11
Computer Science Mastery Projects
Ten build-it-yourself projects that turn chapters 2–10 into skill: what each one teaches, a milestone plan, which language to build it in, how to test it, and what to try next.
Start here: five warm-up projects
Warm-up 1: the guessing game (loops, input, validation)
The computer picks a number; you guess; it says higher or lower. Practises a loop that ends on a condition, reading input, and never trusting input (the user might type "fifty").
import random
secret = random.randint(1, 100)
tries = 0
print("I'm thinking of a number from 1 to 100.")
while True:
text = input("Your guess: ")
if not text.strip().isdigit():
print("Please type a whole number."); continue # reject bad input, ask again
guess = int(text); tries += 1
if guess < secret: print("Higher.")
elif guess > secret: print("Lower.")
else:
print(f"Correct! {secret} in {tries} tries."); break
I'm thinking of a number from 1 to 100.
Your guess: fifty
Please type a whole number.
Your guess: 50
Lower.
Your guess: 25
Higher.
Your guess: 37
Lower.
Your guess: 31
Higher.
Your guess: 34
Higher.
Your guess: 36
Lower.
Your guess: 35
Correct! 35 in 7 tries.
The player above used halving (binary search, chapter 4's Start here), and it never takes more than 7 guesses for 100 numbers. Make it yours: let the computer guess your number using halving; count how many guesses it needs for 1 to 1,000,000 (it should be at most 20).
Warm-up 2: word counter (files, strings, dictionaries, errors)
Reads a file named on the command line and reports lines, words, characters and the most common words. Practises command-line arguments, reading files, cleaning strings, counting with a dictionary, and handling a missing file politely, with a non-zero exit code (chapter 1).
import sys
from collections import Counter
path = sys.argv[1]
try:
text = open(path, encoding="utf-8").read()
except FileNotFoundError:
print(f"no such file: {path}", file=sys.stderr); sys.exit(1) # errors to stderr, exit code 1
lines = text.splitlines()
words = [w.strip(".,!?;:\"'()").lower() for w in text.split()]
words = [w for w in words if w]
print(f"{len(lines)} lines, {len(words)} words, {len(text)} characters")
for word, n in Counter(words).most_common(3):
print(f" {word!r}: {n}")
$ python3 wc.py story.txt
3 lines, 12 words, 58 characters
'the': 4
'fox': 2
'quick': 1
$ python3 wc.py nope.txt; echo "exit=$?"
no such file: nope.txt
exit=1
Note that "The" and "the" counted as the same word only because of .lower(), and "fox." matched "fox" only because of .strip(...). Deciding what counts as "the same" is most of the work in real text processing. Make it yours: replace Counter with a plain dictionary you update yourself; then compare your counts with the Unix wc command on the same file (does it count characters the same way? Chapter 6's UTF-8 section explains why it might not).
Warm-up 3: a to-do list that remembers (saving state in a file)
A program forgets everything when it exits, unless it saves to a file. This one stores tasks as JSON (a standard text format for structured data that every language can read) and handles three commands:
import sys, json, os
FILE = "todo.json"
def load():
if not os.path.exists(FILE): return []
with open(FILE) as f: return json.load(f)
def save(items):
with open(FILE, "w") as f: json.dump(items, f, indent=1)
items = load()
cmd = sys.argv[1] if len(sys.argv) > 1 else "list"
if cmd == "add":
items.append({"text": " ".join(sys.argv[2:]), "done": False}); save(items)
elif cmd == "done":
items[int(sys.argv[2]) - 1]["done"] = True; save(items)
elif cmd == "list":
for i, it in enumerate(items, 1):
print(f"{i}. [{'x' if it['done'] else ' '}] {it['text']}")
else:
print("usage: todo.py add TEXT | done N | list", file=sys.stderr); sys.exit(2)
$ python3 todo.py add buy milk
$ python3 todo.py add revise chapter 6
$ python3 todo.py done 1
$ python3 todo.py
1. [x] buy milk
2. [ ] revise chapter 6
$ cat todo.json
[
{
"text": "buy milk",
"done": true
},
{
"text": "revise chapter 6",
"done": false
}
]
Make it yours: python3 todo.py done 9 currently crashes with an IndexError. Make it print a helpful message and exit with code 1. Then think about this: if the computer loses power while save is writing, the file could be half-written and the whole list lost. (The fix, writing to a temporary file and renaming it, is how real databases avoid this; you'll meet it in Project 8.)
Warm-up 4: temperature converter (functions and testing)
Small pure functions are the easiest code to test. This one checks itself with assert statements, which stop the program loudly if a claim is false:
def c_to_f(c): return c * 9 / 5 + 32
def f_to_c(f): return (f - 32) * 5 / 9
for c in (-40, 0, 37, 100):
print(f"{c:>5} °C = {c_to_f(c):6.1f} °F")
assert f_to_c(c_to_f(25)) == 25 # converting there and back gives the original
assert c_to_f(-40) == -40 # the one temperature that's the same on both scales
print("checks passed")
-40 °C = -40.0 °F
0 °C = 32.0 °F
37 °C = 98.6 °F
100 °C = 212.0 °F
checks passed
The tests check known facts (water boils at 212 °F) and properties (there and back gives the original) rather than re-doing the same arithmetic. Make it yours: add a test for f_to_c(c_to_f(0.1)) == 0.1. Does it pass? If not, chapter 6's Start here explains why, and the fix is to compare with a tolerance: abs(a - b) < 1e-9.
Warm-up 5: a calculator in Java (types, exceptions, a second language)
The same kind of program in a statically-typed language. Practises Java's structure (a class with main), switch expressions, and handling every way input can be wrong with exceptions:
import java.util.Scanner;
public class Calc {
static double apply(double a, String op, double b) {
return switch (op) {
case "+" -> a + b;
case "-" -> a - b;
case "*" -> a * b;
case "/" -> {
if (b == 0) throw new ArithmeticException("cannot divide by zero");
yield a / b;
}
default -> throw new IllegalArgumentException("unknown operator: " + op);
};
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNextLine()) {
String line = in.nextLine().trim();
if (line.equals("quit")) break;
String[] p = line.split("\\s+");
if (p.length != 3) { System.out.println("type: number operator number"); continue; }
try {
double r = apply(Double.parseDouble(p[0]), p[1], Double.parseDouble(p[2]));
System.out.println("= " + r);
} catch (NumberFormatException e) {
System.out.println("not a number");
} catch (RuntimeException e) {
System.out.println("error: " + e.getMessage());
}
}
}
}
$ javac Calc.java && java Calc
7 / 2
= 3.5
3 * 4.5
= 13.5
1 / 0
error: cannot divide by zero
ten + 1
not a number
2 ^ 3
error: unknown operator: ^
hello
type: number operator number
quit
Of the six inputs, four were wrong in different ways, and the program survived all of them. Real software spends much of its code on exactly this. (Why does the code check b == 0 itself? Because dividing a Java double by zero doesn't fail: it quietly gives Infinity.) Make it yours: rewrite the calculator in Go or C using the same test inputs; then use chapter 10's Start here parser so it accepts 2 + 3 * 4 with precedence.
When you've finished the warm-ups
You've practised: loops that end on a condition, validating input, files and command-line arguments, exit codes and stderr, saving state, small tested functions, and handling errors in two languages. That's the toolkit the mastery projects assume. Start with Project 1 below when you've also read chapters 2, 3 and 8.
How to approach the projects
Why build these
Reading gets you to mastery levels L1–L3. Building gets you to L4–L5: you have to debug real failures and make design choices. Each project below is small enough to finish in a few focused sessions, yet touches the internals of something you use every day: the allocator under new, the shell, the HTTP server under Spring, the thread pool under ExecutorService, the storage engine under PostgreSQL.
General rules for all ten:
- Start with the smallest version that runs end to end, then deepen it. A shell that runs one command beats a half-finished shell with pipes.
- Write tests first for the tricky parts: parsers, protocol framing, concurrency invariants.
- Measure. Each project has a performance question. Answer it with numbers (
hyperfine,perf, JMH,go test -bench,criterion). - Write a README explaining your design decisions and what you'd do differently. Interviewers and future you both care about the reasoning.
- Build at least two of them in a language you're less comfortable with. Coming from Java, Rust or Go teaches the most, and C or Zig shows you what the runtime was hiding.
Choosing a language per project
| Project | Best for learning | Why |
|---|---|---|
| 1. Memory allocator | C or Zig | You need raw memory, mmap, pointer arithmetic. Zig's Allocator interface makes it pluggable |
| 2. Shell | C, Rust, or Go | fork/exec/pipe/dup2 are clearest in C. Rust's nix crate gives safe wrappers |
| 3. HTTP server | Java (then Rust or Go) | Compare thread-per-request, virtual threads and an event loop yourself |
| 4. Thread pool | Java and Rust | Java to understand ExecutorService; Rust for Send/Sync and ownership of jobs |
| 5. Key-value store | Go or Rust | Concurrency + persistence + networking, without manual memory management |
| 6. File indexer | Rust or Go | Parallel filesystem walks, tries, inverted indexes |
| 7. DNS client | Go, Zig, or C | Binary protocol encoding, UDP, byte order |
| 8. TCP chat server | Go (then Java virtual threads) | Goroutines + channels map naturally onto fan-out messaging |
| 9. Compiler/interpreter | Rust (or Java, Go, Zig) | Enums + pattern matching make ASTs pleasant |
| 10. Distributed KV | Go | Strong RPC and concurrency story, and most Raft teaching material uses it |
The ten projects
Project 1: Memory allocator toy
Goal: implement malloc, free, realloc and calloc on top of mmap (or a big static array), then make them fast and resistant to fragmentation.
Concepts exercised: virtual memory and mmap (ch. 8), alignment and padding (ch. 2, 6), free lists (ch. 3), first-fit vs best-fit, coalescing, size classes, per-thread caches, false sharing (ch. 7).
Milestones
- A bump allocator: one big region and a pointer that only moves forward.
freedoes nothing. That's 15 lines, and it's what arenas and GC nurseries do. - Block headers storing each block's size, and a singly linked free list. Use first-fit allocation and add freed blocks to the list. Return 16-byte aligned pointers.
- Splitting large free blocks and coalescing adjacent free blocks. Boundary tags (footers) let you find the previous block in O(1).
- Segregated size classes (16, 32, 64, … bytes), each with its own free list. Requests above a threshold go straight to
mmap. - Make it thread-safe: first a global lock, then per-thread caches (thread-local free lists), like tcmalloc and jemalloc.
- Measure: throughput and peak RSS compared with the system allocator, on a synthetic workload of mixed sizes. Load it with
LD_PRELOADunder a real program (ls,python) to see whether it survives.
// Milestone 2 core: header + first-fit free list (single-threaded sketch)
typedef struct Block { size_t size; struct Block *next; int free; } Block; // header
static Block *head;
void *my_malloc(size_t n) {
n = (n + 15) & ~(size_t)15; // round up to 16-byte multiples (ch. 6 bit trick)
for (Block *b = head; b; b = b->next)
if (b->free && b->size >= n) { b->free = 0; return b + 1; } // payload follows the header
Block *b = mmap(NULL, sizeof(Block) + n, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); // one mmap per block: slow, simple
if (b == MAP_FAILED) return NULL;
*b = (Block){ .size = n, .next = head, .free = 0 };
head = b;
return b + 1;
}
void my_free(void *p) { if (p) ((Block *)p - 1)->free = 1; }
Testing: random allocate/free sequences checked against a shadow map. Write a canary pattern into every allocation and verify it on free. Run under AddressSanitizer with your allocator disabled, so the harness is checked.
Stretch: implement the Zig std.mem.Allocator interface (alloc, resize, remap, free via a vtable) and plug your allocator into a Zig ArrayList. Or implement Rust's GlobalAlloc and set it with #[global_allocator].
Project 2: Shell
Goal: a Unix shell that runs programs, supports pipes (|), redirection (<, >, >>, 2>&1), background jobs (&), built-ins (cd, exit, export), and Ctrl-C handling.
Concepts exercised: lexing and parsing (ch. 10), fork/exec/wait (ch. 8), file descriptors and dup2, pipes, signals and process groups, environment variables, PATH lookup.
Milestones
- A REPL that reads a line, splits it on whitespace, then fork + execvp + waitpid. Print the exit status.
- Built-ins must run in the shell process. Why must
cdbe a built-in? (A child'schdircan't change the parent's directory.) - A real lexer: quotes (
"a b",'$x'), escapes, and operators as tokens. - Redirection: after
fork, in the child,openthe file anddup2(fd, STDOUT_FILENO). - Pipelines:
pipe()creates a read end and a write end. Fora | b | c, create N−1 pipes, fork each command, wire stdin and stdout withdup2, and close every unused pipe end in every process. Forgetting to close one is the classic bug: the reader never sees EOF and hangs. - Signals: the shell ignores SIGINT, and children restore the default handler. Put each pipeline in its own process group (
setpgid) and hand the terminal to the foreground job (tcsetpgrp), so Ctrl-C reaches the job, not the shell. - Background jobs and a
jobsbuilt-in. Reap finished children with SIGCHLD andwaitpid(-1, …, WNOHANG)so no zombies pile up.
Testing: run scripted sessions and compare output with bash -c. Watch for leaked fds with ls -l /proc/$$/fd. Check zombies with ps.
Stretch: $VAR expansion, $?, globbing (*.rs), &&/||, a history file, tab completion.
Project 3: HTTP server
Goal: an HTTP/1.1 server from raw TCP sockets that serves static files and a small JSON API, then load-test three concurrency models.
Concepts exercised: sockets and the TCP lifecycle (ch. 9), byte-stream framing, parsing, file I/O and sendfile, blocking vs non-blocking I/O and epoll (ch. 8), thread pools vs virtual threads vs event loops.
Milestones
- Accept a connection, read until
\r\n\r\n, parse the request line and headers, and reply withHTTP/1.1 200 OK,Content-Lengthand a body. Test withcurl -v. - Framing done right: requests may arrive split across reads, or two requests may arrive in one read (pipelining). Handle
Content-Lengthbodies and reject oversized headers (a slowloris and memory defence). - Keep-alive: serve several requests per connection, with an idle timeout.
- Static files: map the URL path to a file under a root directory and reject
..traversal (canonicalise, then check the prefix). SetContent-Typeand handleIf-Modified-Sincewith a 304. - Three server versions, same handler:
- (a) a fixed thread pool, one blocking thread per connection;
- (b) Java virtual threads,
Executors.newVirtualThreadPerTaskExecutor(); - (c) a single-threaded epoll/NIO event loop (JavaSelector, or Rust withmio). - Load-test each with
wrkorohaat 100, 1,000 and 10,000 concurrent connections. Record throughput, p99 latency, memory and thread counts. Explain the differences using chapters 8–9.
Testing: an HTTP conformance smoke test (h2spec doesn't apply to 1.1, but curl, ab and malformed requests from a fuzzer do). Fuzz the parser with random bytes: it must never crash.
Stretch: chunked transfer encoding, gzip compression, TLS (via rustls or Java's SSLEngine), graceful shutdown on SIGTERM that drains connections, and an HTTP/2 upgrade.
Project 4: Thread pool
Goal: a fixed-size thread pool with a bounded task queue, futures for results, graceful shutdown, and a configurable rejection policy, then a work-stealing variant.
Concepts exercised: threads (ch. 8), mutexes and condition variables, the bounded-buffer pattern, happens-before, Send/Sync (Rust), deadlock and starvation, false sharing, work stealing with deques (ch. 3).
Milestones
- N worker threads looping on
queue.take()and runningRunnables. Use your own bounded blocking queue (the monitor from ch. 8), notjava.util.concurrent. submit(Callable)returning aFuture: a one-shot result cell thatget()waits on, using a condition variable or a latch. Propagate exceptions to the caller.- Shutdown:
shutdown()stops accepting tasks and drains the queue;shutdownNow()interrupts workers. Make sure no thread leaks and thatawaitTerminationworks. - Back-pressure: when the queue is full, pick a policy: block the caller, reject with an error, or run the task on the caller's thread (
CallerRunsPolicy). - Work stealing: give each worker its own deque. A worker pops from its own end, and idle workers steal from the other end of someone else's deque. Compare with the shared-queue version on many tiny tasks, and on recursive fork/join tasks (parallel merge sort, ch. 4).
- In Rust: the job type is
Box<dyn FnOnce() + Send + 'static>. Explain why each bound is needed. Compare your pool withrayonandstd::thread::scope.
Testing: stress tests with thousands of tasks that each increment an atomic counter, check the total, and run under ThreadSanitizer, go test -race, or jcstress. Add deliberate deadlock scenarios and show your timeouts catch them.
Stretch: dynamic sizing (grow and shrink between core and max threads), metrics (queue depth, active workers), and priorities.
Project 5: Key-value store
Goal: a single-node persistent key-value store with GET, SET and DEL over a network protocol, durable across crashes, and fast.
Concepts exercised: hash maps and LSM trees (ch. 3), write-ahead logging and fsync (ch. 8), serialization and checksums (ch. 6), sockets and protocol framing (ch. 9), concurrency control.
Milestones
- An in-memory
HashMapbehind a text protocol over TCP. Speaking the Redis protocol (RESP) lets you test withredis-cliandredis-benchmark. - Durability with an append-only log: write each mutation to a log file as length + payload + CRC32, then apply it to memory. On startup, replay the log. Decide when to
fsync: every write, every N milliseconds (group commit), or never. Measure each choice. - Crash testing: kill the process with
-9at random moments under load, restart it, and verify no acknowledged write was lost and no torn record was applied (the checksum detects partial writes). - Compaction: the log grows forever. Write a snapshot of the current map, then truncate the log, atomically (write a temp file, fsync, rename, fsync the directory, ch. 8).
- Bitcask design (Riak's storage engine): keep values on disk and only a key → file offset index in memory. Or go further toward an LSM tree: memtable → sorted SSTable files with a sparse index and a Bloom filter → background merge compaction.
- Concurrency: many clients at once. Try a global
RwLock, then sharding the map by key hash into N independently locked shards.
Testing: a linearizability check for single-key operations using a history checker (Porcupine in Go). Fuzz the protocol parser. Run the crash-recovery loop above.
Stretch: TTL expiry, range scans (requires a sorted structure), MULTI/EXEC transactions, replication to a follower (a bridge to project 10).
Project 6: File indexer
Goal: index every text file under a directory tree and answer full-text queries such as rust AND async NOT tokio, plus filename-prefix search, in milliseconds, with incremental updates as files change.
Concepts exercised: filesystem walking, inodes, permissions and symlinks (ch. 8), UTF-8 decoding and normalisation (ch. 6), tries and hash maps (ch. 3), set operations as sorted-list intersection (ch. 5), parallelism, mmap.
Milestones
- Walk the tree recursively. Skip binary files (by NUL bytes or an extension list), respect
.gitignore, and avoid symlink cycles (track device + inode pairs). - Tokenise: lowercase with Unicode case folding, split on non-alphanumerics, optionally stem words.
- Build an inverted index: term → sorted list of (file ID, positions). Answer
ANDby intersecting posting lists (a two-pointer merge, as in merge sort),ORby union, andNOTby difference. - Rank results with TF-IDF or BM25, the scoring Lucene and Elasticsearch use.
- Persist the index in a compact binary format (varint-encoded delta gaps between document IDs, ch. 6), and mmap it at startup.
- Parallelise indexing across cores. Compare a single thread, a thread pool, and Rust
rayonor Goerrgroup. - Incremental updates: watch for changes (inotify via Rust
notify, Gofsnotify, or JavaWatchService) and re-index only the changed files. - A trie or sorted array over file paths for instant prefix and fuzzy filename search, like
fzf.
Testing: compare results against grep -rliw on a fixed corpus. Benchmark indexing and query speed on a large tree, such as the Linux kernel source (~80,000 files).
Stretch: phrase queries using positions, regex search using trigram indexes (how Google Code Search and Zoekt work), and an HTTP API for search.
Project 7: DNS client
Goal: a command-line DNS resolver that builds DNS query packets by hand, sends them over UDP, parses the binary responses, and can resolve iteratively from the root servers like dig +trace.
Concepts exercised: UDP sockets (ch. 9), binary protocol encoding, big-endian byte order (ch. 6), bit fields, DNS records and the delegation hierarchy (ch. 9), timeouts and retries, caching with TTL.
Milestones
- Encode a query: a 12-byte header (ID, flags with RD = 1, QDCOUNT = 1), then the question. The name is encoded as length-prefixed labels (
3www7example3com0), followed by QTYPE (A = 1, AAAA = 28) and QCLASS (IN = 1). All integers are big-endian. - Send it over UDP to
8.8.8.8:53with a timeout and a retry. Match the response ID to the query. - Parse the response: the header, then the question, answer, authority and additional sections. Handle name compression: a two-byte pointer (top bits
11) to an earlier offset in the packet. Guard against pointer loops, a classic security bug in DNS parsers. - Decode A, AAAA, CNAME, MX, NS and TXT records, and print them like
dig. - Iterative resolution: send a query without RD to a root server, follow the NS referrals (using glue A records from the additional section, or resolving the NS names recursively), and continue until you get an answer. Print each hop.
- Truncation: if the TC bit is set, retry over TCP with a 2-byte length prefix.
- A cache keyed by (name, type) that respects TTLs, including negative caching.
Testing: compare your answers with dig for many domains. Feed the parser malformed packets (truncated records, pointer loops, lengths out of range); it must reject them cleanly and never crash or loop forever.
Stretch: EDNS(0) for larger UDP payloads, DNS over HTTPS (RFC 8484), DNSSEC signature validation, or a small caching server that answers other programs.
Project 8: TCP chat server
Goal: a multi-room chat server over TCP with nicknames, rooms, private messages and broadcast, which survives slow or misbehaving clients and thousands of connections.
Concepts exercised: concurrency models (ch. 8), message framing over TCP streams, fan-out broadcast, back-pressure and slow consumers, timeouts and keepalive (ch. 9), graceful shutdown with signals.
Milestones
- A line-based protocol (
/nick,/join,/msg,/quit) over plain TCP, testable withnc. One goroutine (or virtual thread) per client reads lines. - A hub that owns all room state and receives events over a channel: join, leave, message. A single owner means no locks (CSP, ch. 2). Each client has an outbound channel, and a writer goroutine drains it to the socket.
- The slow consumer problem: one client stops reading. Its socket buffer fills, then its outbound channel fills, and broadcasting to it blocks the whole room. Fix it with bounded outbound queues plus a policy: drop the slow client, or drop old messages. Test it by connecting a client that never reads.
- Timeouts and liveness: idle timeouts, application-level ping/pong, and cleanup when the peer disappears (half-open connections).
- Graceful shutdown: on SIGTERM, notify clients, flush their queues and close.
- Reimplement it in Java with virtual threads and a
ConcurrentHashMapof rooms. Compare code size, memory per connection, and behaviour with 10,000 idle clients.
Testing: a load generator that opens thousands of connections and measures broadcast latency. Race detection. Chaos testing: random disconnects, half-written lines, and clients sending megabytes without a newline (enforce a maximum line length).
Stretch: a WebSocket front end so a browser can join, TLS, message history persisted with your project 5 store, and a binary length-prefixed protocol instead of lines.
Project 9: Tiny compiler or interpreter
Goal: a small programming language with variables, arithmetic, if/while, functions and closures. First a tree-walking interpreter, then a bytecode VM, and optionally a compiler to native code or WebAssembly.
Concepts exercised: everything in chapter 10 (lexing, parsing, ASTs, scoping, type checking, IR, codegen), closures and environments (ch. 2), stacks and hash maps (ch. 3), recursion (ch. 4), garbage collection.
Milestones
- A lexer and a recursive-descent / Pratt parser producing an AST, with good error messages (line:column plus a caret under the problem).
- A tree-walking interpreter with environments as a chain of hash maps (lexical scope). Functions are first-class closures that capture their defining environment. Make
fib(25)work and time it. - Variable resolution as a separate pass that records scope distance for each identifier, which fixes closure-capture bugs and speeds up lookups.
- Compile to bytecode for a stack VM (constants,
ADD,JUMP_IF_FALSE,CALL,RETURN,GET_LOCALandGET_UPVALUEfor closures). Write the dispatch loop. Timefib(25)again and compare with the tree walker. - A simple mark-sweep garbage collector for heap objects (strings, closures). Find the roots on the VM stack and in globals. Stress it by forcing a collection on every allocation.
- Optional: a static type checker (simple types plus inference for
let), or compile to WebAssembly text (.wat) or C and run the output natively.
The book Crafting Interpreters (Robert Nystrom, free online) walks through exactly this progression: a tree-walker in Java, then a bytecode VM in C. Doing its second half in Rust or Zig instead of C is a strong learning exercise.
Testing: a suite of example programs with expected output (a golden-file test). Fuzz the parser. Run the GC stress mode.
Stretch: a REPL, a debugger (breakpoints in the VM loop), constant folding and dead-code elimination passes on your IR, and NaN-boxing to pack values into 64 bits.
Project 10: Distributed key-value service
Goal: take project 5 and make it replicated and fault-tolerant. A cluster of 3–5 nodes elects a leader with Raft, replicates a log of commands, and keeps serving correct reads and writes while minority nodes crash or the network partitions.
Concepts exercised: everything above, plus the distributed-systems foundations of roadmap Part V: consensus, terms and leader election, log replication, commit indexes, linearizability, partitions, timeouts, idempotent retries, and snapshotting.
Milestones
- Read the Raft paper (Ongaro & Ousterhout, "In Search of an Understandable Consensus Algorithm", 2014) and watch its visualisation at raft.github.io.
- RPC layer between nodes: Go
net/rpcor gRPC, or Java/Rust gRPC. Add an in-process simulated network that can drop, delay, reorder and partition messages. - Leader election: follower, candidate and leader states, randomised election timeouts,
RequestVote, terms. Test that exactly one leader emerges, and that a new one is elected after the leader is partitioned away. - Log replication:
AppendEntrieswith consistency checks (prevLogIndex and prevLogTerm), back off on mismatch, advance the commit index when a majority has the entry, then apply committed entries to the key-value state machine. - Persistence: the current term, the vote, and the log must be fsynced before replying (ch. 8). Crash and restart nodes randomly under load.
- Client semantics: clients retry on timeout, so give every request a client ID and sequence number, and deduplicate in the state machine. That's exactly-once effect on top of at-least-once delivery. Reads go through the leader with a read index or lease, to be linearizable.
- Snapshots and log compaction:
InstallSnapshotfor followers that fall far behind. - Run a Jepsen-style test: random partitions and crashes, a recorded history of client operations, and a linearizability check (Porcupine).
The MIT 6.5840 (formerly 6.824) Distributed Systems course labs are this project, with a test harness in Go, and they're the best-known way to do it.
Stretch: membership changes (adding and removing nodes), sharding across multiple Raft groups with a configuration service (6.5840 Lab 5), follower reads with leases, and a comparison with etcd's production Raft implementation.
Tracking your progress
Project log template
For each project, keep a short log in your notes or repo, filled in as you go:
Project: ____________ Language(s): ________ Dates: ____ → ____
Milestones done: [ ]1 [ ]2 [ ]3 [ ]4 [ ]5 [ ]6 [ ]7
Hardest bug and how I found it:
Performance question → measured answer (with numbers):
Design decision I'd change next time, and why:
Concepts from chapters 2–10 it made concrete:
What I'd explain in an interview (2-minute version):
Tick a project's Done box in this book when its core milestones work, its tests pass, and you've written the two-minute explanation. Projects 3, 5 and 10 together make a strong portfolio story for a senior backend or platform role: "I built an HTTP server, a durable storage engine, and a Raft-replicated KV service, and here are the benchmarks."
Reference implementations
The projects above are meant to be built by you, from the milestones, before you look at anyone else's code. This section gives a compact, working reference for eight of them (the DNS client is chapter 9's lab and the interpreter is chapter 10's lab), for three uses: checking your design after you've built yours, unblocking yourself when stuck on one milestone, and as a baseline to extend. Each was compiled and run for this book, with sanitizers or race detectors where they apply; the outputs shown are real. They are deliberately small (80–220 lines each): production versions add the "going further" items listed for each project.
Reference: memory allocator (C)
A first-fit allocator over one mmapped 64 MB arena. Each block has a header holding its size, a free flag, its physical neighbours (for coalescing) and, when free, its free-list links. Allocation scans the free list, splits big blocks; freeing coalesces with free neighbours on both sides.
// Project 1 reference: a first-fit allocator with a doubly linked free list, splitting and coalescing.
// Memory comes from one mmap'd arena; every block has a header; free blocks are linked through their payload.
#include <assert.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#define ALIGN 16
#define ARENA (64u << 20) // 64 MB arena
typedef struct Block {
size_t size; // payload size in bytes (multiple of ALIGN)
int free;
struct Block *prev_phys, *next_phys; // neighbours in address order (for coalescing)
struct Block *prev_free, *next_free; // free-list links (valid only when free)
} Block;
#define HDR ((sizeof(Block) + ALIGN - 1) & ~(size_t)(ALIGN - 1))
static Block *free_list, *first;
static size_t used_bytes, peak;
static void list_push(Block *b) { b->prev_free = NULL; b->next_free = free_list; if (free_list) free_list->prev_free = b; free_list = b; }
static void list_remove(Block *b) {
if (b->prev_free) b->prev_free->next_free = b->next_free; else free_list = b->next_free;
if (b->next_free) b->next_free->prev_free = b->prev_free;
}
static void init(void) {
char *mem = mmap(NULL, ARENA, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
assert(mem != MAP_FAILED);
first = (Block *)mem; *first = (Block){ .size = ARENA - HDR, .free = 1 };
list_push(first);
}
void *my_malloc(size_t n) {
if (!first) init();
if (n == 0) n = 1;
n = (n + ALIGN - 1) & ~(size_t)(ALIGN - 1);
for (Block *b = free_list; b; b = b->next_free) { // first fit
if (b->size < n) continue;
list_remove(b);
if (b->size >= n + HDR + ALIGN) { // split: the remainder becomes a new free block
Block *rest = (Block *)((char *)b + HDR + n);
*rest = (Block){ .size = b->size - n - HDR, .free = 1, .prev_phys = b, .next_phys = b->next_phys };
if (b->next_phys) b->next_phys->prev_phys = rest;
b->next_phys = rest; b->size = n;
list_push(rest);
}
b->free = 0; used_bytes += b->size; if (used_bytes > peak) peak = used_bytes;
return (char *)b + HDR;
}
return NULL; // out of memory
}
static Block *merge(Block *a, Block *b) { // absorb b (physically after a) into a
a->size += HDR + b->size; a->next_phys = b->next_phys;
if (b->next_phys) b->next_phys->prev_phys = a;
return a;
}
void my_free(void *p) {
if (!p) return;
Block *b = (Block *)((char *)p - HDR);
assert(!b->free && "double free");
b->free = 1; used_bytes -= b->size;
if (b->next_phys && b->next_phys->free) { list_remove(b->next_phys); merge(b, b->next_phys); } // coalesce right
if (b->prev_phys && b->prev_phys->free) { list_remove(b->prev_phys); b = merge(b->prev_phys, b); } // coalesce left
list_push(b);
}
static void stats(const char *when) {
size_t nfree = 0, largest = 0, total_free = 0;
for (Block *b = free_list; b; b = b->next_free) { nfree++; total_free += b->size; if (b->size > largest) largest = b->size; }
printf("%-26s free blocks %6zu, free bytes %9zu, largest free %9zu, external fragmentation %5.1f%%\n",
when, nfree, total_free, largest, total_free ? 100.0 * (1 - (double)largest / total_free) : 0.0);
}
int main(void) {
enum { N = 200000 };
static void *ptrs[N]; static size_t sizes[N];
srand(7);
for (int i = 0; i < N; i++) { // allocate with a mix of sizes, fill with a pattern
sizes[i] = 8 + rand() % 512;
ptrs[i] = my_malloc(sizes[i]); assert(ptrs[i]);
memset(ptrs[i], i & 0xFF, sizes[i]);
}
stats("after 200k allocations:");
for (int i = 0; i < N; i += 2) { my_free(ptrs[i]); ptrs[i] = NULL; } // free every other block
stats("after freeing every other:");
for (int i = 1; i < N; i += 2) // verify the survivors weren't corrupted
for (size_t k = 0; k < sizes[i]; k++) assert(((unsigned char *)ptrs[i])[k] == (i & 0xFF));
void *big = my_malloc(1 << 20);
printf("1 MB request with fragmented heap: %s\n", big ? "served from the untouched tail" : "FAILED");
my_free(big);
for (int i = 1; i < N; i += 2) my_free(ptrs[i]);
stats("after freeing everything:");
printf("peak payload in use: %.1f MB; header overhead per block: %zu bytes\n", peak / 1048576.0, HDR);
return 0;
}
after 200k allocations: free blocks 1, free bytes 3336288, largest free 3336288, external fragmentation 0.0%
after freeing every other: free blocks 100001, free bytes 30439440, largest free 3336288, external fragmentation 89.0%
1 MB request with fragmented heap: served from the untouched tail
after freeing everything: free blocks 1, free bytes 67108816, largest free 67108816, external fragmentation 0.0%
peak payload in use: 51.7 MB; header overhead per block: 48 bytes
What the run shows. Freeing every other block leaves 100,001 free blocks holding 30 MB, but the largest is only 3.3 MB (the untouched tail): 89% external fragmentation. A 1 MB request still succeeds only because of that tail; in a long-running process with no tail left, it would fail despite 30 MB being free. Freeing the rest coalesces everything back into one block. The same program also ran clean under AddressSanitizer and UndefinedBehaviorSanitizer (-fsanitize=address,undefined), and the survivors' fill pattern was verified, so splitting and coalescing never corrupted live data.
The 48-byte header is large (two pairs of pointers plus size and flag). Real allocators shrink it: boundary tags store the size at both ends so physical neighbours can be found without pointers; size classes (slab/segregated free lists: glibc's bins, jemalloc, mimalloc) make allocation O(1) and fragmentation predictable; per-thread caches avoid lock contention. Break it: free a pointer twice (the assert catches it; remove the assert and watch the free list corrupt), or write one byte past an allocation and see what ASan reports.
Reference: shell (C)
Pipelines of any length, <, >, >>, cd and exit built-ins, background jobs with &, zombie reaping, and correct Ctrl-C behaviour.
// Project 2 reference: a small Unix shell. Pipelines (a | b | c), redirection (< > >>), built-ins (cd, exit),
// background jobs (&), and correct handling of Ctrl-C (the shell ignores SIGINT; children get the default).
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#define MAXARGS 64
#define MAXCMDS 16
typedef struct { char *argv[MAXARGS]; char *in, *out; int append; } Cmd;
static int parse(char *line, Cmd *cmds, int *bg) { // split on spaces; '|' separates commands
int n = 0; Cmd *c = &cmds[0]; memset(cmds, 0, sizeof(Cmd) * MAXCMDS);
int argc = 0; *bg = 0;
for (char *tok = strtok(line, " \t\n"); tok; tok = strtok(NULL, " \t\n")) {
if (!strcmp(tok, "|")) { c->argv[argc] = NULL; if (++n >= MAXCMDS) return -1; c = &cmds[n]; argc = 0; }
else if (!strcmp(tok, "<")) c->in = strtok(NULL, " \t\n");
else if (!strcmp(tok, ">")) { c->out = strtok(NULL, " \t\n"); c->append = 0; }
else if (!strcmp(tok, ">>")) { c->out = strtok(NULL, " \t\n"); c->append = 1; }
else if (!strcmp(tok, "&")) *bg = 1;
else if (argc < MAXARGS - 1) c->argv[argc++] = tok;
}
c->argv[argc] = NULL;
return argc || n ? n + 1 : 0;
}
static int builtin(Cmd *c) {
if (!c->argv[0]) return 1;
if (!strcmp(c->argv[0], "exit")) exit(c->argv[1] ? atoi(c->argv[1]) : 0);
if (!strcmp(c->argv[0], "cd")) {
const char *dir = c->argv[1] ? c->argv[1] : getenv("HOME");
if (chdir(dir) < 0) fprintf(stderr, "cd: %s: %s\n", dir, strerror(errno));
return 1;
}
return 0;
}
static int run(Cmd *cmds, int n, int bg) {
if (n == 1 && builtin(&cmds[0])) return 0; // built-ins must run in the shell process itself
int prev_read = -1; pid_t pids[MAXCMDS];
for (int i = 0; i < n; i++) {
int fd[2] = {-1, -1};
if (i < n - 1 && pipe(fd) < 0) { perror("pipe"); return 1; }
pid_t pid = fork();
if (pid == 0) {
signal(SIGINT, SIG_DFL); // children react to Ctrl-C; the shell doesn't
if (prev_read != -1) { dup2(prev_read, STDIN_FILENO); close(prev_read); }
if (fd[1] != -1) { dup2(fd[1], STDOUT_FILENO); close(fd[1]); close(fd[0]); }
if (cmds[i].in) { int f = open(cmds[i].in, O_RDONLY); if (f < 0) { perror(cmds[i].in); _exit(1); } dup2(f, 0); close(f); }
if (cmds[i].out) {
int f = open(cmds[i].out, O_WRONLY | O_CREAT | (cmds[i].append ? O_APPEND : O_TRUNC), 0644);
if (f < 0) { perror(cmds[i].out); _exit(1); } dup2(f, 1); close(f);
}
execvp(cmds[i].argv[0], cmds[i].argv);
fprintf(stderr, "%s: command not found\n", cmds[i].argv[0]); _exit(127);
}
pids[i] = pid;
if (prev_read != -1) close(prev_read); // parent must close its copies, or readers never see EOF
if (fd[1] != -1) close(fd[1]);
prev_read = fd[0];
}
if (bg) { printf("[bg] %d\n", pids[n - 1]); return 0; }
int status = 0;
for (int i = 0; i < n; i++) waitpid(pids[i], &status, 0);
return WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
}
int main(void) {
signal(SIGINT, SIG_IGN);
char line[4096]; Cmd cmds[MAXCMDS]; int bg, last = 0;
for (;;) {
while (waitpid(-1, NULL, WNOHANG) > 0) {} // reap finished background jobs (no zombies)
if (isatty(0)) { printf("tsh$ "); fflush(stdout); }
if (!fgets(line, sizeof line, stdin)) break;
int n = parse(line, cmds, &bg);
if (n > 0) last = run(cmds, n, bg);
else if (n < 0) fprintf(stderr, "too many pipeline stages\n");
}
return last;
}
$ cat script.txt
echo hello from tsh
printf banana\napple\ncherry\napple\n > fruits.txt
sort < fruits.txt | uniq -c | sort -rn
echo appended >> fruits.txt
wc -l < fruits.txt
cd /tmp
pwd
ls /nonexistent
nosuchcmd
cat /tmp/P/sandbox/fruits.txt | grep a | tr a-z A-Z | head -2
sleep 0.2 &
exit 3
$ ./tsh < script.txt; echo "exit status: $?"
hello from tsh
2 apple
1 cherry
1 banana
5
/tmp
ls: cannot access '/nonexistent': No such file or directory
nosuchcmd: command not found
BANANA
APPLE
[bg] 18932
exit status: 3
The subtle parts, each a classic bug if missed:
cdandexitmust run in the shell process: a child thatchdirs changes only its own working directory and then exits.- The parent closes its copies of every pipe end after forking. If it keeps a write end open, the last command in a pipeline never sees end-of-file and hangs forever.
- The shell ignores SIGINT, and children restore the default before
exec, so Ctrl-C kills the running command, not your shell. - Background jobs are reaped with
waitpid(-1, …, WNOHANG)before each prompt, or they remain zombies (chapter 8). execfailure is reported in the child with exit status 127, the shell convention for "command not found".
Not implemented (the next milestones): quoting and escapes ("hello world" is two words here, which is why the script avoids quotes), variables and $?, globbing, job control with process groups (fg, bg, Ctrl-Z), and &&/||.
Reference: HTTP/1.1 server on raw TCP (Go)
No net/http: the server reads bytes from TCP connections, parses request lines and headers, honours Content-Length, supports keep-alive, serves static files safely, and shuts down gracefully on SIGTERM.
// Project 3 reference: an HTTP/1.1 server on raw TCP (no net/http): request parsing, keep-alive,
// Content-Length bodies, static files with path-traversal protection, timeouts, and graceful shutdown.
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log"
"mime"
"net"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
const maxHeaderBytes, maxBody = 8 << 10, 1 << 20
type request struct {
method, target, proto string
headers map[string]string
body []byte
}
var errBadRequest = errors.New("bad request")
func readRequest(r *bufio.Reader) (*request, error) {
line, err := r.ReadString('\n')
if err != nil {
return nil, err // io.EOF: client closed an idle keep-alive connection
}
parts := strings.Fields(line)
if len(parts) != 3 || !strings.HasPrefix(parts[2], "HTTP/1.") {
return nil, errBadRequest
}
req := &request{method: parts[0], target: parts[1], proto: parts[2], headers: map[string]string{}}
total := len(line)
for {
h, err := r.ReadString('\n')
if err != nil {
return nil, err
}
if total += len(h); total > maxHeaderBytes {
return nil, errBadRequest
}
h = strings.TrimRight(h, "\r\n")
if h == "" {
break // blank line ends the headers
}
k, v, ok := strings.Cut(h, ":")
if !ok {
return nil, errBadRequest
}
req.headers[strings.ToLower(strings.TrimSpace(k))] = strings.TrimSpace(v)
}
if cl := req.headers["content-length"]; cl != "" {
n, err := strconv.Atoi(cl)
if err != nil || n < 0 || n > maxBody {
return nil, errBadRequest
}
req.body = make([]byte, n)
if _, err := io.ReadFull(r, req.body); err != nil {
return nil, err
}
}
return req, nil
}
func respond(w *bufio.Writer, status int, reason, ctype string, body []byte, keepAlive bool) {
conn := "close"
if keepAlive {
conn = "keep-alive"
}
fmt.Fprintf(w, "HTTP/1.1 %d %s\r\nContent-Type: %s\r\nContent-Length: %d\r\nConnection: %s\r\nDate: %s\r\n\r\n",
status, reason, ctype, len(body), conn, time.Now().UTC().Format(time.RFC1123))
w.Write(body)
w.Flush()
}
func handle(req *request, root string) (int, string, string, []byte) {
switch {
case req.method == "POST" && req.target == "/echo":
return 200, "OK", "text/plain", req.body
case req.method != "GET" && req.method != "HEAD":
return 405, "Method Not Allowed", "text/plain", []byte("method not allowed\n")
}
clean := filepath.Clean("/" + strings.SplitN(req.target, "?", 2)[0]) // resolves ../ against the root
path := filepath.Join(root, clean)
if !strings.HasPrefix(path, root+string(os.PathSeparator)) && path != root {
return 403, "Forbidden", "text/plain", []byte("forbidden\n")
}
if fi, err := os.Stat(path); err == nil && fi.IsDir() {
path = filepath.Join(path, "index.html")
}
data, err := os.ReadFile(path)
if err != nil {
return 404, "Not Found", "text/plain", []byte("not found\n")
}
ctype := mime.TypeByExtension(filepath.Ext(path))
if ctype == "" {
ctype = "application/octet-stream"
}
return 200, "OK", ctype, data
}
func serveConn(c net.Conn, root string, wg *sync.WaitGroup, shutting *bool, mu *sync.Mutex) {
defer wg.Done()
defer c.Close()
r, w := bufio.NewReader(c), bufio.NewWriter(c)
for {
c.SetReadDeadline(time.Now().Add(5 * time.Second)) // idle/slowloris protection
req, err := readRequest(r)
if err != nil {
if errors.Is(err, errBadRequest) {
respond(w, 400, "Bad Request", "text/plain", []byte("bad request\n"), false)
}
return
}
mu.Lock()
closing := *shutting
mu.Unlock()
keep := !closing && req.headers["connection"] != "close" && req.proto == "HTTP/1.1"
status, reason, ctype, body := handle(req, root)
if req.method == "HEAD" {
respond(w, status, reason, ctype, nil, keep)
} else {
respond(w, status, reason, ctype, body, keep)
}
log.Printf("%s %s %d %dB keep-alive=%v", req.method, req.target, status, len(body), keep)
if !keep {
return
}
}
}
func main() {
root, _ := filepath.Abs("www")
ln, err := net.Listen("tcp", "127.0.0.1:18080")
if err != nil {
log.Fatal(err)
}
var wg sync.WaitGroup
var mu sync.Mutex
shutting := false
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
go func() {
<-ctx.Done()
mu.Lock()
shutting = true
mu.Unlock()
ln.Close() // stop accepting; in-flight connections finish their current request
}()
log.Printf("listening on %s, serving %s", ln.Addr(), root)
for {
c, err := ln.Accept()
if err != nil {
break
}
wg.Add(1)
go serveConn(c, root, &wg, &shutting, &mu)
}
wg.Wait()
log.Print("shut down cleanly")
}
$ curl -s -i http://127.0.0.1:18080/ | head -4
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 19
Connection: keep-alive
$ curl -s http://127.0.0.1:18080/menu/today.json
{"today":"biryani"}
$ curl --path-as-is -s -o /dev/null -w "traversal attempt: %{http_code}\n" http://127.0.0.1:18080/../secret.txt
traversal attempt: 404
$ curl -s -o /dev/null -w "missing: %{http_code}\n" http://127.0.0.1:18080/nope
missing: 404
$ curl -s -o /dev/null -w "DELETE: %{http_code}\n" -X DELETE http://127.0.0.1:18080/
DELETE: 405
$ curl -s -d 'skip friday' http://127.0.0.1:18080/echo
skip friday
$ curl -s -o /dev/null -o /dev/null -w "%{num_connects} new connection(s)\n" http://127.0.0.1:18080/ http://127.0.0.1:18080/menu/today.json
1 new connection(s)
0 new connection(s) ← the second request reused the kept-alive connection
$ printf 'NONSENSE\r\n\r\n' | nc -q1 127.0.0.1 18080 | head -1
HTTP/1.1 400 Bad Request
$ kill -TERM <pid> # server log ends with:
2026/10/26 12:41:40 shut down cleanly
Security and robustness details worth copying: filepath.Clean("/" + path) resolves .. against a root of / before joining, so /../secret.txt becomes /secret.txt inside the web root (a 404 rather than the file outside it), and a prefix check rejects anything that still escapes; a read deadline per request stops slow-loris clients from holding connections forever; header size and body size are capped; bad request lines get a 400 and the connection is closed. Next milestones: chunked transfer encoding, Range requests, conditional requests (If-None-Match/ETag), TLS, and HTTP pipelining edge cases. Then compare your parser with net/http's, which handles many more edge cases (and has had CVEs in exactly those).
Reference: thread pool (C++20)
Fixed workers, a bounded queue that blocks submitters when full (backpressure), futures carrying results or exceptions back to the caller, and a shutdown that drains queued work.
// Project 4 reference: a fixed-size thread pool with a bounded queue (backpressure), futures for results,
// exception propagation, and graceful shutdown that drains queued work.
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstdio>
#include <deque>
#include <functional>
#include <future>
#include <mutex>
#include <stdexcept>
#include <thread>
#include <vector>
class ThreadPool {
public:
ThreadPool(size_t threads, size_t capacity) : capacity_(capacity) {
for (size_t i = 0; i < threads; ++i) workers_.emplace_back([this] { loop(); });
}
~ThreadPool() { shutdown(); }
template <class F>
auto submit(F f) -> std::future<decltype(f())> { // blocks while the queue is full: backpressure
using R = decltype(f());
auto task = std::make_shared<std::packaged_task<R()>>(std::move(f));
std::future<R> fut = task->get_future();
{
std::unique_lock lk(m_);
not_full_.wait(lk, [this] { return q_.size() < capacity_ || stopping_; });
if (stopping_) throw std::runtime_error("pool is shutting down");
q_.emplace_back([task] { (*task)(); }); // packaged_task stores the result or the exception
}
not_empty_.notify_one();
return fut;
}
void shutdown() { // finish queued tasks, then join
{
std::lock_guard lk(m_);
if (stopping_) return;
stopping_ = true;
}
not_empty_.notify_all(); not_full_.notify_all();
for (auto& t : workers_) t.join();
}
size_t max_queue_seen() const { return max_seen_; }
private:
void loop() {
for (;;) {
std::function<void()> job;
{
std::unique_lock lk(m_);
not_empty_.wait(lk, [this] { return !q_.empty() || stopping_; }); // predicate guards spurious wakeups
if (q_.empty()) return; // stopping and drained
job = std::move(q_.front()); q_.pop_front();
max_seen_ = std::max(max_seen_, q_.size() + 1);
}
not_full_.notify_one();
job(); // run outside the lock
}
}
std::vector<std::thread> workers_;
std::deque<std::function<void()>> q_;
std::mutex m_;
std::condition_variable not_empty_, not_full_;
size_t capacity_, max_seen_ = 0;
bool stopping_ = false;
};
int main() {
using namespace std::chrono;
ThreadPool pool(4, 8);
std::atomic<int> running{0}, peak{0};
auto t0 = steady_clock::now();
std::vector<std::future<int>> results;
for (int i = 0; i < 32; ++i)
results.push_back(pool.submit([i, &running, &peak] {
int now = ++running; int p = peak.load();
while (now > p && !peak.compare_exchange_weak(p, now)) {}
std::this_thread::sleep_for(milliseconds(20)); // simulated I/O-bound work
--running;
if (i == 13) throw std::invalid_argument("task 13 failed");
return i * i;
}));
long sum = 0; int failures = 0;
for (auto& f : results) {
try { sum += f.get(); } catch (const std::exception& e) { ++failures; std::printf("caught from worker: %s\n", e.what()); }
}
auto ms = duration_cast<milliseconds>(steady_clock::now() - t0).count();
std::printf("32 tasks x 20 ms on 4 threads: %lld ms (ideal 160), sum=%ld, failures=%d, peak concurrency=%d, max queued=%zu (cap 8)\n",
(long long)ms, sum, failures, peak.load(), pool.max_queue_seen());
pool.shutdown();
try { pool.submit([] { return 0; }); } catch (const std::exception& e) { std::printf("submit after shutdown: %s\n", e.what()); }
}
caught from worker: task 13 failed
32 tasks x 20 ms on 4 threads: 161 ms (ideal 160), sum=10247, failures=1, peak concurrency=4, max queued=8 (cap 8)
submit after shutdown: pool is shutting down
32 tasks of 20 ms on 4 threads finished in 162 ms against an ideal 160: the pool keeps all four workers busy. The queue never held more than its capacity of 8, so the submitting thread was blocked while workers caught up: that's backpressure, and without it a fast producer can queue unbounded work and exhaust memory. Task 13's exception travelled through the packaged_task into the future and was rethrown at get(), instead of terminating the program (an exception escaping a std::thread calls std::terminate). The build was also run under ThreadSanitizer (-fsanitize=thread) with no reports. Things to notice in the code: condition-variable waits use a predicate (spurious wakeups and missed notifications are handled), jobs run outside the lock, and shutdown wakes everyone. Compare with Java's ThreadPoolExecutor (core/max sizes, rejection policies such as CallerRunsPolicy, which is another form of backpressure) and with work-stealing pools (ForkJoinPool, Rust's rayon, Go's scheduler).
Reference: key-value store (Go)
A Bitcask-style store: an append-only log of checksummed records, an in-memory hash index from key to the offset of its latest record, crash recovery that stops at the first torn or corrupt record, and compaction that rewrites live records into a new file and renames it into place atomically.
// Project 5 reference: a Bitcask-style key-value store. Every write appends a checksummed record to a log;
// an in-memory hash index maps each key to its latest record's offset; recovery replays the log and stops at
// the first torn or corrupt record; compaction rewrites only live records and swaps files atomically.
package main
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"hash/crc32"
"io"
"os"
)
// record: crc32(4) | keyLen(4) | valLen(4, 0xFFFFFFFF = tombstone) | key | value
const hdr = 12
const tombstone = ^uint32(0)
type Store struct {
f *os.File
path string
index map[string]int64 // key → offset of its latest record
size int64
}
func Open(path string) (*Store, error) {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0o644)
if err != nil {
return nil, err
}
s := &Store{f: f, path: path, index: map[string]int64{}}
return s, s.recover()
}
func (s *Store) recover() error {
r := bufio.NewReader(s.f)
var off int64
for {
key, _, deleted, n, err := readRecord(r)
if err != nil {
if !errors.Is(err, io.EOF) {
fmt.Printf(" recovery: discarding torn/corrupt tail at offset %d (%v)\n", off, err)
}
break
}
if deleted {
delete(s.index, key)
} else {
s.index[key] = off
}
off += n
}
s.size = off
return s.f.Truncate(off) // drop any partial record so new appends start on a clean boundary
}
func readRecord(r io.Reader) (key string, val []byte, deleted bool, n int64, err error) {
h := make([]byte, hdr)
if _, err = io.ReadFull(r, h); err != nil {
if errors.Is(err, io.ErrUnexpectedEOF) {
err = errors.New("short header")
}
return
}
crc, kl, vl := binary.LittleEndian.Uint32(h), binary.LittleEndian.Uint32(h[4:]), binary.LittleEndian.Uint32(h[8:])
if kl > 1<<16 || (vl != tombstone && vl > 1<<24) {
err = errors.New("implausible lengths")
return
}
body := int(kl)
if vl != tombstone {
body += int(vl)
}
b := make([]byte, body)
if _, err = io.ReadFull(r, b); err != nil {
err = errors.New("short body")
return
}
if crc32.ChecksumIEEE(append(h[4:], b...)) != crc {
err = errors.New("checksum mismatch")
return
}
return string(b[:kl]), b[kl:], vl == tombstone, int64(hdr + body), nil
}
func encode(key string, val []byte, del bool) []byte {
vl := uint32(len(val))
if del {
vl, val = tombstone, nil
}
rec := make([]byte, hdr+len(key)+len(val))
binary.LittleEndian.PutUint32(rec[4:], uint32(len(key)))
binary.LittleEndian.PutUint32(rec[8:], vl)
copy(rec[hdr:], key)
copy(rec[hdr+len(key):], val)
binary.LittleEndian.PutUint32(rec, crc32.ChecksumIEEE(rec[4:]))
return rec
}
func (s *Store) append(rec []byte) (int64, error) {
off := s.size
if _, err := s.f.WriteAt(rec, off); err != nil {
return 0, err
}
s.size += int64(len(rec))
return off, nil
}
func (s *Store) Put(key string, val []byte) error {
off, err := s.append(encode(key, val, false))
if err == nil {
s.index[key] = off
}
return err
}
func (s *Store) Delete(key string) error {
_, err := s.append(encode(key, nil, true))
delete(s.index, key)
return err
}
func (s *Store) Get(key string) ([]byte, bool) {
off, ok := s.index[key]
if !ok {
return nil, false
}
_, val, _, _, err := readRecord(io.NewSectionReader(s.f, off, s.size-off)) // one seek + read per lookup
return val, err == nil
}
func (s *Store) Sync() error { return s.f.Sync() } // durability point: fsync
func (s *Store) Compact() error {
tmp := s.path + ".compact"
out, err := os.Create(tmp)
if err != nil {
return err
}
newIndex, off := map[string]int64{}, int64(0)
for k := range s.index {
v, _ := s.Get(k)
rec := encode(k, v, false)
if _, err := out.Write(rec); err != nil {
return err
}
newIndex[k] = off
off += int64(len(rec))
}
if err := out.Sync(); err != nil { // data durable before the swap
return err
}
out.Close()
if err := os.Rename(tmp, s.path); err != nil { // atomic replace on POSIX filesystems
return err
}
s.f.Close()
s.f, _ = os.OpenFile(s.path, os.O_RDWR, 0o644)
s.index, s.size = newIndex, off
return nil
}
func main() {
path := "orders.log"
os.Remove(path)
s, _ := Open(path)
for i := 0; i < 10000; i++ { // 10k updates over 1,000 keys: lots of overwritten history
s.Put(fmt.Sprintf("order:%d", i%1000), []byte(fmt.Sprintf(`{"state":"v%d"}`, i)))
}
for i := 0; i < 100; i++ {
s.Delete(fmt.Sprintf("order:%d", i))
}
s.Sync()
v, _ := s.Get("order:999")
_, gone := s.Get("order:5")
fmt.Printf("log size %d bytes, live keys %d, order:999=%s, order:5 present=%v\n", s.size, len(s.index), v, gone)
// crash simulation: a write torn half-way (power loss mid-append)
rec := encode("order:999", []byte(`{"state":"torn"}`), false)
s.f.WriteAt(rec[:len(rec)/2], s.size)
s.f.Close()
s, _ = Open(path)
v, _ = s.Get("order:999")
fmt.Printf("after reopen: live keys %d, order:999=%s (the torn write was discarded)\n", len(s.index), v)
data, _ := os.ReadFile(path)
fmt.Printf("before compaction: %d bytes\n", len(data))
s.Compact()
fi, _ := os.Stat(path)
v, _ = s.Get("order:999")
fmt.Printf("after compaction: %d bytes (%.0f%% smaller), live keys %d, order:999=%s\n",
fi.Size(), 100*(1-float64(fi.Size())/float64(len(data))), len(s.index), v)
data, _ = os.ReadFile(path) // now flip one bit in the middle of the compacted file
data[len(data)/2] ^= 0x40
os.WriteFile(path, data, 0o644)
s.f.Close()
s, _ = Open(path)
fmt.Printf("after bit flip at offset %d: recovered %d keys (everything before the corruption)\n", len(data)/2, len(s.index))
}
log size 379780 bytes, live keys 900, order:999={"state":"v9999"}, order:5 present=false
recovery: discarding torn/corrupt tail at offset 379780 (short body)
after reopen: live keys 900, order:999={"state":"v9999"} (the torn write was discarded)
before compaction: 379780 bytes
after compaction: 34200 bytes (91% smaller), live keys 900, order:999={"state":"v9999"}
recovery: discarding torn/corrupt tail at offset 17100 (checksum mismatch)
after bit flip at offset 17100: recovered 450 keys (everything before the corruption)
Reading the run:
- 10,000 updates to 1,000 keys plus 100 deletes produced a 380 KB log for 900 live keys: the log keeps history. Compaction shrank it by 91% to just the live records.
- A torn write (half a record, as after power loss mid-append) is detected on reopen because the record is short; recovery truncates it and the previous value of
order:999stands. The per-record CRC is what makes this safe: without it, a half-written length field could make recovery read garbage as data. - A single flipped bit in the middle of the file stops recovery at that record: 450 of 900 keys survive. That's the honest limit of a single log file with stop-at-first-error recovery. Production systems add resynchronisation markers so recovery can skip a bad record and continue, split the log into segments, keep replicas (project 10), and run checksums on reads (the
Getpath here verifies the CRC too).
Durability is explicit: Sync() calls fsync, and compaction fsyncs the new file before the rename, so a crash can't leave a renamed but empty file. Without the fsync, "written" means "in the page cache" (chapter 8). Going further: hint files for fast startup (store key → offset so the log needn't be replayed), concurrent readers with a single writer, and range queries (which need a sorted structure: an LSM tree or B+ tree, chapter 3).
Reference: concurrent file indexer (Go)
A walker goroutine feeds paths to a fixed pool of tokenising workers; a single merger goroutine owns the inverted index, so the index needs no locks. Queries use the same tokeniser as indexing and AND semantics.
// Project 6 reference: a concurrent file indexer. One goroutine walks the tree, a fixed pool of workers
// tokenises files, and a single merger owns the inverted index (term → set of files), so no locks are needed.
package main
import (
"bufio"
"fmt"
"io/fs"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"unicode"
)
type posting struct {
path string
terms map[string]int
}
func tokenize(path string) (map[string]int, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
terms := map[string]int{}
sc := bufio.NewScanner(f)
sc.Buffer(make([]byte, 64*1024), 1024*1024)
for sc.Scan() {
for _, w := range strings.FieldsFunc(strings.ToLower(sc.Text()), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) {
if len(w) > 2 {
terms[w]++
}
}
}
return terms, sc.Err()
}
func build(root string, workers int) (map[string]map[string]int, int, time.Duration) {
start := time.Now()
paths := make(chan string, 256)
results := make(chan posting, 256)
go func() { // walker
filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err == nil && d.IsDir() && strings.Contains(d.Name(), "backup") {
return filepath.SkipDir
}
if err == nil && !d.IsDir() && strings.HasSuffix(p, ".md") {
paths <- p
}
return nil
})
close(paths)
}()
var wg sync.WaitGroup
for i := 0; i < workers; i++ { // tokenising workers
wg.Add(1)
go func() {
defer wg.Done()
for p := range paths {
if t, err := tokenize(p); err == nil {
results <- posting{p, t}
}
}
}()
}
go func() { wg.Wait(); close(results) }()
index := map[string]map[string]int{} // merger: the only writer of the index
files := 0
for r := range results {
files++
for t, n := range r.terms {
if index[t] == nil {
index[t] = map[string]int{}
}
index[t][r.path] = n
}
}
return index, files, time.Since(start)
}
func search(index map[string]map[string]int, query string) []string {
var terms []string
for _, w := range strings.FieldsFunc(strings.ToLower(query), func(r rune) bool { return !unicode.IsLetter(r) && !unicode.IsDigit(r) }) {
if len(w) > 2 { // same tokenisation as indexing, or queries silently miss
terms = append(terms, w)
}
}
scores := map[string]int{}
for i, t := range terms { // AND semantics: keep files containing every term; score by total frequency
next := map[string]int{}
for p, n := range index[t] {
if _, ok := scores[p]; i == 0 || ok {
next[p] = scores[p] + n
}
}
scores = next
}
out := make([]string, 0, len(scores))
for p := range scores {
out = append(out, p)
}
sort.Slice(out, func(i, j int) bool { return scores[out[i]] > scores[out[j]] })
for i, p := range out {
out[i] = fmt.Sprintf("%s (%d)", filepath.Base(filepath.Dir(filepath.Dir(p)))+"/"+filepath.Base(p), scores[p])
}
return out
}
func main() {
root := "/home/asha"
build(root, 1) // warm the page cache so both timings measure CPU work, not first-read disk I/O
for _, w := range []int{1, runtime.NumCPU()} {
index, files, d := build(root, w)
fmt.Printf("%d worker(s): indexed %d files, %d distinct terms in %v\n", w, files, len(index), d.Round(time.Millisecond))
}
index, _, _ := build(root, runtime.NumCPU())
for _, q := range []string{"write skew serializable", "bloom filter", "copy-on-write fork"} {
r := search(index, q)
if len(r) > 3 {
r = r[:3]
}
fmt.Printf("%-26q → %v\n", q, r)
}
}
1 worker(s): indexed 293 files, 27883 distinct terms in 300ms
2 worker(s): indexed 293 files, 27883 distinct terms in 261ms
"write skew serializable" → [vol4/59a.md (73) vol17/194c.md (40) vol12/129a.md (32)]
"bloom filter" → [vol1/03b.md (25) vol1/03c.md (14) vol4/58a.md (10)]
"copy-on-write fork" → [vol1/08d.md (53) vol6/79a.md (37) vol1/08c.md (30)]
(The corpus is this book's own chapter files.) Two lessons from the run. First, the same tokenisation must apply at index and query time: the first draft split queries on spaces only, so copy-on-write was looked up as one token that didn't exist and returned nothing (chapter 194G's search lesson in miniature). Second, 2 workers were only 6% faster than 1: the single merger, which inserts every term of every file into the map, is the serial bottleneck (Amdahl's law: speeding up the parallel part doesn't help when the serial part dominates). The first timing run, before the warm-up line was added, showed 4.0 s vs 0.3 s, but that was the page cache (first read from disk vs cached), not parallelism: always warm caches or measure both deliberately. Going further: shard the index by term hash so several mergers can work in parallel, persist the index (and update it incrementally using file modification times or inotify), rank with BM25, and support phrase queries with positional postings.
Reference: TCP chat server (Go)
A hub goroutine owns the set of clients (no locks); each connection has a reader goroutine and a writer goroutine with a bounded outbox; a client that stops reading is disconnected after a short grace period rather than slowing everyone down.
// Project 8 reference: a TCP chat server. One goroutine per connection reads lines; a hub goroutine owns the
// set of clients and broadcasts; each client has a bounded outbox, and a client too slow to keep up is
// disconnected instead of stalling everyone (backpressure policy: drop the slow consumer).
package main
import (
"bufio"
"fmt"
"net"
"strings"
"time"
)
type client struct {
name string
outbox chan string
conn net.Conn
}
type hub struct {
join, leave chan *client
msgs chan string
}
func (h *hub) run() {
clients := map[*client]bool{} // owned by this goroutine only: no locks needed
for {
select {
case c := <-h.join:
clients[c] = true
h.fanout(clients, fmt.Sprintf("* %s joined (%d online)", c.name, len(clients)))
case c := <-h.leave:
if clients[c] {
delete(clients, c)
close(c.outbox)
h.fanout(clients, fmt.Sprintf("* %s left", c.name))
}
case m := <-h.msgs:
h.fanout(clients, m)
}
}
}
func (h *hub) fanout(clients map[*client]bool, m string) {
for c := range clients {
select {
case c.outbox <- m:
continue
default:
}
select { // outbox full: give the client a short grace period, then disconnect it rather than stall everyone
case c.outbox <- m:
case <-time.After(50 * time.Millisecond):
delete(clients, c)
close(c.outbox)
c.conn.Close()
fmt.Printf("server: dropped slow client %s\n", c.name)
}
}
}
func serve(h *hub, conn net.Conn) {
r := bufio.NewReader(conn)
conn.Write([]byte("name? "))
name, err := r.ReadString('\n')
if err != nil {
conn.Close()
return
}
c := &client{name: strings.TrimSpace(name), outbox: make(chan string, 256), conn: conn}
go func() { // writer: drains the outbox with a write deadline
for m := range c.outbox {
conn.SetWriteDeadline(time.Now().Add(2 * time.Second))
if _, err := conn.Write([]byte(m + "\n")); err != nil {
break
}
}
conn.Close()
}()
h.join <- c
for {
line, err := r.ReadString('\n')
if err != nil {
break
}
if line = strings.TrimSpace(line); line != "" {
h.msgs <- c.name + ": " + line
}
}
h.leave <- c
}
func main() {
h := &hub{join: make(chan *client), leave: make(chan *client), msgs: make(chan string, 64)}
go h.run()
ln, _ := net.Listen("tcp", "127.0.0.1:0")
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
go serve(h, conn)
}
}()
addr := ln.Addr().String()
dial := func(name string) (net.Conn, *bufio.Reader) {
c, _ := net.Dial("tcp", addr)
r := bufio.NewReader(c)
r.ReadString(' ') // "name? "
fmt.Fprintln(c, name)
return c, r
}
collect := func(r *bufio.Reader, out chan<- []string) { // a well-behaved client: reads continuously
var lines []string
for {
l, err := r.ReadString('\n')
if err != nil {
break
}
lines = append(lines, strings.TrimSpace(l))
}
out <- lines
}
asha, ra := dial("asha")
aOut := make(chan []string, 1)
go collect(ra, aOut)
time.Sleep(50 * time.Millisecond)
ravi, rr := dial("ravi")
rOut := make(chan []string, 1)
go collect(rr, rOut)
slow, _ := dial("slowpoke") // connects but never reads
slow.(*net.TCPConn).SetReadBuffer(4096)
time.Sleep(50 * time.Millisecond)
fmt.Fprintln(asha, "lunch at 12:30?")
fmt.Fprintln(ravi, "yes, biryani day")
for i := 0; i < 20000; i++ { // a burst big enough to overflow slowpoke's outbox and socket buffers
fmt.Fprintf(ravi, "spam %d %s\n", i, strings.Repeat("x", 200))
}
time.Sleep(500 * time.Millisecond)
asha.Close()
ravi.Close()
lines := <-aOut
spam := 0
var other []string
for _, l := range lines {
if strings.HasPrefix(l, "ravi: spam") {
spam++
} else {
other = append(other, l)
}
}
fmt.Println("asha saw:", strings.Join(other, " | "))
fmt.Printf("asha received %d of 20000 burst lines (a reading client loses nothing)\n", spam)
fmt.Printf("ravi received %d lines\n", len(<-rOut))
}
server: dropped slow client slowpoke
asha saw: * asha joined (1 online) | * ravi joined (2 online) | * slowpoke joined (3 online) | ravi: yes, biryani day | asha: lunch at 12:30?
asha received 20000 of 20000 burst lines (a reading client loses nothing)
ravi received 20004 lines
Twenty thousand messages in a burst reached the two well-behaved clients completely, while slowpoke, which never reads, was disconnected once its outbox and socket buffers filled (here by the hub's 50 ms grace timeout; on other runs the writer's 2 s write deadline closes it first and the hub sees a "left" event: both paths end in the same place). This is the central design decision of every fan-out system (chat, pub/sub, WebSocket notifications, Kafka consumers): what happens when one consumer is slow? Options are block everyone (simple, fragile), buffer without bound (memory blow-up), drop messages for that consumer, or disconnect it. Note also that ravi: yes, biryani day arrived before asha: lunch at 12:30? although asha sent first in program order: messages from different connections race through different goroutines, so there is no global order unless you create one (sequence numbers from the hub, chapter 9's and Volume 5's ordering discussions). The run under go run -race reported no data races.
Reference: replicated key-value service (Go)
Three replica HTTP servers and a coordinator that writes to all and waits for W = 2 acknowledgements, reads from all and waits for R = 2 answers, returns the highest version, and repairs stale replicas it read from.
// Project 10 reference: a replicated key-value service with quorum reads and writes (N=3, W=2, R=2),
// versioned values (last-writer-wins by a per-key version from the coordinator), read repair, and
// tolerance of one failed node. Each replica is a real HTTP server; the coordinator is a client library.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"sync"
"time"
)
type Versioned struct {
Value string `json:"value"`
Version int64 `json:"version"` // coordinator-assigned; higher wins
}
type Replica struct {
name string
mu sync.Mutex
data map[string]Versioned
srv *http.Server
addr string
down bool
}
func (r *Replica) ServeHTTP(w http.ResponseWriter, req *http.Request) {
r.mu.Lock()
defer r.mu.Unlock()
if r.down { // simulate a crashed/partitioned node: never answer
r.mu.Unlock()
time.Sleep(2 * time.Second)
r.mu.Lock()
return
}
key := req.URL.Path[len("/kv/"):]
switch req.Method {
case http.MethodGet:
v, ok := r.data[key]
if !ok {
http.NotFound(w, req)
return
}
json.NewEncoder(w).Encode(v)
case http.MethodPut:
var v Versioned
if json.NewDecoder(req.Body).Decode(&v) != nil {
http.Error(w, "bad body", 400)
return
}
if cur, ok := r.data[key]; !ok || v.Version > cur.Version { // never overwrite newer with older
r.data[key] = v
}
w.WriteHeader(http.StatusNoContent)
}
}
func startReplica(name string) *Replica {
r := &Replica{name: name, data: map[string]Versioned{}}
ln, _ := net.Listen("tcp", "127.0.0.1:0")
r.addr = "http://" + ln.Addr().String()
r.srv = &http.Server{Handler: r}
go r.srv.Serve(ln)
return r
}
type Coordinator struct {
replicas []*Replica
w, r int
client *http.Client
clock int64
mu sync.Mutex
}
func (c *Coordinator) nextVersion() int64 { // stands in for a hybrid logical clock
c.mu.Lock()
defer c.mu.Unlock()
c.clock = max(c.clock+1, time.Now().UnixNano())
return c.clock
}
func (c *Coordinator) Put(key, value string) error {
body, _ := json.Marshal(Versioned{value, c.nextVersion()})
acks := make(chan bool, len(c.replicas))
for _, rep := range c.replicas { // send to all N, wait for W acknowledgements
go func(rep *Replica) {
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodPut, rep.addr+"/kv/"+key, bytes.NewReader(body))
resp, err := c.client.Do(req)
if err == nil {
resp.Body.Close()
}
acks <- err == nil && resp.StatusCode == http.StatusNoContent
}(rep)
}
ok := 0
for i := 0; i < len(c.replicas); i++ {
if <-acks {
if ok++; ok >= c.w {
return nil
}
}
}
return fmt.Errorf("write quorum not reached: %d/%d acks", ok, c.w)
}
type reply struct {
rep *Replica
v *Versioned
err error
}
func (c *Coordinator) Get(key string) (string, error) {
replies := make(chan reply, len(c.replicas))
for _, rep := range c.replicas {
go func(rep *Replica) {
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, rep.addr+"/kv/"+key, nil)
resp, err := c.client.Do(req)
if err != nil {
replies <- reply{rep, nil, err}
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
replies <- reply{rep, nil, nil}
return
}
var v Versioned
err = json.NewDecoder(resp.Body).Decode(&v)
replies <- reply{rep, &v, err}
}(rep)
}
var got []reply
for i := 0; i < len(c.replicas) && len(got) < c.r; i++ {
if rp := <-replies; rp.err == nil {
got = append(got, rp)
}
}
if len(got) < c.r {
return "", fmt.Errorf("read quorum not reached: %d/%d", len(got), c.r)
}
var newest *Versioned
for _, rp := range got {
if rp.v != nil && (newest == nil || rp.v.Version > newest.Version) {
newest = rp.v
}
}
if newest == nil {
return "", fmt.Errorf("not found")
}
for _, rp := range got { // read repair: push the newest version to replicas that answered with older data
if rp.v == nil || rp.v.Version < newest.Version {
body, _ := json.Marshal(newest)
req, _ := http.NewRequest(http.MethodPut, rp.rep.addr+"/kv/"+key, bytes.NewReader(body))
if resp, err := c.client.Do(req); err == nil {
resp.Body.Close()
fmt.Printf(" read repair: updated %s\n", rp.rep.name)
}
}
}
return newest.Value, nil
}
func (c *Coordinator) dump(key string) string {
s := ""
for _, r := range c.replicas {
r.mu.Lock()
v, ok := r.data[key]
r.mu.Unlock()
if ok {
s += fmt.Sprintf("%s=%q ", r.name, v.Value)
} else {
s += r.name + "=∅ "
}
}
return s
}
func main() {
a, b, c3 := startReplica("A"), startReplica("B"), startReplica("C")
co := &Coordinator{replicas: []*Replica{a, b, c3}, w: 2, r: 2, client: &http.Client{}}
fmt.Println("put plan=veg_20 →", co.Put("sub:77", "veg_20"))
fmt.Println(" replicas:", co.dump("sub:77"))
c3.mu.Lock()
c3.down = true // node C fails
c3.mu.Unlock()
fmt.Println("C down; put plan=nonveg_20 →", co.Put("sub:77", "nonveg_20"))
fmt.Println(" replicas:", co.dump("sub:77"))
v, err := co.Get("sub:77")
fmt.Println("get with C down →", v, err)
c3.mu.Lock()
c3.down = false // C returns with stale data
c3.mu.Unlock()
b.mu.Lock()
b.down = true // and now B fails
b.mu.Unlock()
fmt.Println("C back (stale), B down:")
v, err = co.Get("sub:77")
fmt.Println("get →", v, err)
fmt.Println(" replicas:", co.dump("sub:77"))
a.mu.Lock()
a.down = true // two of three down: no quorum
a.mu.Unlock()
fmt.Println("A and B down; put →", co.Put("sub:77", "paused"))
}
put plan=veg_20 → <nil>
replicas: A="veg_20" B="veg_20" C="veg_20"
C down; put plan=nonveg_20 → <nil>
replicas: A="nonveg_20" B="nonveg_20" C="veg_20"
get with C down → nonveg_20 <nil>
C back (stale), B down:
get → nonveg_20 <nil>
replicas: A="nonveg_20" B="nonveg_20" C="nonveg_20"
A and B down; put → write quorum not reached: 1/2 acks
Step by step:
- The first write returns after two acknowledgements; at that instant replica C hasn't applied it yet (
C=∅): a write quorum doesn't mean all replicas are current. - With C down, writes still succeed (A and B acknowledge) and reads return the new value: the system tolerates one failure out of three.
- C comes back stale (it missed the second write), then B fails. A read gets answers from A (new) and C (stale); because R + W > N, at least one of them must have the latest write, and the coordinator picks the highest version. Read repair then updates C.
- With two nodes down, a write can't reach quorum and fails explicitly, rather than accepting a write it can't make durable (the CP choice, chapter 9 and Volume 17, ch. 194D).
The simplifications are the next milestones, and each one is a famous problem: versions come from one coordinator's clock (multiple coordinators need hybrid logical clocks or vector clocks to order concurrent writes, and must decide how to resolve true conflicts); there is no hinted handoff or anti-entropy (C is repaired only if someone reads the key; Merkle trees, chapter 3, let replicas find differences efficiently); membership is static (adding nodes needs consistent hashing and rebalancing, Volume 17, ch. 194G); and failure detection is just a timeout. Then compare with Raft-based designs (etcd), which give linearizable reads and writes at the cost of a leader on every write path.