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.
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.
// 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.
// 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.
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.
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);
}Output

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.
// 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:
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.

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.

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.

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:
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));Output
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.
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.