
Recall first from Timed coding exercises
- Geometric growth gives constant amortized cost for single-element vector insertion.
- An owning C-compatible byte string needs storage for a terminator beyond its logical length.
- An SPSC queue publishes written slots and releases consumed slots through separate atomic indices.
Defending trade-offs: performance, safety, complexity
4 min readThe previous lesson practiced timed coding. This lesson covers performance versus safety versus complexity, behavioral and architecture questions, end-to-end systems-design scenarios, and a full timed mock interview with feedback.
Trade-off questions exist because facts alone do not prove judgment. You can recite what epoll does and still be a poor engineer if you reach for it on a program with two connections. In a design discussion the interviewer is checking whether you can connect a requirement to a mechanism and honestly state what that mechanism costs. "It depends" is the beginning of an answer, never the answer. What must follow is the specific thing it depends on.
A defensible trade-off answer has four moves. First, state the constraint that drives the decision: a latency budget, a RAM ceiling, a message rate, the cost of a failure, or the size of the team that must maintain the code. Second, name your choice. Third, name the cost you are paying, out loud, without minimizing it. Fourth, state the reversal condition: the change in requirements that would make you choose the other way. That last move is what separates a senior answer from a rehearsed one, because it shows your choice is contingent on evidence rather than habit.
The module gave you a stock of real pairs to practice on. unique_ptr versus shared_ptr: shared ownership buys flexible lifetimes but pays with atomic reference-count traffic on every copy and the risk of reference cycles; if one owner is expressible, exclusive ownership is simpler and cheaper. Exceptions versus error codes: exceptions keep the happy path clean and make ignoring an error hard, but they grow binary size and are often disabled in embedded builds; error codes work everywhere but can be silently dropped at any call site. malloc versus a fixed-block pool: the general-purpose allocator in glibc is flexible and battle-tested, but its latency varies with heap state and long-running processes can fragment; a pool gives constant-time allocation from a fixed arena, at the price of a hard capacity limit and code you must write and test yourself. Virtual functions versus CRTP: run-time polymorphism lets you swap implementations behind a stable interface, while static polymorphism removes the indirect call but couples callers to concrete types at compile time and can grow code size. Thread-per-connection versus a single event loop: threads give isolation and simple blocking code, while one loop gives cheap idle connections but makes every handler share one thread of execution.
Notice that none of these pairs has a universal winner. What decides is the constraint. A daemon that must survive for months on a board with little RAM leans toward pools and error codes; a tool that processes files and exits leans toward the standard allocator and whatever makes the code clearest.
One more rule: quantify only what you can defend. If you claim a performance difference, either you measured it (the profiling lesson showed how with perf) or you say "I would measure this before committing". Inventing numbers in an interview is worse than admitting uncertainty, because a good interviewer will probe the number and the whole answer collapses with it.
Take three pairs from this module and speak a 60-second defense of each: constraint, choice, cost, reversal condition. Record yourself. If you cannot fill 60 seconds without hand-waving, you do not yet understand the cost side well enough, and that is exactly what the interviewer will find.
Behavioral, design, and architecture questions
3 min readBehavioral questions ("tell me about a bug that was hard to find", "tell me about a disagreement in a code review") are answered with the a structure for behavioral answers: Situation, Task, Action, Result structure. Set the situation in one or two sentences, state what you were responsible for, describe what you actually did, and end with a concrete result. You have real material from this course: the middleware project, the code review feedback loop, a sanitizer report you chased, a deadlock you reproduced. Use those. A specific story with a modest result beats a grand story with no details, and owning a mistake ("my first fix was wrong because I had not reproduced the failure") reads as strength, not weakness.
Design questions ("how would you structure a logger for ten processes on one board?") have no single correct answer, so the walkthrough is the answer. A repeatable skeleton:
Clarify constraints: rates, latency budget, memory ceiling, failure cost, lifetime of the system. Ask before assuming.
Sketch the structure: components, data flow, and which thread or process owns each piece of state.
Name ownership and interfaces: who allocates, who frees, what crosses each boundary.
Walk the failure paths: what happens on overload, disconnect, exhaustion, and restart.
State the trade-offs: what this design pays, and what would change your mind.
Propose verification: the tests, fault injection, or measurements that would prove it works.
Architecture discussions are design questions at a longer time scale: the interviewer cares about boundaries that must survive change. The vocabulary you built in this module is exactly right here. Where is the hardware abstraction layer, so the control logic can be tested against a mock? What is the threading model: one owning thread per component with queued commands, or shared state under mutexes? What is the error strategy at each boundary, and where does it convert? Which interfaces are stable, and which are free to change? Answering with boundaries, ownership, and testability rather than with class names shows you think about the system, not just the code.
The common failure modes are worth naming because they are visible from outside. Jumping straight to code before stating constraints. Making an assumption silently instead of saying it. Treating a new constraint from the interviewer as an attack to be defended against rather than information: when the interviewer says "now assume the device has 64 MB of RAM", the strong move is to update the design and say what changed and why. And going quiet: a design interview scores your spoken reasoning, so narrate even while you think.
Systems-design scenarios, end to end
5 min readThe three scenarios below (an event loop, a middleware, a memory pool) are drawn from the systems you built in this module, so you are rehearsing articulation, not learning new mechanisms. Practice each as a spoken ten-minute walkthrough.
Going deeperScenario 1: design an event loop
Constraints first. Say them before drawing anything: many mostly-idle socket connections, one core is enough for the work, bounded memory, and no connection may starve the others for long.
Structure. One thread owns all connections. Every socket is nonblocking (O_NONBLOCK). The loop registers each descriptor with epoll_ctl on an epoll instance from epoll_create1, then blocks in epoll_wait. Timers are themselves file descriptors created with timerfd_create, so timeouts join the same wait instead of needing a second mechanism. Each ready descriptor maps to a handler; the handler reads or writes until the operation returns EAGAIN, then returns control to the loop.
Failure paths. With edge-triggered registration (EPOLLET), a handler that stops reading before EAGAIN strands data until the next edge arrives: the walkthrough must say "drain until EAGAIN" explicitly. A peer that closes shows up as a read of zero bytes, and the handler must clean up its registration and state. A handler that throws or crashes takes the whole loop down, so error handling per handler is a stated requirement, not an afterthought.
Trade-offs. Versus thread-per-connection: idle connections cost a descriptor and a small state object instead of a thread with its stack reservation (8 MiB of virtual address space per thread by default on Ubuntu: pthread_attr_getstacksize returned 8388608 and ulimit -s printed 8192 in a test), and there is no cross-thread synchronization because one thread owns everything. The cost: one slow handler delays every other connection, so handlers must do bounded work per invocation and push long jobs elsewhere. Reversal condition: if handlers genuinely block on disk or heavy computation, threads or a worker pool win.
Verification. Connect many idle clients and confirm memory stays flat; inject a slow handler and measure how long an unrelated connection waits.
Going deeperScenario 2: design a middleware for processes on one board
Constraints. Several processes on one device exchange small messages; the message size has a fixed upper bound; the system must survive one peer crashing and restarting; RAM is tight.
Structure. A Unix domain socket per peer pair, a length-prefixed wire format with a version field and a message type, and one owning thread per component with a bounded inbound queue. The fixed size cap is the load-bearing decision: it lets every message buffer come from a fixed-block pool, so no allocation happens on the message path.
Failure paths. Reads are partial by nature: the receiver loops until the full frame arrives, and a frame whose declared length exceeds the cap is a protocol violation, answered by closing that connection, not by trusting the length. A crashed peer is detected by the socket closing; the survivor drops queued messages for it and accepts a fresh connection when it restarts. A full inbound queue applies backpressure or drops by a stated policy; "the queue never fills" is not a policy.
Trade-offs. The fixed cap buys pool allocation and simple framing but rejects legitimately large payloads: the reversal condition is a requirement for unbounded payloads, which forces streaming or heap buffers. The version field costs a few bytes per message and buys the ability to evolve the format without lockstep upgrades.
Verification. Fault injection: truncated frames, oversized lengths, a peer killed mid-message, and a flood that fills the queue. Each has a defined expected behavior, which is what makes it a test.
Going deeperScenario 3: design a fixed-block memory pool
Constraints. A control path must allocate with predictable latency; the number of live objects has a known ceiling; the pool lives for the whole program.
Structure. A static arena of raw storage, aligned for the strictest type it will hold (alignof(std::max_align_t) is the safe default), carved into N equal blocks. Free blocks form a free list whose next pointers are stored inside the free blocks themselves, so the bookkeeping costs no extra memory. Allocation pops the head; deallocation pushes it back: both are constant-time pointer operations. Objects are constructed in a block with placement new and destroyed explicitly before the block returns to the list.
Failure paths. Exhaustion returns null (or an error), and the caller's policy is documented: retry, drop, or fail loudly. Blocking forever inside an allocator on a control path is the answer to argue against. Double-free and use-after-free are the pool's characteristic bugs; a debug build can scan the free list or poison freed blocks to catch them.
Trade-offs. Constant-time allocation and zero fragmentation within the pool, paid for with a hard capacity limit, wasted space when objects vary in size, and code you own. Thread safety is a decision, not a default: a single owning thread needs no lock; sharing the pool across threads adds a mutex on every operation. And a subtle cost worth stating: because the pool sub-allocates inside one big arena, AddressSanitizer no longer sees individual object boundaries unless you poison them manually, so you trade away some tooling coverage. In a test, a 70-byte memset into a 64-byte pool block overran into the next block and AddressSanitizer reported nothing; after ASAN_POISON_MEMORY_REGION (from <sanitizer/asan_interface.h>) was applied to the blocks that were free, the same overrun was reported as use-after-poison.
Verification. An invariant check (allocated plus free always equals N), an exhaustion test, and a randomized alloc/free stress run under the debug checks.
Driving all three out loud, with the constraint-first order and an honest cost statement in each, is the single highest-value preparation you can do for the design portion of an interview.
The mock interview: timed, recorded, scored
3 min readReading about interviews and performing in one are different skills, and only the second is tested. Run a full 60-minute mock on your Ubuntu 24.04 setup (WSL2 or a VM), with a partner as interviewer if you have one, or alone with a voice recorder and a written question list drawn from the question bank lesson. A workable split: 10 minutes of language questions, 20 minutes of systems design (pick one scenario from the previous section, or a variant your partner invents), 25 minutes of timed coding in the style of the previous lesson, and 5 minutes of feedback.
The rules matter more than the questions. Keep a visible timer and do not pause it. Speak your reasoning continuously, because silence scores zero even when your thinking is good. When you are stuck on the coding block, state your intended approach out loud and move to a simpler version rather than freezing: interviewers score a partial working solution with clear reasoning above a silent perfect one that never arrives. You can time each block from the shell:
start=$(date +%s)
# work one timed block here, speaking your reasoning out loud
echo "elapsed seconds: $(( $(date +%s) - start ))"
Score the session against a fixed rubric, five criteria, each 0 to 2: correctness (did the code and the design actually work), constraints (did you ask before assuming), trade-offs (did you name costs and reversal conditions), communication (was the reasoning audible and structured), and time (did each block finish). A partner scores live; alone, score from the recording afterward, which has the extra benefit of letting you hear your own filler phrases and long silences.
Feedback is the product. Write down three things that worked and three concrete fixes, each phrased as an action ("state the memory ceiling before sketching the middleware", not "communicate better"). Then redo the single weakest answer within two days, timed again, and compare. One mock with a scored redo teaches more than three mocks with no feedback, because the loop closes on a specific defect instead of a general feeling of having practiced. Schedule at least two full mocks before the exam session, spaced so the fixes from the first have been drilled before the second.
The next lesson, "The written exam and timed practical", puts everything from this session under exam conditions: the question bank, the timed coding discipline, and the design walkthroughs you rehearsed here, now with a fixed clock and a pass bar.
Key takeaways
- A strong trade-off answer names the constraint, the choice, the cost paid, and what would change the decision
- Design questions are judged on the walkthrough (constraints, structure, failure paths, verification), not on reaching one canonical answer
- A single-threaded event loop trades isolation for simplicity: one slow handler delays every connection
- Mock interviews only pay off when they are timed, recorded, scored against a rubric, and followed by a redo of the weakest answer
Reflect
- Explain to a colleague, in two sentences: defend a design choice using constraints, cost paid, and a reversal condition
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pageepoll(7): the epoll interface
- Man pagemalloc(3): general-purpose heap allocation
- Man pagetimerfd_create(2): timers delivered as file descriptors
Official documentation first. Links checked when the lesson was published.