Building Software
Sections

Contents Section 6, Design

Components and Architecture

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

Section 6 of 9, subsection 2 of 6. Depth: explain. A 9-minute read.

Mistakes to catch in review

  1. Business rules written directly inside HTTP handlers or UI components, where they can't be reused or tested alone.

  2. A small application split into many services, adding network failures and deployment overhead for no benefit.

  3. Code in every module reaching straight into the database instead of going through the component that owns that data.

Which way the arrows point

You ask an agent to add refunds to a small event-booking app. Customers who cancel at least 72 hours before the event get their money back, between 24 and 72 hours they get half, and inside 24 hours they get nothing. The agent returns this handler, which computes the refund and records it on the booking. The call to the payment provider that would move the money is left out of the example, and a booking inside 24 hours is still marked refunded, with a refund of zero.

TypeScript
app.post("/bookings/:id/refund", async (req, res) => {
  const { rows } = await pool.query(
    "SELECT id, price_cents, event_starts_at, status FROM bookings WHERE id = $1",
    [req.params.id],
  );
  const booking = rows[0];
  if (!booking) return res.status(404).json({ error: "not found" });
  if (booking.status === "refunded") return res.status(409).json({ error: "already refunded" });

  const hoursLeft = (booking.event_starts_at.getTime() - Date.now()) / 3_600_000;
  let refundCents = 0;
  if (hoursLeft >= 72) refundCents = booking.price_cents;
  else if (hoursLeft >= 24) refundCents = Math.floor(booking.price_cents / 2);

  await pool.query(
    "UPDATE bookings SET status = 'refunded', refund_cents = $2 WHERE id = $1",
    [booking.id, refundCents],
  );
  res.json({ refundCents });
});

A week later support asks for an admin tool that cancels a booking on a customer's behalf, and it has to apply the same refund rule. The rule lives inside an HTTP handler, so the tool can't call it. The agent will copy the rule into the tool, and now the rule that decides how much money goes back to customers exists twice. Testing the rule where it sits means calling the handler with a stubbed database pool and request and faking the clock, because Date.now() is read in the middle of it.

None of this is visible in the feature's own tests. It becomes visible when the second caller arrives.

Components and dependencies

A component is a group of code with a job and a surface: the functions, types or endpoints other code is allowed to use. A dependency is a relationship between two components: A depends on B when A imports B, calls B, or reads B's data. The practical meaning is that A may have to change when B changes.

That makes the direction of each dependency a design decision. If the refund rule depends on the web framework, a framework upgrade can break refund logic. If the web handler depends on the refund rule, the rule can be tested, reused and changed without touching the web layer at all. The arrow should point from the part that changes for incidental reasons (frameworks, databases, delivery mechanisms) toward the part that holds the business's decisions.

Here is the same feature with the rule pulled out into a component that knows nothing about HTTP or SQL. The rule is the customer-cancellation policy, and its name says so.

TypeScript
// src/bookings/refund-policy.ts
export type Booking = {
  id: string;
  priceCents: number;
  eventStartsAt: Date;
  status: "active" | "refunded";
};

export function customerCancellationRefundCents(booking: Booking, now: Date): number {
  const hoursLeft = (booking.eventStartsAt.getTime() - now.getTime()) / 3_600_000;
  if (hoursLeft >= 72) return booking.priceCents;
  if (hoursLeft >= 24) return Math.floor(booking.priceCents / 2);
  return 0;
}

now is passed in, so a test can ask what happens at exactly 72 hours without waiting three days. The rule is a plain function of its inputs, so a test supplies only a booking and a time, and the web handler and the support tool can both call it.

Only a customer's own cancellation may call it. If the organizer cancels an event, the policy is a different rule (most likely a full refund at any time), and it belongs in its own function beside this one. A flag on this function that switches between the two policies would bring back the problem the extraction solved.

Ports and adapters

The rule still has to load and save bookings. If the bookings component imports the Postgres driver to do that, the arrow points back toward the database. The fix is for the bookings component to state what it needs from storage, in its own terms, and let something outside supply it.

TypeScript
// src/bookings/booking-store.ts
export interface BookingStore {
  get(id: string): Promise<Booking | null>;
  // Returns false if the booking was already refunded.
  markRefunded(id: string, refundCents: number): Promise<boolean>;
}

// src/bookings/refund-booking.ts
export async function refundCustomerCancellation(store: BookingStore, id: string, now: Date) {
  const booking = await store.get(id);
  if (!booking) return { kind: "not_found" } as const;
  const cents = customerCancellationRefundCents(booking, now);
  const changed = await store.markRefunded(id, cents);
  if (!changed) return { kind: "already_refunded" } as const;
  return { kind: "refunded", cents } as const;
}

The interface is called a port, and a class that implements it against a real system is an adapter. The Postgres adapter lives outside the bookings folder and implements markRefunded with UPDATE ... WHERE id = $1 AND status = 'active', returning whether a row changed, so two simultaneous refund requests can't both succeed. The web handler becomes a thin adapter too: it turns a request into a call to refundCustomerCancellation and turns the result into a status code.

Output
web handler ───────▶ refundCustomerCancellation ───▶ customerCancellationRefundCents
support tool ──────▶ refundCustomerCancellation
postgres adapter ──▶ BookingStore (interface owned by bookings)

Every arrow points into the bookings component. Alistair Cockburn called this arrangement hexagonal architecture, and layered designs that keep the core free of framework code make the same move under other names.

There is a tension here with the usual advice against interfaces that have one implementation.

This port has two from the start: the Postgres adapter and an in-memory fake that tests use. It also sits at a boundary with an external system, which is where a swap is likely. An interface earns its keep when it stands between your rules and something you don't control. An interface between two pieces of your own code that always change together only adds a file.

The in-memory fake is also the quickest way to see why markRefunded checks the status itself. This playground sends two refund requests for the same booking at the same moment. The first function reads the booking, checks its status in code and then writes, which is what the original handler did. The second goes through the port.

TypeScriptRuns in your browser
type Booking = { id: string; priceCents: number; eventStartsAt: Date; status: "active" | "refunded" };

function customerCancellationRefundCents(booking: Booking, now: Date): number {
  const hoursLeft = (booking.eventStartsAt.getTime() - now.getTime()) / 3_600_000;
  if (hoursLeft >= 72) return booking.priceCents;
  if (hoursLeft >= 24) return Math.floor(booking.priceCents / 2);
  return 0;
}

const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));

// An in-memory adapter. The short sleeps stand in for database round trips.
class InMemoryBookingStore {
  private rows = new Map<string, Booking>();
  refundedCents = 0;
  constructor(bookings: Booking[]) {
    for (const b of bookings) this.rows.set(b.id, { ...b });
  }
  async get(id: string): Promise<Booking | null> {
    await sleep(5);
    const row = this.rows.get(id);
    return row ? { ...row } : null;
  }
  // Like UPDATE ... SET status = 'refunded' WHERE id = $1, with no status condition.
  async saveRefunded(id: string, refundCents: number): Promise<void> {
    await sleep(5);
    this.rows.get(id)!.status = "refunded";
    this.refundedCents += refundCents;
  }
  // Like UPDATE ... WHERE id = $1 AND status = 'active': the check and the write are one step.
  async markRefunded(id: string, refundCents: number): Promise<boolean> {
    await sleep(5);
    const row = this.rows.get(id);
    if (!row || row.status !== "active") return false;
    row.status = "refunded";
    this.refundedCents += refundCents;
    return true;
  }
}

// The original handler's order: read, check the status in code, then write.
async function checkThenWrite(store: InMemoryBookingStore, id: string, now: Date) {
  const booking = await store.get(id);
  if (!booking) return "not_found";
  if (booking.status === "refunded") return "already_refunded";
  const cents = customerCancellationRefundCents(booking, now);
  await store.saveRefunded(id, cents);
  return `refunded ${cents}`;
}

// The port version from this lesson.
async function refundCustomerCancellation(store: InMemoryBookingStore, id: string, now: Date) {
  const booking = await store.get(id);
  if (!booking) return "not_found";
  const cents = customerCancellationRefundCents(booking, now);
  const changed = await store.markRefunded(id, cents);
  return changed ? `refunded ${cents}` : "already_refunded";
}

const now = new Date("2026-03-01T12:00:00Z");
const booking: Booking = { id: "b_1", priceCents: 5000, eventStartsAt: new Date("2026-03-05T12:00:00Z"), status: "active" };

for (const refund of [checkThenWrite, refundCustomerCancellation]) {
  const store = new InMemoryBookingStore([booking]);
  const results = await Promise.all([refund(store, "b_1", now), refund(store, "b_1", now)]);
  console.log(refund.name, results, "cents refunded in total:", store.refundedCents);
}
Two rows, each showing requests A and B against the same booking, left to right in time. Top row, Check, then write (checkThenWrite): A get and B get both see active, then A write and B write both call saveRefunded, and both arrows meet at Refunded twice, full refund recorded twice. Bottom row, Through the port: A get and B get both see active, then A markRefunded returns true and B markRefunded returns false, and both arrows meet at the highlighted Refunded once, B gets already_refunded. Notes read: both read before either writes; check and write in one step.
Read each row left to right in time order. Checking in code lets both requests act on the same stale read; when the store checks and writes in one step, the second markRefunded returns false and the refund is recorded once.

The first version records a full refund twice on a 5,000-cent booking, because both requests read active before either one wrote. The second records it once. Its check and write happen in one step inside the store, which is the job the AND status = 'active' condition does in the Postgres adapter. Because now is a parameter, the playground fixes the time at four days before the event instead of reading the clock.

One owner for each piece of data

The same app has a notifications module that emails attendees and a reporting module that sums revenue. An agent adding a feature to either one will usually write the query it needs directly.

TypeScript
// src/reports/revenue.ts
const { rows } = await pool.query(
  "SELECT SUM(price_cents - COALESCE(refund_cents, 0)) AS net FROM bookings WHERE status IN ('active', 'refunded')",
);

This query depends on the column names in bookings, on the meaning of refund_cents, and on the full list of status values. The bookings module can no longer change any of those without breaking reporting, and it has no way to know reporting exists. Worse, any rule the bookings module enforces on writes, such as "a refunded booking can't be refunded again", can be bypassed by a module that runs its own UPDATE.

The fix is that each table has one owning component, and other components ask the owner. Reporting calls a function the bookings module exports, such as netRevenueCents(eventId). The query moves into bookings, next to the code that knows what the columns mean. The question that exposes the problem in review is "who else reads or writes this table?", and you can answer it mechanically:

Shell
grep -rnE "(FROM|JOIN|UPDATE|INTO) bookings" src | grep -v "^src/bookings/"

Treat each line that prints as a candidate for review. It may be a module reaching past the owner, or the owner's own storage adapter, which lives outside the folder in this design, or a comment that mentions the table.

When a function call becomes a network call

Everything so far lives in one deployable program with clear internal boundaries, often called a modular monolith. The alternative is to put components in separate services that talk over the network. That split changes what every call between them costs and how it can fail.

A function call inside one process involves no transport and no serialization, which is why it typically takes nanoseconds, though it can still block or throw. A call to another service in the same data center costs a network round trip, commonly cited as around half a millisecond before any serialization or HTTP handling, and it can end in more ways.

The call can fail outright, or time out, or succeed on the far side while the reply is lost, so the caller doesn't know whether the refund happened.

Two lanes. Top lane, One process: Caller has an arrow labelled nanoseconds to Refund rule, a function call. Bottom lane, Over the network: Caller has an arrow labelled around half a millisecond to a highlighted Refund service, another service, which fans out to three outcomes: Fails outright, Times out, and Reply lost, did the refund happen? A note reads: more ways to end.
Inside one process the call costs nanoseconds. Across the network it costs a round trip and can fail outright, time out, or lose its reply, and when the reply is lost the caller cannot tell whether the refund happened.

Availability multiplies across a chain. If a request has to pass through three services in a row and each one is up 99.9% of the time, and their failures are independent, the request succeeds 0.999 × 0.999 × 0.999 ≈ 99.7% of the time. That is roughly 26 hours of failure a year, against about 9 for one service. Retries and timeouts can win some of that back, but each one is code you now have to write and test.

A Request pill flows through Service 1, Service 2 and Service 3 in a row, each up 99.9%. Service 3 points to a highlighted result box reading about 99.7%, about 26 hours of failure a year. A note reads: availability multiplies.
With independent failures, a request that must pass three services each up 99.9% of the time succeeds about 99.7% of the time: roughly 26 hours of failure a year, against about 9 for one service.

Two other things break. Charging a card already sits outside your database transaction, so that step can half-succeed in a monolith too. What changes is that a local transaction cannot span two services that each own a database: "record the payment" in billing and "mark the booking paid" in bookings can no longer commit together. And each service needs its own build, deploy, monitoring and versioned API, so a change that touches two services becomes two coordinated releases.

Splitting pays when a component needs something only a process boundary can give it. Examples: one part needs to scale very differently from the rest, a separate team needs to deploy on its own schedule, or a part handles data like card numbers that you want isolated behind its own access controls and audit. Martin Fowler's MonolithFirst notes that systems which succeeded with microservices mostly started as monoliths, partly because the right boundaries only become clear once the domain is understood.

Decision flow. A New capability pill leads to a diamond, Same data? and same reasons to change. Yes, upward, leads to Existing module, it belongs there. No, its own data, leads right to a second diamond, Independent? scaling, deploy or isolation. No, upward, leads to New module, same program. Yes, downward, leads to a highlighted Separate service, name the need. A note reads: only then a separate service.
A new capability joins an existing module when it shares that module's data and reasons to change. Otherwise it is a new module in the same program, and it becomes a separate service only when it needs independent scaling, deployment or isolation.

When a new capability arrives, three questions place it. Does it use the same data and change for the same reasons as an existing module? Then it belongs in that module.

Does it bring its own data and its own reasons to change? Then it is a new module in the same program. Does it need independent scaling, deployment or isolation that a module boundary can't provide? Only then is it a separate service, and you should be able to name which of those it needs.

Synchronous calls and queued messages

When a booking is confirmed, the app sends a confirmation email. The simplest version calls the email provider inside the request. If the provider takes ten seconds, so does booking. If the provider is down, you have to decide whether a booking that was saved should report failure because its email didn't send.

Putting a message on a queue instead, and letting a worker send the email later, fixes that coupling in time. It also changes several things you now have to handle:

  • The request finishes before the email is sent, so the caller can no longer report whether it was.
  • Most queues deliver each message at least once, which means sometimes twice, so the worker has to recognize a repeat, usually by recording which booking IDs it has already handled.
  • Messages can arrive in a different order than they were sent.
  • Failures move out of the user's request and into the worker, so someone has to watch the queue of messages that failed repeatedly, or they fail silently.
  • Saving the booking and enqueuing the message are two writes to two systems. If the process crashes between them, you lose the email or send one for a booking that doesn't exist. The usual fix, called an outbox, writes the message into a database table in the same transaction as the booking and has a separate process publish it.

In this playground the worker sends the email and then crashes before it tells the queue the message is done, so the queue delivers the same message again:

TypeScriptRuns in your browser
type Message = { bookingId: string; deliveries: number };
type Worker = (msg: Message) => Promise<void>;

const emailsSent: string[] = [];
const sendConfirmationEmail = async (bookingId: string) => {
  await new Promise((r) => setTimeout(r, 5));
  emailsSent.push(bookingId);
};

// A queue that delivers at least once. The first time, the worker finishes its
// work but crashes before acknowledging, so the queue hands the message out again.
async function runQueue(worker: Worker): Promise<string[]> {
  emailsSent.length = 0;
  const queue: Message[] = [{ bookingId: "b_17", deliveries: 0 }];
  while (queue.length > 0) {
    const msg = queue.shift()!;
    msg.deliveries++;
    await worker(msg);
    if (msg.deliveries === 1) queue.push(msg); // crashed before the acknowledgement
  }
  return [...emailsSent];
}

const sendsEveryTime: Worker = async (msg) => {
  await sendConfirmationEmail(msg.bookingId);
};

const handled = new Set<string>(); // in production, a table keyed by booking ID
const skipsRepeats: Worker = async (msg) => {
  if (handled.has(msg.bookingId)) return;
  await sendConfirmationEmail(msg.bookingId);
  handled.add(msg.bookingId);
};

console.log("sends every time:", await runQueue(sendsEveryTime));
console.log("skips repeats:   ", await runQueue(skipsRepeats));

The first worker sends the customer two confirmations for one booking. The second sends one. A crash in the moment between sending and recording the ID would still send twice, so the record shrinks that window without closing it.

A queue is the right choice when the caller doesn't need the result to continue. It removes the waiting and moves the failure handling somewhere else, where you still have to build it.

Keeping boundaries after you draw them

A boundary drawn once gets crossed within weeks, especially when several agents work in the same codebase and each one takes the shortest path to a passing test. A check that runs in the build turns a crossing into a failing test that names the file. This small test is a quick review aid, and it can be fooled by dynamic imports, by imports re-exported through another module, and by a package name that appears in a comment or string.

TypeScript
import { test, expect } from "bun:test";
import { Glob } from "bun";

const forbidden = ["express", "pg"];

test("the bookings core imports no framework or database driver", async () => {
  const offenders: string[] = [];
  for await (const file of new Glob("src/bookings/**/*.ts").scan(".")) {
    const source = await Bun.file(file).text();
    for (const pkg of forbidden) {
      if (new RegExp(`(?:from|import|require\\()\\s*["']${pkg}["']`).test(source)) offenders.push(`${file} imports ${pkg}`);
    }
  }
  expect(offenders).toEqual([]);
});

Tools such as dependency-cruiser for JavaScript, ArchUnit for Java and import-linter for Python parse the code instead of matching text, and they are what enforce a boundary. They also express richer rules, including "only the bookings folder may touch the bookings table's repository". Either way, an agent gets a failing test, with a file name, the moment it takes the shortcut.

The rule

Draw an arrow for each dependency a diff adds. Business rules should have arrows pointing into them and none pointing out toward frameworks, drivers or other modules' tables, and each network hop between them should be justified by a need you can name that a module boundary in one program couldn't meet.

Check your understanding

6 questions on this lesson. Pick an answer to see whether it holds and why.

  1. 1An agent put the loyalty discount rule here. A nightly billing job now needs the same rule. What should change?
    TypeScript
    // src/pricing/discounts.ts
    import type { Request } from "express";
    
    export function loyaltyDiscount(req: Request): number {
      const years = Number(req.query.years);
      return years >= 5 ? 0.1 : 0;
    }
    Show the answer

    Answer C. The rule depends on Express only because it reads its input from a request. Once it takes a plain number, the arrow points from the handler into the rule, and the job, the handler and a test can all call it. A fake Request works, but it keeps the rule tied to a web framework that a billing job has nothing to do with.

  2. 2The bookings module moves the event start time out of bookings and into a new events table, and its own tests pass. What happens to this reminder job in the notifications module?
    TypeScript
    // src/notifications/reminders.ts
    const { rows } = await pool.query(
      `SELECT u.email FROM bookings b JOIN users u ON u.id = b.user_id
       WHERE b.status = 'active' AND b.event_starts_at < now() + interval '1 day'`,
    );
    Show the answer

    Answer A. The query is a string, so the compiler never looks inside it, and Postgres tracks dependencies from views, not from queries other programs send. The bookings module had no way to know this reader existed. If notifications asked a function the bookings module exports, the move would have been a change inside one module.

  3. 3Checkout used to call the invoice generator directly and wait for the PDF. It now puts an invoice.requested message on a queue with at-least-once delivery. What does the design have to handle that it did not before?
    Show the answer

    Answer B. At least once means sometimes twice, so the worker has to recognize a repeat, for example by recording which order IDs it has already invoiced. The first option is backwards: the queue is what lets checkout succeed while the generator is down, because nothing waits for it.

  4. 4Your app is one program with bookings, events and reporting modules, owned by one team that deploys daily. Marketing wants discount codes: new tables for codes, limits and usage counts, managed from an admin screen and applied at checkout. Where should the code live?
    Show the answer

    Answer B. Discount codes bring their own data and change for their own reasons, which makes them a new module, and nothing here needs separate scaling, deployment or isolation. A separate service would not protect checkout either: checkout still waits on it, so its outage still fails checkout, now with a network hop added.

  5. 5This call used to be an in-process function call. An agent moved inventory into its own service. Which outcome can the caller now hit that it could not before?
    TypeScript
    // HTTP POST to the inventory service, with a 2-second timeout
    const reserved = await inventoryClient.reserve(orderId, items);
    Show the answer

    Answer D. A reply can be lost after the other side has done the work, so a timeout leaves the outcome unknown, and retrying blindly may reserve the stock twice. Throwing is the tempting answer, but the in-process function could already throw; the unknown result is what the network adds.

  6. 6An agent adds this line to src/bookings/refund-booking.ts. The boundary test from the lesson matches each file against the pattern (?:from|import|require\()\s*["']pg["']. What happens when the test runs?
    TypeScript
    const { Pool } = await import("pg");
    Show the answer

    Answer C. The pattern allows only spaces between import and the opening quote, so import("pg") slips past it. A tool that parses the code, such as dependency-cruiser, sees a dynamic import as an import and would catch it. A text match is a quick review aid; a parser is what enforces the boundary.

You understand it when you can

Drill

An agent split a small internal tool into four services (users, projects, notifications and billing) that call each other over HTTP, and put the billing rules inside the web request handler. Find the failure modes the split introduced and say where the billing rules should live instead.

Topics

Layers and Dependency Direction
Keeping core logic independent of frameworks, databases and delivery mechanisms.
Modular Monoliths and Services
When one deployable with strong internal boundaries beats many services, and when splitting pays for itself.
Ports and Adapters
Isolating external systems behind interfaces so they can be swapped, faked in tests or replaced.
Synchronous and Asynchronous Communication
Direct calls, queues and events, and the coupling and failure modes each one creates.
Enforcing Boundaries
Module rules, dependency checks and architecture tests that keep boundaries intact across many hands and many agents.

Further reading

Start here

Short reads

  • Deconstructing the Monolith. Kirsten Westeinde, 2019.

    How a large company drew boundaries inside one codebase instead of splitting it into services.

  • Don't start with a monolith. Stefan Tilkov, 2015.

    The case for drawing service boundaries early, a useful counterweight to starting with one program.

  • The Law of Leaky Abstractions. Joel Spolsky, 2002.

    Every abstraction leaks the thing under it, so you still have to understand the layer below.

Watch

  • Modular Monoliths • Simon Brown • GOTO 2018. Simon Brown, 2018. 47-minute talk.

    Brown shows how to package one deployable by component instead of by layer, so boundaries are enforced in code instead of by a network hop, and why a messy monolith turns into messy microservices.

  • Hexagonal Architecture (Alistair Cockburn). Alistair Cockburn, 2024. 56-minute lecture.

    The pattern's creator explains ports and adapters: why core logic must not depend on UI, database or framework, and the real costs of the extra indirection.

Books

  • Fundamentals of Software Architecture: A Modern Engineering Approach. Mark Richards and Neal Ford, 2025, 2nd edition.

    Covers component identification, the layered, modular-monolith, event-driven and microservices styles with explicit trade-off ratings, and architectural governance to keep boundaries intact.

  • Balancing Coupling in Software Design. Vlad Khononov, 2024.

    Gives a model for judging coupling by the knowledge shared between components, their distance and how often they change, which explains when splitting a component into services lowers coupling and when it only makes it more distributed.

  • Building Microservices: Designing Fine-Grained Systems. Sam Newman, 2021, 2nd edition.

    The chapters on modelling service boundaries, synchronous versus event-driven communication, and data ownership explain what changes, and what can fail, once a call crosses a network.

Primary sources

  • Hexagonal Architecture (Alistair Cockburn). Reference.

    Cockburn's original write-up of ports and adapters, with the rule that the application talks to databases, UIs and tests only through ports it defines.

  • MonolithFirst (Martin Fowler). Reference.

    Fowler reports that successful microservice systems almost always started as monoliths, and explains why service boundaries drawn before the domain is understood tend to be wrong.