Building Software
Sections

Contents

Section 3 of 9

The Machine

How Code Actually Runs

4 subsections, the core path through it Core 8–9.

Why it matters when agents do the typing

Every layer of the stack leaks into the layers above it, and those leaks decide speed, cost and correctness. When a service slows down, runs out of memory or corrupts data in the middle of the night, the person paged has to reason from the code down to the machine. Knowing the stack is how you predict what code will do before it runs and explain what it did afterward.

The course: 4 lessons, about 36 minutes of reading, in the order below.

  1. 3.1

    Hardware and the Operating System

    Depth: explain

    What the CPU, memory, storage and operating system actually do when a program runs, and why their costs differ by orders of magnitude.

    A mistake it teaches you to catch: A whole file or table loaded into memory when the job needed to stream it, which works in testing and crashes on real data.

    Lesson: What the Machine Does Under Your Script 10 min

  2. 3.2

    Languages, Compilers and Runtimes

    Core 8 · Depth: explain

    How source code becomes running behavior: parsing, compilation, interpretation, type systems, memory management and concurrency models.

    A mistake it teaches you to catch: A blocking call inside an async handler that stalls every other request on the event loop.

    Lesson: What the Runtime Does With Your Code 8 min

  3. 3.3

    Representing Numbers, Text and Time

    Core 9 · Depth: do

    How computers store integers, decimals, text and timestamps, and the silent errors each representation invites.

    A mistake it teaches you to catch: Money stored and calculated as floating-point numbers, producing totals that are off by a cent.

    Lesson: Every Value Is Stored in Some Encoding 8 min

  4. 3.4

    Networks and Protocols

    Depth: explain

    How machines exchange data, from packets and routing up through DNS, TCP, TLS and HTTP.

    A mistake it teaches you to catch: A state-changing action exposed as a GET request, which link prefetchers and crawlers will trigger.

    Lesson: What Happens Between Two Machines 10 min

Section test: The Machine

10 questions across the 4 lessons above. Take it after the course; each answer explains itself.

  1. 1An agent wraps two kinds of per-item work in Promise.all to speed up an endpoint. About how long does each line of the loop report?
    TypeScript
    const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
    const busy = (ms: number) => { const end = Date.now() + ms; while (Date.now() < end) {} };
    
    const fetchScore = async (id: number) => { await sleep(50); return id; }; // 50 ms waiting on the network
    const computeScore = async (id: number) => { busy(50); return id; };     // 50 ms of CPU, no await
    
    const ids = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    for (const score of [fetchScore, computeScore]) {
      const start = Date.now();
      await Promise.all(ids.map(score));
      console.log(`${score.name}: ${Date.now() - start} ms`);
    }
    Show the answer

    Answer C. Promise.all lets waits overlap: ten 50 ms network waits run at once and finish together after about 50 ms. computeScore has no await, so each call runs its 50 ms of CPU to the end on the one thread before the next starts, ten of them take about 500 ms, and every other request on the server waits too. Overlap helps with round trips and does nothing for computation, which needs a worker thread or another process.

  2. 2Payment IDs above 2^53 came back wrong, so an agent made the ID a bigint all the way from the database to the response. The project type checks under strict. What does the last line do?
    TypeScript
    interface Payment { id: bigint; amountCents: number }
    
    // The database driver now returns BIGINT columns as bigint.
    function paymentBody(p: Payment): string {
      return JSON.stringify(p);
    }
    
    console.log(paymentBody({ id: 9007199254740993n, amountCents: 1250 }));
    Show the answer

    Answer B. JSON.stringify refuses every bigint and throws a TypeError, so this endpoint now fails for every payment, small IDs included. The checker allows it, because JSON.stringify accepts a value of any type. Writing the digits as a bare JSON number would not help either, since the client's JSON.parse rounds 9007199254740993 to 9007199254740992. Send the ID as a string, String(p.id), and keep it a string in the client. The quoted output in the third option is what that conversion produces; nothing writes it for you.

  3. 3A job reads 50,000 uploaded reports in one process, calling this once per file. The caller logs any error and moves on. About 3% of the files are not reports, and the container caps each process at 1,024 open files. What happens?
    TypeScript
    import { openSync, readSync, closeSync } from "node:fs";
    
    function reportVersion(path: string): number {
      const fd = openSync(path, "r");
      const head = Buffer.alloc(8);
      readSync(fd, head, 0, 8, 0);
      if (head.toString("ascii", 0, 4) !== "RPT1") throw new Error(`not a report: ${path}`);
      closeSync(fd);
      return head.readUInt32LE(4);
    }
    Show the answer

    Answer A. The throw skips closeSync, so each bad file leaves its descriptor open. A descriptor is a number the kernel hands out, and the garbage collector reclaims objects with no way to know that a number names an open file, so nothing closes it. Once the process holds 1,024 descriptors, every openSync fails with EMFILE (too many open files), and the job logs an error for each good report that follows. Memory barely moves, since each leak is a slot in the kernel's table for the process. Calling closeSync in a finally block releases the descriptor on every path.

  4. 4A job that held 20 million customer IDs in a plain array was killed with exit code 137. The agent's fix stores them in a typed array at 4 bytes each. Customer IDs passed 2,147,483,647 last month. What does this print?
    TypeScript
    const ids = new Int32Array(3);
    ids[0] = 1_200_000_000;
    ids[1] = 2_147_483_647;
    ids[2] = 3_000_000_000;
    console.log(ids.join(", "));
    Show the answer

    Answer D. An Int32Array slot holds a signed 32-bit integer, and a value that does not fit wraps around with no error: 3,000,000,000 minus 2^32 is -1,294,967,296. The memory saving is real, but that ID now names no customer, or the wrong one. Clamping at the maximum is what a Uint8ClampedArray does, not an Int32Array. A BigInt64Array, or a plain array of numbers, holds IDs this size exactly.

  5. 5An upload gateway rejects request bodies over 1,000,000 bytes with 413. The client checks the size before sending. Which note passes the client's check and is still rejected?
    TypeScript
    function send(note: { text: string }) {
      const body = JSON.stringify(note);
      if (body.length > 1_000_000) throw new Error("note too large");
      return fetch("/api/notes", { method: "POST", body });
    }
    Show the answer

    Answer B. .length counts UTF-16 code units, and fetch sends the string as UTF-8. A kanji is one code unit and 3 UTF-8 bytes, so 400,000 of them pass the check at about 400,000 and arrive as about 1,200,000 bytes. 450,000 copies of é take 2 bytes each, about 900,000 bytes, under the limit. 1,200,000 ASCII letters never leave, because the check catches them. Measuring new TextEncoder().encode(body).length counts what the gateway counts.

  6. 6A report job on a new host logs the error below. db.internal resolves to 10.0.4.12, the database's current address, and the database accepts connections from other hosts. Which explanation fits?
    Output
    Error: connect ETIMEDOUT 10.0.4.12:5432
    Show the answer

    Answer A. The error is the kernel's answer to connect. ETIMEDOUT means the handshake's SYN never got a SYN-ACK back, which is what a firewall or security group that drops packets produces. A host where nothing listens answers at once with a refusal, ECONNREFUSED. A password is checked only after the TCP connection exists, and the address in the error is the current one, so DNS has already done its part.

  7. 7The handler calls geocode and serves a fallback when it throws. The geocoder starts accepting connections and never answering, at 20 calls a second. Users get the fallback after 3 seconds. What keeps growing?
    TypeScript
    const timeout = (ms: number) =>
      new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timeout")), ms));
    
    async function geocode(address: string) {
      return Promise.race([
        fetch(GEOCODER_URL, { method: "POST", body: address }),
        timeout(3000),
      ]);
    }
    Show the answer

    Answer D. Promise.race settles when the first promise does, but the fetch that lost keeps running and holds its connection and memory until it gives up on its own, which for Node's fetch is five minutes waiting for headers. At 20 calls a second that is thousands of open requests. Passing signal: AbortSignal.timeout(3000) to fetch aborts the request itself. Pending I/O does not block the event loop; it holds resources.

  8. 8The orders service goes down, and the load balancer in front of it answers every request with 503 and an HTML error page. What does a call to loadOrder do?
    TypeScript
    async function loadOrder(id: string): Promise<Order> {
      const res = await fetch(`${ORDERS_API}/orders/${id}`, { signal: AbortSignal.timeout(2000) });
      return (await res.json()) as Order;
    }
    Show the answer

    Answer C. fetch resolves for any HTTP response, error statuses included, and rejects only when no response arrives. res.json() then tries to parse an HTML page and throws a SyntaxError, so the log points at parsing while the cause is a 503 from the load balancer. Checking res.ok before parsing, and throwing an error that carries the status, keeps the real cause in the log. The as Order cast is erased and checks nothing at runtime.

  9. 9The report service starts answering 500 with a JSON error body. What does this script do?
    Shell
    #!/usr/bin/env bash
    set -euo pipefail
    
    curl -s https://reports.internal/export > export.json
    upload export.json
    Show the answer

    Answer B. An HTTP 500 is a complete response, and without --fail curl exits 0 for it and writes the error body to export.json. set -e sees success, and upload sends the error as the export. pipefail concerns pipelines, and there is none here. curl --fail turns a 4xx or 5xx status into exit code 22, and then set -e stops the script before upload.

  10. 10This picks which day's sales report a nightly job builds. It ran every night in March 2026, and US clocks moved forward at 02:00 on 8 March. Which day's report was never built?
    TypeScript
    const DAY = 86_400_000;
    const localDate = (d: Date) =>
      `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
    
    // Runs at 00:30 every night on a server set to America/Los_Angeles.
    function reportDate(now: Date): string {
      return localDate(new Date(now.getTime() - DAY));
    }
    Show the answer

    Answer A. 8 March was 23 hours long in Los Angeles. At 00:30 on 9 March, 24 hours earlier is 23:30 on 7 March, so that run built 7 March a second time and 8 March was skipped. A fixed 86,400,000 ms is one day only when the local day has 24 hours. Subtracting one calendar day from the local date gives 8 March.