The Software Architecture Picture Book
Module Aone reason to change Module Bhidden behind an interface Shared platform: data · auth · loggingdependencies point inward, never in circles architecture = the decisions that are expensive to change later
PLATE 0 — Good structure makes the next change cheap. Bad structure makes every change risky.
A picture book for grown-ups · with code

Software Architecture and Design Patterns

Nine spreads on structuring code that lasts: principles, layering, patterns, monolith vs microservices, events, and how to write decisions down.

Say it like a pro

"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.

Sone reason to change Oextend, don't edit Lsubtypes are drop-in Ismall interfaces Ddepend on abstractions High cohesion things that belong together Low coupling few, thin links between parts
PLATE 1 — Keep related things together, and keep unrelated things apart.
Chapter 1 · Design principles

The ideas behind every pattern

SRP
a module has one reason to change
OCP
add behaviour by adding code, not rewriting working code
LSP
a subtype must work wherever its parent does
ISP
many small interfaces beat one fat one
DIP
high-level policy shouldn't depend on low-level detail; both depend on an abstraction
DRY / YAGNI / KISS
one source of truth · don't build it until needed · keep it simple
composition over inheritance
assemble behaviours rather than building deep class trees
// ✘ 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())
Say it like a pro

"The checkout depends on a gateway interface, so we can swap providers and test without the network."

frameworks & drivers · web · DB · UI adapters · controllers · repositories use cases · application rules domainentities · rules dependencies point in the core knows nothing about HTTP, SQL, or frameworks
PLATE 2 — Business rules in the middle. Technology on the outside, swappable.
Chapter 2 · Layers, clean & hexagonal architecture

Protect the business rules from the plumbing

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()
trade-off
more files and mapping code; worth it for long-lived, rule-heavy systems, overkill for a small CRUD app
Say it like a pro

"The domain is framework-free, use cases talk to ports, and adapters for HTTP and Postgres plug in at the edge."

Strategyswap an algorithmat runtime Factorycreate the right objectwithout naming its class Observersubscribers notifiedwhen state changes Decoratorwrap to add behaviour(logging, caching) Adaptermake an incompatibleAPI fit yours Repositoryhide how data is storedbehind a collection API Patterns are a vocabulary, not a goal name the problem first, then reach for the pattern that fits every pattern adds indirection: use it when the pain is real
PLATE 3 — Named solutions to problems that keep recurring.
Chapter 3 · Design patterns

The handful you'll actually use

// 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)!;
  }
}
also useful
Builder · Singleton (use sparingly: it's global state) · Command · Facade · Template method · Dependency injection
anti-patterns
God object · spaghetti · premature abstraction · "manager" classes that do everything
Say it like a pro

"A strategy map replaces the conditional, an observer decouples side effects, and a decorator adds caching without touching the repo."

Big ball of mud Modular monolith Microservices Microservices buy independence and cost complexity + separate deploys, scaling, tech choices, team ownership − network failures, latency, distributed data, versioning, observability, ops load Start modular, split when it hurts split along business boundaries (bounded contexts), not technical layers a team that can't ship a clean monolith won't ship clean microservices the "distributed monolith" is the worst of both: services that must deploy together
PLATE 4 — Distribution is a cost you pay. Pay it only for a benefit you need.
Chapter 4 · Monolith, modules & microservices

Boundaries first, deployment second

StylePick when
monolithsmall team, young product, unclear boundaries
modular monolithgrowing team; want boundaries without network cost
microservicesmany teams, independent scaling/release needs, mature ops
serverlessspiky 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
bounded context
a part of the domain with its own language and rules (Billing's "customer" ≠ Support's "customer")
strangler fig
migrate by routing one slice at a time to the new system
Say it like a pro

"A modular monolith with enforced boundaries, so any module can become a service later without a rewrite."

Order (aggregate root) OrderLine × n Money (value object) invariant: total ≥ 0, ≤ 50 lines Rules change it only through the root one transaction = one aggregate reference others by ID value objects are immutable, compared by value Ubiquitous language + bounded contexts Sales Shipping Billing name things the way the business does · the code reads like the domain translate at context boundaries (anti-corruption layer)
PLATE 5 — Model the business, in the business's words.
Chapter 5 · Domain-driven design

Make the code speak the domain

// 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"; }
}
entity
has an identity that persists as it changes (Order #42)
domain event
a fact that happened: OrderPaid; other contexts react to it
when to use
complex, rule-heavy domains. Plain CRUD doesn't need the ceremony.
Say it like a pro

"One aggregate per transaction, invariants in the root, money as a value object, and events between contexts."

Orders OrderPaid event broker Shipping Email Analytics CQRS commands → write model (rules) queries → read model (fast views) kept in sync by events Outbox pattern save data + event in ONE DB transaction, then a relay publishes it: never lose one Costs of async eventual consistency · duplicate and out-of-order messages → idempotent handlers harder to trace → correlation IDs · schema versioning for events
PLATE 6 — Publish what happened. Let others decide what to do about it.
Chapter 6 · Events, CQRS & integration

Decouple with messages

// 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);
}
StyleUse
sync call (HTTP/gRPC)need an answer now
event / pub-subnotify many, don't wait
sagamulti-step workflow with compensations instead of a distributed transaction
event sourcingstore the events as the truth; powerful, costly. Use only if the audit/replay is core.
Say it like a pro

"Outbox for reliable publishing, idempotent consumers, versioned events, and sagas instead of distributed transactions."

Performance Scalability Availability Security Maintainability Testability Cost Usability Operability You can't maximize them all caching ↑ speed, ↓ freshness · replication ↑ availability, ↓ consistency layers ↑ maintainability, ↓ raw speed · encryption ↑ security, ↓ some performance rank them for THIS product, write targets: "p95 < 300 ms", "99.9% available"
PLATE 7 — Architecture is choosing which qualities matter most, and paying for them on purpose.
Chapter 7 · Quality attributes & trade-offs

Make "good" measurable

  1. Collect the drivers: business goals, hard constraints (budget, compliance, team size), and the top 3–5 quality attributes.
  2. Turn each into a testable scenario: "When 5,000 users check out in one minute, p95 stays under 400 ms."
  3. Pick tactics that serve the ranked attributes and note what each costs.
  4. Verify with tests, not hope: load tests, chaos experiments, security scans.
// 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
Say it like a pro

"Ranked quality attributes with measurable targets, verified by load tests and architecture fitness functions in CI."

tests ✔ tiny change tests ✔ commit debt grows with interest pay it down steadily Code smells long function / class duplicated logic long parameter lists feature envy shotgun surgery primitive obsession magic numbers / flags a smell is a prompt to look, not an automatic rule
PLATE 8 — Small safe steps beat big rewrites. Interest on debt compounds, so pay a bit regularly.
Chapter 8 · Refactoring & technical debt

Improve the design without changing the behaviour

// 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];
}
  • Refactor only under test: write characterization tests first for legacy code.
  • Boy-scout rule: leave the code a little better every time you touch it.
  • Branch by abstraction / strangler fig: replace big pieces gradually behind an interface.
  • Track debt visibly: a list with cost and owner; budget time each sprint.
  • Avoid big-bang rewrites. They usually take longer and lose hidden behaviour.
cyclomatic complexity
number of paths through a function; high = hard to test
tools
ESLint complexity rules · SonarQube · CodeScene (hotspots: complex + frequently changed)
Say it like a pro

"Characterization tests, then small refactors behind an interface, and a standing slice of each sprint for debt."

ADR-007 · Use Postgres Status: accepted · 2026-10-30 Context: need transactions,reporting, a small ops team Options: Postgres · Mongo · Dynamo Decision: Postgres (managed) Consequences: SQL skills,vertical scale limit later C4: zoom levels 1 System context 2 Containers 3 Components 4 Code Write down the why in the repo, next to the code · short · one decision per file · never delete, supersede diagrams as code (Mermaid, Structurizr, PlantUML) so they can be reviewed and updated
PLATE 9 — Code shows what. Decision records explain why.
Chapter 9 · Decisions & documentation

Keep the reasoning alive

# 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
  1. Write an ADR for any decision that's costly to reverse or that people keep asking about.
  2. Keep a one-page context diagram and a container diagram. That's usually enough.
  3. Review architecture with the people who must build and run it. Prototype risky parts first.
read next
"Clean Architecture" (Martin) · "Designing Data-Intensive Applications" · "Domain-Driven Design Distilled" · "A Philosophy of Software Design" · Refactoring (Fowler)
Say it like a pro

"Decisions recorded as ADRs, diagrams in the repo as code, and trade-offs written down so the next person can disagree intelligently."