Volume 1 Exercises: Foundations of ComputingPractice for Volume 1
0 / 0

Workbench / Volume 1 Exercises: Foundations of Computing

V1·11

Computer Science Mastery Projects

Exercises for Volume 1, chapter 11: checkpoints for the five warm-ups and the ten mastery projects (memory allocator, shell, HTTP server, thread pool, key-value store, file indexer, DNS client, TCP chat server, tiny compiler or interpreter, distributed key-value service), how to choose a language, test, measure and log a project, and how to read the reference implementations. 11 theory questions, 11 programming checkpoints, 3 integration projects, the engineering practices the chapter leaves out, and 6 senior-level exercises.

37 exercises · ~17 min to read
Updated Suggest a correction

Start here: how this chapter's exercises work

This chapter is projects, so its exercises work differently. They don't ask you to build the ten projects again; they're checkpoints that check you understood each project's hard part before (theory) and while (programming) you build it.

  • Theory (one per project, plus warm-ups and method): the design decisions and failure modes each project exists to teach.
  • Programming checkpoints: a small, self-contained piece of each project (often its test harness or its trickiest component) with real output. If your checkpoint passes, your project's foundation is sound.
  • Integration projects join several mastery projects into one system, which is the cumulative set for this chapter: they draw on all of chapters 01–10.
  • What the chapter leaves out: the engineering practices that separate "it works on my machine" from a project you can defend in a design review or an interview.
  • Senior exercises: reviewing, scoping, explaining and presenting project work.

Earlier chapters already contain parts of several projects: chapter 08's C1 (an append-only log with group commit) is project 5's storage engine; chapter 09's C1 (an HTTP/1.1 server) and P10 (a DNS client) are projects 3 and 7; chapter 10's P1–P3 and C1–C2 (lexer, parser, checker, bytecode VM) are project 9. Reuse them.

Outputs come from this book's sandbox (Java 21, gcc 13, 2 vCPUs). Java is used where possible; the allocator and shell checkpoints need C, because their subject is the C/Unix interface.

Coverage map.

Chapter component Exercises
warm-ups; how to approach the projects; choosing a language T1, S3
Project 1: memory allocator T2, P1
Project 2: shell T3, P2
Project 3: HTTP server T4, P3
Project 4: thread pool T5, P4
Project 5: key-value store T6, P5
Project 6: file indexer T7, P6
Project 7: DNS client T8, P7
Project 8: TCP chat server T9, P8
Project 9: tiny compiler or interpreter T10, P9
Project 10: distributed key-value service T11, P10
tracking progress; the project log; reference implementations P11, S1, S6

Theory

T1. What the warm-ups and the method are for

  1. The warm-ups (guessing game, word counter, to-do list, temperature converter, calculator in Java) each practise one idea that every mastery project depends on. Name the idea for each, and the mastery project where forgetting it would hurt most.
  2. The chapter recommends milestones, a project log and testing each milestone before the next. Why does building in milestones matter more for these projects than for typical work tasks?
  3. The chapter suggests different languages per project (C for the allocator and shell, Go or Java for servers, Rust or C++ for the thread pool…). Give the principle behind the choices, and when you'd override it.

T2. The memory allocator

  1. Why does a general-purpose allocator need headers, alignment and a free list, while a bump allocator needs none? Where are bump allocators used for real?
  2. Explain external fragmentation with P1's numbers: after 11,012 allocations in a 1 MB heap, first-fit had 88 KB free but its largest free block was 8 KB, so 88 allocations failed. How do splitting, coalescing and size classes each help?
  3. Compare first-fit and best-fit using P1 (best-fit: 52 KB free, 4 KB largest, 72 failures, 1,027 blocks scanned per malloc vs 582 for first-fit). Why don't real allocators use either?
  4. Why do tcmalloc, jemalloc and mimalloc use per-thread caches, and what chapter 07 problem do they also have to avoid?

T3. The shell

  1. Why must cd, exit and export be built-ins rather than programs?
  2. For a | b | c, how many pipes and processes are created, which descriptors does each process end up with, and why does forgetting to close one unused write end make the pipeline hang forever (P2)?
  3. Explain process groups, setpgid and tcsetpgrp, and why Ctrl-C in a correct shell kills the foreground pipeline but not the shell.
  4. How does a shell avoid zombies from background jobs?

T4. The HTTP server

  1. Name five ways a naive HTTP server breaks on real input (framing, partial reads, slow clients, path traversal, oversized headers, keep-alive) and the fix for each.
  2. The project asks you to load-test three concurrency models (thread per connection, a thread pool, an event loop / virtual threads). What should the results show at 100, 1,000 and 10,000 concurrent keep-alive connections, and why?
  3. What does sendfile do, and why does it help a static file server?

T5. The thread pool

  1. Describe the core design (workers, a bounded queue, futures), and explain what must happen when a task throws an exception, when the queue is full, and on shutdown.
  2. P4's pool, with 1 worker and a queue of 2, rejected 8 of 10 blocking submissions. Why 8 and not 7, and why is that a lesson about testing concurrent code?
  3. What's work stealing, and why do ForkJoinPool and Go's scheduler use per-worker deques where workers pop their own work from one end and steal from the other end of others'?
  4. Name three deadlock or starvation hazards specific to thread pools.

T6. The key-value store

  1. Design the write path for SET k v so that once the client gets "OK", the value survives a power failure. Where do the write-ahead log, fsync and the in-memory index fit, and what does group commit buy (chapter 08's C1)?
  2. Compare a hash index over an append-only log (Bitcask) with an LSM tree (memtable, sorted SSTables, compaction) on: write speed, read speed, range queries, memory needed, and space reclamation.
  3. What can go wrong on restart if the last log record was half-written, and how does a checksum per record handle it?
  4. Your store answers GET from memory and SET through the log. Two clients SET the same key concurrently. What ordering guarantee do you give, and how do you implement it?

T7. The file indexer

  1. Design an inverted index for rust AND async NOT tokio: what's stored, how a query is evaluated with sorted posting lists, and the cost of AND and OR (chapter 05).
  2. What should the tokenizer do about case, punctuation, Unicode normalisation, and non-English text (Hindi, Telugu, Chinese)? What happens to a file that isn't valid UTF-8?
  3. How should the walker handle symlinks, permission errors, huge files and binary files? How do you keep the index current as files change, without re-reading everything?
  4. Why is the index in this project essentially what Lucene/Elasticsearch do, and what do they add?

T8. The DNS client

  1. Walk through iterative resolution of www.github.com from the root, as dig +trace does: which servers, which record types at each step (NS referrals, glue A records, CNAME), and when you stop.
  2. Why must the client handle message compression pointers carefully (chapter 06's binary-parsing lessons), and what malformed inputs should its tests include?
  3. What should the client do on timeouts, truncated responses (the TC flag), and SERVFAIL, and how should its cache handle TTLs and negative answers?

T9. The TCP chat server

  1. Why does broadcasting a message to a room need care when one client is slow (a phone on a bad network)? Describe three strategies and which you'd choose.
  2. How do you frame chat messages on TCP, and what limits do you enforce per client?
  3. What happens to the server when 5,000 idle clients stay connected, and how do keep-alives and idle timeouts interact with NAT (chapter 09)?

T10. The tiny compiler or interpreter

  1. Closures: explain why make_counter() returning a function that increments a captured variable requires environments that outlive a function call. How does a tree-walking interpreter represent them, and what does a bytecode VM do instead (upvalues in Lua and clox)?
  2. Your interpreter supports recursion. What happens with fib(100000) written recursively, and how do real implementations handle deep recursion (stack limits, tail calls)?
  3. Your language allocates closures and lists. When do you need a garbage collector, and what's the simplest correct one to write (mark-sweep with an explicit root set)?

T11. The distributed key-value service

  1. Explain Raft's leader election (terms, randomised timeouts, votes) and log replication (append entries, the commit index). Why is a write committed only once a majority has it, and what does that buy during a partition?
  2. A 5-node cluster: how many failures can it tolerate? What about 4 nodes, and why is an even number of nodes a poor choice?
  3. A client sends SET x 1 to the leader, the leader crashes before replying, and the client retries with a new leader. How do you prevent the command being applied twice, and why does it matter for INCR x?
  4. Why can a leader that serves reads from its local state return stale data, and what are two ways to make reads linearizable?

Programming checkpoints

P1. An allocator you can measure

In Java, simulate an allocator over a 1 MB heap stored in an int[]: each block has an 8-byte header (size and a free flag); malloc(n) rounds n + 8 up to 16 bytes, finds a free block by first-fit or best-fit, and splits it if the remainder is at least 32 bytes; free marks the block free and coalesces adjacent free blocks. Run 20,000 random operations (55% allocations: 90% of sizes 16–215 bytes, 10% 2,000–7,999 bytes; otherwise free a random live block) with a fixed seed, and report: failed allocations, total free memory, the largest free block, external fragmentation (1 − largest ÷ total free), and blocks scanned per malloc. Add a shadow map that checks no two live blocks overlap after every operation.

P2. The pipe that never ends

In C, run printf 'b\na\n' | sort with pipe, fork, dup2 and execlp, waiting for both children. Run it twice: once closing every unused pipe end in the parent and in each child, once leaving the write end open in the sort child and in the parent. Use timeout 3 around the second run and report the exit status. Then explain which open write end was enough to cause the hang.

P3. An HTTP server's hostile-input test suite

Write a test program (in any language) that connects to your project-3 HTTP server (or chapter 09's C1) and checks its behaviour for: a request split across 5 writes with 100 ms pauses; two pipelined requests in one write; a header line of 64 KB; a body shorter than its Content-Length followed by silence; GET /../../etc/passwd and GET /%2e%2e/%2e%2e/etc/passwd; 200 concurrent idle keep-alive connections plus one real request; and a slowloris client sending one header byte per second. For each, state the expected response or behaviour (status code, close, timeout) and report pass or fail.

P4. A thread pool's contract tests

Implement a minimal Java thread pool (fixed workers, ArrayBlockingQueue, submit(Callable) returning a FutureTask, abort-on-full rejection, close() that stops accepting, lets queued tasks finish and joins workers). Test: 100 tasks computing squares sum to 328,350; a task that throws an Exception and one that throws an Error both deliver their failure through get() and the worker survives; with 1 worker, a queue of 2 and 10 blocking tasks, how many are rejected; submitting after close() is rejected.

P5. Crash-test the key-value store

Write a test harness for your project-5 store (or chapter 08's C1 log): a client process sends SET key-i value-i for i = 1, 2, 3… as fast as it can and prints each key it gets "OK" for to a file; the harness kills the server with kill -9 at a random moment, restarts it, and checks that every acknowledged key is present with the right value and that no key has a corrupted value. Repeat 50 times. Then corrupt one byte in the middle of the log file and check the server's behaviour on restart.

P6. An inverted index with set operations

In Java, index a directory of text files (any source tree works): tokenise with Unicode-aware splitting (\p{L}+|\p{N}+), lowercase with Locale.ROOT, normalise with Normalizer.Form.NFC, and build a Map<String, int[]> of sorted posting lists. Implement AND, OR and NOT as linear merges of sorted arrays, parse queries like rust AND async NOT tokio (left to right is fine), and print the matching paths and query time. Compare with grep -rl for the same terms, both for results and speed on repeated queries.

P7. Iterative DNS resolution

Extend chapter 09's P10 DNS client to resolve iteratively: start from a root server's IP (for example a.root-servers.net, 198.41.0.4), send queries without the recursion-desired bit, follow NS referrals using glue records (resolving name-server names when glue is missing), follow CNAMEs, and print each step like dig +trace. Cap referrals and CNAME chains, set a timeout and one retry per server, and cache referrals for the run. Test with names that need a CNAME (www.github.com) and one that doesn't exist.

P8. A slow consumer in a chat room

With your chat server (project 8), connect 50 clients to one room, where one client never reads from its socket. Have another client send 10,000 messages of 100 bytes. Measure: do the other 48 receivers get all messages, how long it takes, the server's memory use, and what happens to the non-reading client. Run it against a naive version (broadcast writes directly to each socket in a loop) and your improved version (bounded per-client queues with a drop or disconnect policy).

P9. Closures and deep recursion in your interpreter

Write test programs for your project-9 interpreter: (a) make_counter returning a closure, called three times on two independent counters (expect 1, 2, 3 and 1, 2, 3); (b) a closure capturing a loop variable inside a while loop (decide your language's semantics: per-iteration binding or shared, and test it); (c) recursive fib(25) for correctness and timing; (d) recursion 100,000 deep, which must give a clean error, not crash the interpreter; (e) a program that allocates a million short-lived closures, checking memory stays bounded.

P10. Partition your Raft cluster

For your project-10 cluster of 5 nodes, write a test that: (1) writes 1,000 keys through the leader; (2) partitions the leader and one follower from the other three (block traffic between groups: in-process, by dropping messages in your transport layer; or with iptables between containers); (3) keeps writing from clients on both sides for 10 seconds; (4) heals the partition; (5) checks that every write that got "OK" is present on all nodes, no write that got an error or timeout appears twice, and all nodes' logs agree. Record a history of operations (invoke and complete times, results) and check it for linearizability with a checker such as Porcupine (Go) or Knossos (Clojure, via Jepsen).

P11. Keep a project log that's worth reading

Pick one project you've started and write its log entries for three milestones using the chapter's template (goal, what you built, what broke and why, how you found it, what you measured, what you'd do differently). Then turn it into a one-page project summary with: the problem, the design (one diagram), two hard problems you solved with evidence, measurements with methodology, known limitations, and what you'd build next.

Integration projects (chapters so far: 01–10)

C1. The shell meets the indexer

Add two built-ins to your project-2 shell: index <dir>, which builds (or loads) a project-6 index of a directory in the background as a job, and find-text <query>, which runs a query against it and writes matching paths to stdout, so it composes with pipes (find-text "async AND NOT tokio" | xargs wc -l). The index must update incrementally as files change, survive a shell restart (saved to disk with a checksum), and the shell must stay responsive while indexing runs.

Combines: shell, pipes and stdout (ch 01, 08); clean design (ch 02); inverted indexes and tries (ch 03); merge algorithms (ch 04); set logic (ch 05); UTF-8 and normalisation (ch 06); page cache and file I/O performance (ch 07, 08); file watching (ch 08); parsing the query language (ch 10); projects 2 and 6.

C2. A production-shaped key-value service

Combine projects 3, 4 and 5: put an HTTP/JSON API (GET/PUT/DELETE /kv/{key}) and the project-5 binary protocol in front of your key-value store, run request handling on your project-4 thread pool (or virtual threads), and add what a real service needs: health and readiness endpoints, metrics (request counts and latency histograms per operation, fsync latency, queue depth), structured logs with request IDs, graceful shutdown on SIGTERM (finish in-flight requests, flush the log), configuration via environment variables, and a load test reporting throughput and p50/p99/p999 latency at several concurrency levels.

Combines: CLI, configuration and exit codes (ch 01); error handling and API design (ch 02); hash maps and logs (ch 03); percentiles (ch 04, 05); binary formats and checksums (ch 06); caches and syscalls (ch 07); fsync, signals and thread pools (ch 08); HTTP, keep-alive and timeouts (ch 09); the JVM's warm-up and GC (ch 10); projects 3, 4 and 5.

C3. Chaos test the distributed service

Run your project-10 cluster (5 nodes, each built like C2) under a continuous workload while a chaos script randomly, every 10–30 seconds, does one of: kill -9 a node, partition the network (minority/majority, or isolate the leader), add 200 ms latency to one node, fill one node's disk, pause a node (SIGSTOP for 15 s, simulating a long GC pause), or skew one node's clock. Record a full operation history, check linearizability (P10), and track availability (percentage of successful operations per second) and recovery time after each fault. Write up the results, every bug found, and its fix.

Combines: process control and signals (ch 01, 08); everything in ch 02–07 as used by the nodes; disk-full and fsync failures (ch 08); latency, partitions and timeouts (ch 09); GC pauses (ch 10); projects 5 and 10.

What the chapter leaves out

Testing techniques that fit systems projects

Example-based unit tests are not enough for these projects. Use property-based testing (jqwik for Java, Hypothesis for Python, proptest for Rust): state invariants ("after any sequence of mallocs and frees, no live blocks overlap") and let the tool generate and shrink failing sequences to minimal examples. Use differential testing: compare your component against a reference (your shell against bash -c, your allocator against a shadow map, your resolver against dig, your interpreter against a simpler interpreter). Use fuzzing (Jazzer for Java, libFuzzer/AFL for C, go test -fuzz) for every parser: HTTP requests, DNS responses, log records, your language's source. Use deterministic simulation for concurrency and distribution (one thread, a seeded scheduler and a simulated network, as FoundationDB and TigerBeetle do), so every failure can be replayed exactly.

Benchmarking methodology

Numbers without methodology are noise. State the hardware, OS, runtime version and flags; warm up (chapter 10); repeat runs and report variation (median and spread, or confidence intervals); measure latency percentiles with histograms (HdrHistogram), from the client side, and avoid coordinated omission (a load generator that waits for each response before sending the next hides queueing delays: use constant-rate generators like wrk2, k6's arrival-rate executors or Gatling's open models); compare against a baseline (the system allocator, ThreadPoolExecutor, Redis) on the same machine; change one thing at a time; and explain why the numbers are what they are (with profiles: chapter 10's gaps). A benchmark you can't explain is a benchmark you can't trust.

Reading reference implementations well

The chapter's reference implementations (C, Go, C++) are most useful when read after your own attempt, with questions: what did they handle that I didn't (error paths, limits, partial reads)? What's simpler in theirs? What would break first under load? Go further with production code at the same scale: Redis's ae.c event loop and AOF, SQLite's pager and WAL, musl's malloc, Go's net/http server, the JDK's ThreadPoolExecutor and ForkJoinPool, etcd's raft package, Lua's VM (lvm.c, about 2,000 lines). Read tests first (they show the intended behaviour), then the main loop, then the error handling. Keep notes in your project log.

Scoping and finishing

Most personal projects die from scope, not difficulty. Define "done" per milestone before starting it; time-box stretch goals; ship a working, tested, documented version before optimising; and keep a known limitations section instead of fixing everything. A finished project with honest limitations teaches more, and shows better, than an ambitious unfinished one. The same skill (cutting scope while protecting the core) is what senior engineers do on every real project.

Making projects presentable

A project is portfolio evidence only if someone can understand it in five minutes: a README with what it is, how to run it (one command, ideally a container), a design diagram, the test and benchmark results with methodology, and limitations; clean history with meaningful commits; CI running tests on every push. For interviews, the project log's "what broke and why" entries are the stories: a concrete bug, your wrong hypotheses, how you found the real cause, what you changed. Interviewers at senior level care about that reasoning far more than about features.

Senior exercises

S1. Review a teammate's project like a design review

A junior teammate shares their project-5 key-value store: a HashMap in memory, a background thread that writes the whole map to data.json every 5 seconds, a custom text protocol over TCP with one thread per client, and a README claiming "durable and fast: 200k ops/sec". Write the review: what's good, the top issues by severity with the evidence or test that would demonstrate each, and the three changes that would teach them the most.

S2. Turn a project into a team design document

You want to propose, at work, replacing an ad-hoc file-based job queue with a small internal service based on your project-5/project-10 experience. Write the outline of the design document: context, goals and non-goals, the proposed design, alternatives considered (including "use an existing system"), risks, rollout and how you'll measure success. Be honest about when not to build it.

S3. Choose what to build next, deliberately

You have about five hours a week for six months. Using this chapter's ten projects, design a plan that maximises growth towards a senior/staff role for a Java backend engineer: which projects, in which order and languages, what to skip, and how you'll know each was worth it. Justify choices against the skills a staff engineer is expected to show.

S4. Explain linearizability to your team with your own project

Using your project-10 cluster (or a whiteboard simulation of it), prepare a 10-minute explanation of linearizability for engineers who use etcd, ZooKeeper or a database's "strong consistency" setting without knowing what it promises. Include one concrete history that is linearizable and one that isn't, why the second can happen with stale leader reads, and what it means for code they write.

S5. Decide whether a project's design would survive production

Take your C2 service (HTTP + thread pool + KV store, single node). The product team wants to use it for session storage for the mobile app: 2 million active sessions, 5,000 reads/s and 500 writes/s at peak, sessions expire after 30 days, and losing sessions logs users out. List what would have to change for production, estimate memory and disk, and decide whether to adopt it, adopt an existing system, or adapt it.

S6. Tell a project story in an interview

Prepare the story of one project for a senior engineering interview, in the STAR shape but with technical depth: about 3 minutes, covering the goal, one hard problem (symptom, wrong hypotheses, investigation, root cause, fix), the evidence that it worked (measurements, tests), a trade-off you made deliberately, and what you'd do differently. Then list the five follow-up questions an interviewer is likely to ask, with short answers.