Building Software
Sections

Contents

Section 6 of 9

Design

Structuring Systems That Stay Understandable

6 subsections, the core path through it Core 14–15.

Why it matters when agents do the typing

Code gets cheaper to produce every year, so complexity piles up faster than anyone can read it, and the team that owns the system still has to change it safely. Good structure (small interfaces, clear boundaries, each rule in one place) keeps a system understandable enough to verify. A well-bounded module can be understood, tested and replaced on its own.

The course: 6 lessons, about 51 minutes of reading, in the order below.

  1. 6.1

    Managing Complexity

    Depth: do

    Coupling, cohesion, information hiding and simplicity: the principles that decide whether a codebase gets easier or harder to change over time.

    A mistake it teaches you to catch: A factory, an interface and a configuration loader added for a feature that has exactly one implementation.

    Lesson: The price of the next change 9 min

  2. 6.2

    Components and Architecture

    Depth: explain

    How a system is divided into modules and services, which way dependencies point, and how the parts communicate.

    A mistake it teaches you to catch: Business rules written directly inside HTTP handlers or UI components, where they can't be reused or tested alone.

    Lesson: Which way the arrows point 9 min

  3. 6.3

    Interfaces and APIs

    Depth: do

    Designing the contracts between parts of a system and between systems: shapes, errors, versions and limits.

    A mistake it teaches you to catch: A breaking change to a public API, such as a renamed field or changed type, shipped without a version or a migration path.

    Lesson: The promise an API makes 8 min

  4. 6.4

    Error Handling and Failure Paths

    Core 14 · Depth: do

    Deciding what happens when things go wrong: which errors to handle, which to pass up, and which should stop the program.

    A mistake it teaches you to catch: A catch-all handler that logs the error and returns a default value, so failures look like successes.

    Lesson: What the Caller Sees When Something Breaks 10 min

  5. 6.5

    Where Logic Meets the Database

    Core 15 · Depth: do

    The boundary between application code and storage: where business rules live, what queries get generated, and how the two stay consistent.

    A mistake it teaches you to catch: N+1 queries: one query for a list and then one more for every item, usually hidden inside an ORM's lazy loading.

    Lesson: The Queries Behind Your Code 9 min

  6. 6.6

    Frontend and Backend

    Depth: explain

    Splitting responsibility between the user interface and the server: where state lives, where checks run, and how the two talk.

    A mistake it teaches you to catch: Authorization, pricing or discount logic enforced only in the browser, where any user can change it.

    Lesson: The Browser Belongs to the User 6 min

Section test: Design

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

  1. 1During a database failover, queries fail with Connection terminated unexpectedly for a few seconds, and this handler answers. What does a client that follows the status codes do?
    TypeScript
    // The one error handler for the public API. Every endpoint throws on failure.
    app.use((err: Error, req: Request, res: Response, _next: NextFunction) => {
      res.status(400).json({ error: err.message });
    });
    Show the answer

    Answer B. A 400 tells the client its request is wrong, so a client that follows the status code drops a request that would succeed a few seconds later. Errors should be translated at this boundary: known errors to their own codes, and anything unexpected to a 500 or 503 with a problem body and a request ID, with the detail kept in the server's log. This handler also sends err.message to every client, which can expose driver and SQL details.

  2. 2How many queries does one load of the recent-orders list send, and which fix keeps the customers module the only code that reads its table?
    TypeScript
    // customers/index.ts: the only module that reads the customers table
    export async function customerName(id: number): Promise<string> {
      const c = await customerRepo.findOneByOrFail({ id });
      return c.name;
    }
    
    // orders/recent.ts
    const orders = await orderRepo.find({ order: { createdAt: "DESC" }, take: 50 });
    const rows = await Promise.all(
      orders.map(async (o) => ({ id: o.id, customer: await customerName(o.customerId) })),
    );
    Show the answer

    Answer D. Promise.all runs the 50 lookups at the same time, but each is still its own query, so the page sends the orders query plus 50 more. A join in the orders code would fix the count and make it a second reader of the customers table, so a column change there could break orders. A batch function on the owning module keeps the table behind one interface and sends two queries for any page size.

  3. 3The client handles loading, error, empty and ready states, and its tests pass. Then the orders database goes down. What does a customer with 12 orders see?
    TypeScript
    // server
    app.get("/api/orders", requireLogin, async (req, res) => {
      try {
        res.json(await ordersFor(req.user.id));
      } catch (err) {
        log.error(err);
        res.json([]);
      }
    });
    
    // client, inside the Orders component; "ready" with no orders
    // renders "You have no orders yet."
    fetch("/api/orders", { signal: AbortSignal.timeout(10_000) })
      .then(async (r) => {
        if (!r.ok) throw new Error(`HTTP ${r.status}`);
        return (await r.json()) as Order[];
      })
      .then((orders) => setState({ kind: "ready", orders }))
      .catch(() => setState({ kind: "error", message: "We couldn't load your orders." }));
    Show the answer

    Answer B. The server's catch block logs the failure and answers 200 with an empty list, which is also the correct answer for a customer with no orders. From the client's side nothing failed, so its error handling never runs and it shows the empty state. Error states in the interface only work when the server reports a failure as one: let the error reach the API's error handler and answer with a 5xx.

  4. 4So that slow renders stop holding requests open, an agent moved PDF rendering onto a queue and changed this endpoint's response, still under /v1. Which describes the change?
    Output
    POST /v1/invoices/inv_81/pdf
    
    before the change:
    HTTP/1.1 200 OK
    {"url": "https://files.example.com/inv_81.pdf"}
    
    after the change:
    HTTP/1.1 202 Accepted
    {"job_id": "job_4410"}
    Show the answer

    Answer C. A client built against the old response reads url from a 2xx body, and that field is gone, so it fails or carries undefined forward. With a queue the request ends before the PDF exists, so the caller can no longer get the result in the same call, and that is a different contract. A different contract needs a new endpoint or version that clients opt into, while the old one keeps working until they move.

  5. 5Support wants a report of how last month's 4,000 tickets would be prioritized under a proposed change to the rule. The agent plans to run triage on each old ticket against a copy of the database. What should the review ask for?
    TypeScript
    // tickets/triage.ts
    export async function triage(ticket: Ticket): Promise<Priority> {
      const customer = await db.customers.get(ticket.customerId);
      const urgent = customer.plan === "enterprise" || /outage|down|data loss/i.test(ticket.body);
      const priority: Priority = urgent ? "urgent" : "normal";
      await db.tickets.update(ticket.id, { priority });
      if (urgent) await pager.page("support-on-call", ticket.id);
      return priority;
    }
    Show the answer

    Answer C. triage decides and acts in one call, so a caller that only wants the decision also gets the write and the page. Pointed at a database copy, it still calls the real pager, once for every old ticket the rule calls urgent. A dryRun flag works today, but every step added to triage later has to remember to check it, and one that forgets acts for real during a report. A copied condition drifts the first time someone changes the rule in one place. A function that only computes the priority keeps the rule in one place and can be tested without a database or a pager.

  6. 6A user picks a new username and an email that already has an account. What does the user see, and what should the catch do instead?
    TypeScript
    // accounts has unique indexes on lower(username) and on lower(email)
    async function createAccount(username: string, email: string) {
      try {
        return await accountRepo.insert({ username, email });
      } catch {
        throw new UsernameTaken(username);
      }
    }
    Show the answer

    Answer A. The catch turns every failure into UsernameTaken, including the email collision, a dropped connection or a bug, so the user is told to change the one field that was fine. PostgreSQL does report which index was hit, as error 23505 with the constraint's name, but this code never looks. Map each violation it knows to its own message, and let everything else propagate to the boundary, where it becomes a 500 and a log entry.

  7. 7An agent built a company directory page. It was fast in development with 60 test users. The largest customer has 40,000 employees, and each viewer works in one department. What should the review ask for?
    TypeScript
    // Directory page. GET /api/users returns every employee:
    // name, email, department and title.
    const res = await fetch("/api/users");
    const everyone: User[] = await res.json();
    const colleagues = everyone.filter((u) => u.department === viewer.department);
    renderList(colleagues);
    Show the answer

    Answer C. Every load downloads and parses all 40,000 employees to show one department, and that cost grows with the customer. Virtualization only cuts the cost of drawing rows, and the download and parsing stay the same. A browser cache still fetches everything once per session and goes stale when people join or move. The query should select the viewer's department, and the endpoint should take a limit with a maximum and a cursor, so each response stays small however large the company gets.

  8. 8A user asks to delete their account, and the file store times out during files.deleteAll before deleting anything. What happens, and what should the review ask for?
    TypeScript
    // utils.ts, imported by 70 files
    export async function safe<T>(fn: () => Promise<T>): Promise<T | null> {
      try {
        return await fn();
      } catch (err) {
        console.error(err);
        return null;
      }
    }
    
    // delete-account.ts, in the agent's diff
    // files.deleteAll(userId: string): Promise<number> removes the user's uploads
    await safe(() => files.deleteAll(user.id));
    await users.remove(user.id);
    Show the answer

    Answer A. safe returns null on any failure and the code ignores the result, so users.remove runs and the account disappears while its uploads stay in storage. The only trace is a console line, and nothing records that the deletion is unfinished. The storage error should propagate so the request fails and can be retried, with the user row removed last. Because safe lives in a module 70 files import, a retry added inside it would change all 70 callers at once, including ones that are not safe to repeat, such as a call that sends an email.

  9. 9A project has 300 events, and its 90 task.closed events are all older than its newest 120. A client asks for ?kind=task.closed&limit=50. What does the first response hold?
    TypeScript
    app.get("/v1/projects/:id/events", async (req, res) => {
      const limit = parseLimit(req.query.limit); // 1 to 100, default 50
      const before = decodeCursor(req.query.cursor) ?? Number.MAX_SAFE_INTEGER;
      const { rows } = await db.query(
        "SELECT id, kind, created_at FROM events WHERE project_id = $1 AND id < $2 ORDER BY id DESC LIMIT $3",
        [req.params.id, before, limit],
      );
      const data = req.query.kind ? rows.filter((e) => e.kind === req.query.kind) : rows;
      const next_cursor = rows.length === limit ? encodeCursor(rows[rows.length - 1].id) : undefined;
      res.json({ data, next_cursor });
    });
    Show the answer

    Answer D. The query takes the newest 50 events of any kind, and the filter then drops all of them, so data is empty while the cursor points further back. The second page is empty too, and matches can only start on the third page or later. A client that treats an empty page as the end never sees them. Put kind in the WHERE clause, with an index that covers it, so each page holds up to 50 matches and an empty page means none are left.

  10. 10The API team adds an on_hold order status and starts returning it from GET /v1/orders. The app calls statusLabel while rendering each order and has no error boundary. What happens?
    TypeScript
    // Mobile app 4.2, still installed on most customers' phones.
    function statusLabel(status: string): string {
      switch (status) {
        case "pending": return "Pending";
        case "shipped": return "On its way";
        case "delivered": return "Delivered";
        default: throw new Error(`unknown order status: ${status}`);
      }
    }
    Show the answer

    Answer C. The default branch throws during render, and with no error boundary nothing catches it, so a customer with a held order gets a blank screen or a crashed app until they update. A new enum value breaks clients that treat unknown values as errors, so the API should ship it in a new version or a field old clients never read. An unknown value from a server is also a case to expect rather than an impossible state, so the app should show a neutral label instead of throwing.