Nine spreads on structuring code that lasts: principles, layering, patterns, monolith vs microservices, events, and how to write decisions down.
"A modular monolith with clear boundaries, dependencies pointing at the domain, events between modules, and ADRs recording why."
Examples in TypeScript. Use the tabs or the ← → keys.
// ✘ high-level code welded to a low-level detail
class Checkout { pay(amount: number) { new StripeClient().charge(amount); } }
// ✔ depend on an abstraction, inject the detail
interface PaymentGateway { charge(amountCents: number): Promise<void> }
class Checkout {
constructor(private readonly gateway: PaymentGateway) {}
pay(amountCents: number) { return this.gateway.charge(amountCents); }
}
// production: new Checkout(new StripeGateway()) tests: new Checkout(new FakeGateway())
"The checkout depends on a gateway interface, so we can swap providers and test without the network."
Layered: presentation → application → domain → infrastructure. Clean/hexagonal goes further: the domain defines ports (interfaces) and the outside world supplies adapters, so dependencies always point inward.
// domain: pure rules, no imports from frameworks
export class Order {
private lines: { sku: string; qty: number; priceCents: number }[] = [];
add(sku: string, qty: number, priceCents: number) {
if (qty <= 0) throw new Error("qty must be positive");
this.lines.push({ sku, qty, priceCents });
}
get totalCents() { return this.lines.reduce((s, l) => s + l.qty * l.priceCents, 0); }
}
// port (defined by the application layer)
export interface OrderRepo { save(o: Order): Promise<void> }
// use case
export class PlaceOrder {
constructor(private repo: OrderRepo) {}
async run(items: { sku: string; qty: number; priceCents: number }[]) {
const o = new Order(); items.forEach(i => o.add(i.sku, i.qty, i.priceCents));
await this.repo.save(o); return o.totalCents;
}
}
// adapter (outer layer): class PgOrderRepo implements OrderRepo { … } controller: parse HTTP → PlaceOrder.run()
"The domain is framework-free, use cases talk to ports, and adapters for HTTP and Postgres plug in at the edge."
// Strategy: pick behaviour by data, not by if/else chains
type Discount = (cents: number) => number;
const discounts: Record<string, Discount> = {
none: c => c,
student: c => Math.round(c * 0.9),
black: c => Math.round(c * 0.7),
};
const price = (cents: number, plan: keyof typeof discounts) => discounts[plan](cents);
// Observer: decouple "something happened" from "who cares"
type Handler<T> = (e: T) => void;
class Emitter<T> {
private hs: Handler<T>[] = [];
on(h: Handler<T>) { this.hs.push(h); return () => { this.hs = this.hs.filter(x => x !== h); }; }
emit(e: T) { this.hs.forEach(h => h(e)); }
}
const orderPlaced = new Emitter<{ id: string }>();
orderPlaced.on(e => console.log("email receipt", e.id));
orderPlaced.on(e => console.log("update stock", e.id));
// Decorator: add caching around any repo without changing it
class CachedRepo implements UserRepo {
private cache = new Map<string, User>();
constructor(private inner: UserRepo) {}
async get(id: string) {
if (!this.cache.has(id)) this.cache.set(id, (await this.inner.get(id))!);
return this.cache.get(id)!;
}
}
"A strategy map replaces the conditional, an observer decouples side effects, and a decorator adds caching without touching the repo."
| Style | Pick when |
|---|---|
| monolith | small team, young product, unclear boundaries |
| modular monolith | growing team; want boundaries without network cost |
| microservices | many teams, independent scaling/release needs, mature ops |
| serverless | spiky or event-driven workloads |
src/
modules/
billing/
index.ts ← the ONLY public surface (exports a small interface)
internal/… ← not importable from other modules
catalog/ index.ts internal/…
orders/ index.ts internal/…
// lint rule (eslint-plugin-boundaries / dependency-cruiser): orders may import billing/index, never billing/internal
$ npx depcruise src --include-only '^src' --output-type dot | dot -T svg > deps.svg # see your real dependencies $ npx madge --circular src # find import cycles
"A modular monolith with enforced boundaries, so any module can become a service later without a rewrite."
// value object: immutable, validated, compared by value
export class Money {
private constructor(readonly cents: number, readonly currency: string) {}
static of(cents: number, currency = "USD") {
if (!Number.isInteger(cents)) throw new Error("cents must be an integer");
return new Money(cents, currency);
}
add(o: Money) { this.assertSame(o); return Money.of(this.cents + o.cents, this.currency); }
private assertSame(o: Money) { if (o.currency !== this.currency) throw new Error("currency mismatch"); }
}
// aggregate root: the only way in, enforces invariants
export class Order {
private lines: { sku: string; qty: number; price: Money }[] = [];
private status: "open" | "paid" | "shipped" = "open";
addLine(sku: string, qty: number, price: Money) {
if (this.status !== "open") throw new Error("order is closed");
if (this.lines.length >= 50) throw new Error("too many lines");
this.lines.push({ sku, qty, price });
}
pay() { if (!this.lines.length) throw new Error("empty order"); this.status = "paid"; }
}
OrderPaid; other contexts react to it"One aggregate per transaction, invariants in the root, money as a value object, and events between contexts."
// event contract: versioned, past tense, carries the facts
type OrderPaidV1 = { type: "OrderPaid"; version: 1; id: string; orderId: string; totalCents: number; at: string };
// outbox: write the event in the same transaction as the state change
await db.tx(async t => {
await t.query("UPDATE orders SET status='paid' WHERE id=$1", [orderId]);
await t.query("INSERT INTO outbox(id, type, payload) VALUES ($1,'OrderPaid',$2)", [eventId, payload]);
});
// a relay process publishes unsent outbox rows to the broker, then marks them sent
// consumer: idempotent
async function onOrderPaid(e: OrderPaidV1) {
if (await seen(e.id)) return; // dedupe by event id
await createShipment(e.orderId);
await markSeen(e.id);
}
| Style | Use |
|---|---|
| sync call (HTTP/gRPC) | need an answer now |
| event / pub-sub | notify many, don't wait |
| saga | multi-step workflow with compensations instead of a distributed transaction |
| event sourcing | store the events as the truth; powerful, costly. Use only if the audit/replay is core. |
"Outbox for reliable publishing, idempotent consumers, versioned events, and sagas instead of distributed transactions."
// an architecture fitness function: a test that guards a structural rule
import { cruise } from "dependency-cruiser";
test("domain must not import infrastructure", async () => {
const res = await cruise(["src"], { ruleSet: { forbidden: [
{ name: "domain-no-infra", severity: "error", from: { path: "^src/domain" }, to: { path: "^src/infra" } },
]}});
expect(res.output.summary.violations).toHaveLength(0);
});
$ k6 run load.js # load test against a stated target $ npx madge --circular src ; npx ts-prune # structure health checks
"Ranked quality attributes with measurable targets, verified by load tests and architecture fitness functions in CI."
// before: nested conditionals and a boolean flag
function shipping(order, express) {
if (order.total > 5000) { if (express) return 500; else return 0; }
else { if (express) return 1500; else return 700; }
}
// after: a table of rules, intention is visible
const FREE_OVER_CENTS = 5000;
const RATES = { standard: 700, express: 1500 } as const;
function shippingCents(totalCents: number, speed: keyof typeof RATES): number {
if (totalCents > FREE_OVER_CENTS) return speed === "express" ? 500 : 0;
return RATES[speed];
}
"Characterization tests, then small refactors behind an interface, and a standing slice of each sprint for debt."
# docs/adr/0007-use-postgres.md # ADR 0007: Use PostgreSQL for the primary datastore Status: Accepted (supersedes ADR 0002) Date: 2026-10-30 ## Context Orders need ACID transactions and ad-hoc reporting. Two engineers will run it. ## Options considered 1. PostgreSQL (managed) 2. MongoDB 3. DynamoDB ## Decision PostgreSQL on a managed service, one primary + a read replica. ## Consequences + strong consistency, SQL, mature tooling − vertical scaling limits; revisit at ~5 TB or 10k writes/s
# a diagram as code (Mermaid, renders in GitHub) flowchart LR Web --> API API --> DB[(Postgres)] API --> Q[[Queue]] Q --> Worker
"Decisions recorded as ADRs, diagrams in the repo as code, and trade-offs written down so the next person can disagree intelligently."