Chapter 39 — Software Architecture & Service Boundaries (+ ADRs, Design Docs, RFCs)
Part VIII · Synthesis | Prerequisites: Parts I–VII | Builds: Pulsely's architecture documented as a design doc + ADR library
You have spent thirty-eight chapters acquiring mechanisms — transactions, queues, caches, tokens, traces, pipelines. This chapter is about a different muscle: deciding where the seams between those mechanisms go, and writing the decision down so it survives you. Architecture is not a layer of the stack; it's the set of choices that are expensive to reverse, and the discipline of placing them so that the system stays cheap to change as it — and the team — grows. Part VIII is synthesis, so this chapter re-teaches nothing. It assumes you already know how a claim-submission transaction works, how a NestJS module wires its providers, and how a queue decouples a slow side effect. What's new is the judgment that arranges them, and the senior skill almost nobody is explicitly taught: how to write an ADR.
By the end you'll be able to draw Pulsely's bounded contexts from memory, name why each seam is where it is, explain the distributed-monolith trap to a skeptic, and author an ADR in the format that survives review. We'll formalize the ADR library that's been accumulating implicitly all book.
1. The problem: a one-line change that costs a week
A ticket lands: add an ICD-10 diagnosis-code field to an encounter. You estimate an hour. You're wrong by a week.
The field has to be added to the encounters table — fine. But an encounter's diagnosis codes are denormalized onto the claims table at bill-drop time, so claims need it too. The chart-timeline serializer hand-builds an encounter summary from a raw row join, so it breaks the moment the row shape changes. Clinical search indexes a flattened encounter document, so the indexer needs the field or your search relevance silently drifts. The worklist/alerts service formats a "visit ready to bill" task by reaching directly into the encounters table — a query you didn't know existed until it 500s in staging. Six modules, fourteen files, one shared migration that three teams must coordinate. A change that is conceptually local — a diagnosis belongs to an encounter, full stop — is physically global, because the boundaries are in the wrong place. Everything touches everything.
This is the ball-of-mud growth curve, and it's seductive precisely because it starts well. Early on, with everything in one place and no boundaries to respect, velocity is high — you can reach into any table, call any function, ship in an afternoon. Then the curve inverts. You add the fourth engineer and throughput goes down, because every change now has an unknowable blast radius and every PR touches files three other people are editing. The thing that made you fast (no boundaries) is now the thing making you slow.
The naive cure — "do microservices" — produces a worse disease if you cut the boundaries wrong. A team splits the mud into six services and discovers that shipping the diagnosis-code feature now requires a coordinated deploy of three of them, in order, because they share a database and call each other synchronously in lockstep. You've kept all the coupling and added a network between the coupled parts. Debugging a stack trace is now an exercise in correlating logs across three repos. This is the distributed monolith, and it is the most expensive way to fail at architecture.
🚫 A framing this book rejects. "Just write clean code and the architecture takes care of itself." Local code quality and system structure are different axes. You can have immaculate classes — every method short, every name perfect, full test coverage — inside a system where no boundary survives contact with a deadline, because clean code says nothing about which module is allowed to import which. Architecture is a property of the dependency graph between modules, not of the code inside any one of them. A codebase can be locally beautiful and globally a swamp.
Here's the uncomfortable part for someone pivoting into backend: boundaries are a senior responsibility, and the deliverable is partly writing. Juniors are handed a module and told what it owns. Seniors draw the lines — and then have to defend them, in prose, to peers who will live inside those lines for years and who are (rightly) skeptical. The decision and its written justification are one artifact. A boundary nobody wrote down is a boundary the next engineer erodes without knowing it existed.
2. The mental model: architecture is the cost of change
Hold one idea above all others: architecture is the set of decisions that are expensive to reverse. If a choice is cheap to change next month, it is not architecture — it's an implementation detail, and you should defer it, not agonize over it. Which validation library, how a function is named, whether a query uses a CTE — reversible, therefore not architectural. Which service owns the claims table, whether you run one deployable or six, what the contract between Scheduling and Charting looks like — expensive to reverse, therefore architecture. The whole chapter is organized around reversibility, because it tells you where to spend your scarce decision-making energy.
🧭 Mental model. Architecture is a bet on which changes stay cheap. Every pattern below — layers, hexagonal, DDD, monolith vs services — is a different wager about which kinds of change you expect and want to keep local. There is no globally correct architecture, only a correct match between your expected change profile and the seams you place. When someone asks "is this a good architecture?", the only honest answer is "for what changes?"
The load-bearing question for every boundary is therefore: what changes together, and what changes independently? Put a seam where the rate of change differs. Identity (login, sessions, RBAC) changes on a security cadence — rarely, carefully, under audit. RPM alert thresholds change weekly as clinical protocols get tuned. Gluing those two into one module means every threshold tweak risks the auth code and drags it through security review; separating them lets each move at its own speed. You are not drawing boxes by noun ("a Patient box, a Claim box") — you're drawing them by co-variance: things that change for the same reason, at the same time, for the same stakeholder, belong together.
A module, seen this way, is a blast-radius container. A good boundary guarantees that a change inside it cannot break anything outside it except through a contract you can see and that CI can check. That's the entire payoff. Cohesion high inside, coupling low across, and every cross-boundary dependency forced through a narrow, visible door.
And coupling is not a vibe — it's a directed graph. Module A importing module B is an arrow A → B. Architecture is mostly the discipline of deleting arrows and controlling the direction of the ones that remain. A swamp is a graph where every node points at every other node, often in both directions (cycles). A healthy system is a graph with few arrows, no cycles, and a clear sense of which things are stable (depended-upon) and which are volatile (depending-out). Most of the rest of this chapter is just rules for which arrows to allow.
🔑 The reversibility invariant. Spend architectural effort in proportion to the cost of reversing a decision. Cheap-to-reverse → pick something reasonable and move on; you'll change it later for free. Expensive-to-reverse → slow down, consider alternatives, and write the ADR. The classic senior failure modes are both violations of this: agonizing over a reversible choice (bikeshedding the lint config) while sleepwalking through an irreversible one (letting two contexts share a table because it was convenient on a Tuesday).
Finally: the documents — ADRs, design docs, RFCs — are the system's durable memory of why a boundary exists. Code records what the boundary is; only prose records why, and "why" is exactly what erodes first. Without the written reason, the next engineer (often future-you) hits the boundary, finds it inconvenient, sees no justification, and routes around it. Six months later the seam is gone and nobody decided to remove it. Writing the decision down is not bureaucracy; it's how a boundary defends itself when you're not in the room.
3. Theory & invariants
A mental model tells you how to picture seams. Invariants tell you what must stay true once you've placed them. These are the load-bearing rules of architecture; everything operational in §4–§8 is them made concrete.
Coupling and cohesion, named precisely
Coupling is how strongly two modules depend on each other, and it comes in a spectrum from tolerable to toxic. From loosest (aim here) to tightest (flee this):
- Message/event coupling — A emits an event, B reacts; A doesn't even know B exists. The loosest and most desirable.
- Data/parameter coupling — A calls B with plain arguments. Fine.
- Control coupling — A passes a flag that tells B how to behave, leaking B's internals into the call. Think of passing a boolean prop that flips a component into a different internal mode: the caller now has to know about the callee's private modes.
- Common coupling — A and B both read/write a shared global or shared table; a change to that shared thing hits both. Like two components both reading and writing the same Redux/Zustand store slice — reshape the slice and both shatter.
- Content coupling — A reaches into B's internals (a private field, an undocumented table column). The tightest and worst, because B can't change anything without breaking A invisibly.
The whole game is to push every cross-boundary dependency as far toward the message end as the latency budget allows.
Two derived numbers make this measurable — but start with the picture. Stand at a module and count the arrows touching it. Arrows coming in (how many other modules import it) measure how depended-upon it is: a shared React hook that half your components import has a lot of incoming arrows. Arrows going out (how many modules it imports) measure how much it leans on others. Now name them: incoming = afferent coupling (Ca), outgoing = efferent coupling (Ce). Instability is just the fraction of a module's arrows that point outward: I = Ce / (Ce + Ca). Near 0 means everything leans on you and you lean on nothing — you must stay rock-solid, because any change to you shakes the whole tree. Near 1 means you lean on everything and nothing leans on you — you're free to churn, because breaking you breaks only you. You don't compute these in a spreadsheet; you carry the intuition: things many modules depend on must be stable, and things that are inherently volatile must not be widely depended upon.
Cohesion is the converse: a module should have one reason to change. The intuition behind the academic LCOM metric is simple — if a module's parts don't use each other (the auth functions never touch the billing functions that happen to live in the same file), it isn't one module, it's two modules wearing a trench coat. Split it.
🔑 The governing law. Maximize cohesion within a boundary; minimize coupling across it; and when you must couple, couple on stable abstractions — depend on an interface/contract, not an implementation. This single sentence subsumes layered, hexagonal, and clean architecture; they're all mechanical recipes for obeying it. Its corollary is the stable-dependencies principle: arrows should point toward stability. Volatile things (the HTTP framework, the specific database, today's alert-scoring heuristic) live at the edges and depend inward; stable things (your domain rules, your contracts) live at the center and are depended upon. Nothing stable should depend on anything volatile. To feel why: if your core clinical rules
importthe Express request object or the Postgres client directly — stable code reaching out to volatile code — then swapping the web framework or the database forces edits deep in your domain logic, code that has nothing to do with HTTP or SQL. It's the same pain as a React component that reaches straight intowindow.fetchinternals instead of taking its data as props: you can't change how the data arrives without surgery on the component itself.
Layered, hexagonal, clean — one rule, three shapes
Layered architecture stacks presentation → application → domain → infrastructure, with the invariant that dependencies point downward only. It's the default most frameworks nudge you toward, and it's fine until the layers leak: the canonical failure is the DB schema dictating the API shape — your public JSON is just your table rows, so a column rename is a breaking API change (we attack this in §6).
Hexagonal (ports & adapters) fixes the leak by inverting the most dangerous arrow. The domain sits at the center and knows nothing about HTTP or SQL. It declares ports — interfaces it owns and defines in its own terms (ClaimRepository, ClearinghouseGateway). Adapters at the edges implement those ports (a Postgres ClaimRepository, a clearinghouse ClearinghouseGateway, an Express controller that calls in). The invariant: the dependency arrow points inward, toward the domain. This is the Dependency Inversion Principle lifted from the class level to the architecture level — and it's why you can swap Postgres for an in-memory fake in tests with zero edits to domain code (§4).
Clean architecture is the same inward-dependency rule generalized into concentric rings — entities → use cases → interface adapters → frameworks — with the same invariant: source-code dependencies only ever point inward, and the innermost ring (your domain) imports no framework whatsoever. The litmus test: can you compile and unit-test your core with the web framework, the ORM, and the message broker all deleted? If yes, your dependencies point the right way.
📎 Borrowed on credit: working in existing code. Everything here assumes you're placing boundaries in code you control. The far more common senior situation — inheriting a system whose boundaries are already wrong, and safely moving them without a rewrite (characterization tests, seams, the strangler fig) — is its own discipline and gets its own chapter (Ch 40). Here we learn to draw lines well; there we learn to fix lines drawn badly by someone who left.
DDD-lite: the vocabulary you actually need
You do not need the full Domain-Driven Design tome. You need five words used precisely:
- Entity — a thing with identity over time. An encounter is the same encounter even as its status marches scheduled → arrived → in-progress → signed → billed; identity, not attribute values, defines it.
- Value object — defined entirely by its attributes, and immutable. Money (
{amount, currency}), an address, a date range. Two value objects with the same attributes are the same; you replace them, you don't mutate them. - Aggregate — a consistency boundary: a cluster of entities and value objects that change together and must obey an invariant, guarded by a single aggregate root. The root is the only entry point; outside code may not reach past it into the internals.
- Bounded context — a boundary within which a model is coherent and valid, and outside which it isn't. The word "Patient" means different things in different contexts: in Scheduling it's someone who occupies a slot and has a phone number and a reason-for-visit; in Charting it's a clinical record — problems, meds, allergies, results; in Billing/RCM it's a guarantor with coverage, a subscriber ID, and a balance. Forcing one
Patientclass to serve all three produces an object that satisfies none. - Ubiquitous language — code names are domain names. If clinicians say "encounter" and your code says "visit," you pay a permanent translation tax in every conversation, every bug report, every onboarding. Within a context, there is one word per concept, and it's the domain's word.
🔑 The aggregate–transaction invariant. One transaction mutates one aggregate. Reference other aggregates by their id — never by loading the whole linked object and holding its web of child objects in memory. In plain terms: store a
patientId, don't embed the entire patient record; the root enforces its own invariant inside that one transaction. This is the bridge from domain modeling (this chapter) to the transaction boundaries you already know: the aggregate is what a transaction is for. When a single save updates patient + encounter + claim + alert, that's not an aggregate — that's your whole database masquerading as one, the way you'd never let a single Mongo write fan out and rewrite half your collections. It's the signal that your consistency boundary is drawn far too wide. Cross-aggregate consistency becomes eventual, achieved by publishing an event and handling it later (the outbox you already built), not by widening the transaction.
Conway's Law and the distributed-monolith anti-invariant
Conway's Law observes that a system's structure inevitably mirrors the communication structure of the org that builds it. Three teams will build a three-part system whose seams fall on the team boundaries, because the cheapest coordination path is the within-team path. The senior maneuver is the inverse: design the org to get the architecture you want. If you want a clean Billing boundary, give one team sole ownership of Billing. Boundaries that cut across team lines never hold, because the people on either side talk constantly and the seam fills with shortcuts.
And the anti-invariant to brand into memory — the distributed monolith: services that must deploy together, share a database, or call each other synchronously in lockstep. Any one of those three means you paid the full network tax (latency, partial failure, distributed debugging, version skew) and kept the coupling you were trying to escape. It is strictly the worst of both worlds, and §7 is largely about not building it by accident.
4. Under the hood: making boundaries real in TypeScript
A boundary you can't enforce is a boundary that erodes the first time someone's in a hurry. "Don't import Charting's internals from Billing" is a code-review comment; it will be forgotten. Let's make the boundaries mechanical — checkable by CI, not by goodwill.
A public API per context. Every bounded context exposes exactly one entry file — index.ts — and everything else in the context is private. Cross-context imports may only target the barrel; reaching past it is the violation you forbid.
// contexts/billing/index.ts — the ONLY surface other contexts may import
export { ClaimService } from './application/claim.service';
export type { ClaimSummary } from './application/claim.dto';
export { ClaimSubmitted } from './domain/events';
// internals — repositories, entities, SQL — are NOT exported and stay private
Enforce it in CI, so the build breaks on a violation. A lint rule turns the convention into a wall:
// .eslintrc — fail the build if anyone imports a context's internals
'no-restricted-imports': ['error', {
patterns: [{
group: ['**/contexts/*/!(index)', '**/contexts/*/!(index)/**'],
message: 'Import a context only via its public index.ts (no reaching into internals).',
}],
}]
Now "Billing imports Charting's repository" isn't a debate in a PR — it's a red CI check. (A tool like dependency-cruiser or eslint-plugin-boundaries can additionally forbid cycles and assert the allowed call graph from §3 declaratively.) The boundary defends itself.
Hexagonal, concretely. The domain service depends on a port interface it owns; an adapter implements it. Swapping the adapter requires zero domain edits:
// domain — owns the port, knows nothing about Postgres or HTTP
interface ClaimRepo { byId(id: string): Promise<Claim | null>; }
class BillingService {
constructor(private readonly repo: ClaimRepo) {} // depends on the port
async charge(id: string): Promise<Money> {
const c = await this.repo.byId(id);
if (!c) throw new NotFound(id);
return c.chargeAmount; // a domain rule, no SQL in sight
}
}
// adapters — implement the port at the edge
class PgClaimRepo implements ClaimRepo { /* real SQL */ }
class InMemoryClaimRepo implements ClaimRepo { /* test double */ }
In a unit test you inject InMemoryClaimRepo; in production, PgClaimRepo. The arrow points inward; Postgres is a detail at the edge. This is the payoff of §3's inversion, and it's why hexagonal codebases test fast — the core has no I/O.
NestJS as a structural teacher. A Nest module's exports array is the bounded context's public contract, enforced by the compiler and DI container:
@Module({
providers: [ClaimService, PgClaimRepo],
exports: [ClaimService], // ClaimService is public; PgClaimRepo stays private to this module
})
export class BillingModule {}
Another module that wants PgClaimRepo cannot get it injected — Nest's container won't provide an un-exported token. The framework surfaces circular module dependencies as a startup error, so a cycle (your §3 anti-pattern) fails loudly instead of rotting quietly. The exports array is a machine-checked version of index.ts.
🏭 The transferable principle, across runtimes: dependency inversion is identical everywhere; only the enforcement mechanism differs. In Java/Spring,
@Service/@Repositorystereotypes plus constructor injection make ports-and-adapters the default idiom, and Spring Modulith (or package-private visibility + ArchUnit tests) enforces module boundaries at build time — the compiler'spackage-privatekeyword does work that TypeScript, with no real privacy across files, makes you bolt on via lint rules. (You can skip the Java specifics; the transferable payoff is the last sentence.) Node lets you add enforcement; the JVM gives you more of it for free. Neither changes the design; both just change how hard it is to violate by accident.
How a module graduates to a service. Here's the lever that makes "modular monolith now, microservice later" a mechanical move rather than a rewrite: the port stays the same; only the adapter's transport changes. Today BillingService is injected an in-process ClaimRepo. The day Billing needs to scale or deploy independently, you implement ClaimRepo as an HTTP (or queue) client that calls a now-separate Billing service. The domain code that depends on the port doesn't change a line. You extract a service by swapping an adapter — if you drew the port well in the first place. That "if" is the entire argument for getting boundaries right before you have services.
5. In production: gateways, BFFs, and writing the decision down
Two patterns live at the edge of your boundaries, and one skill — writing — turns all of this from folklore into institutional memory.
API Gateway is one edge process that fronts all clients and does the cross-cutting work nobody wants to duplicate per service: TLS termination, authentication, rate-limiting, routing, request validation. It owns no business state — it's orchestration, a doorway, not a source of truth. Backend-for-Frontend (BFF) goes one step further: a per-client backend (a Web BFF, a Mobile BFF) that aggregates and reshapes downstream calls so each frontend receives exactly the payload it needs, in the shape it needs. The provider's mobile app, on a flaky cellular link, gets a single trimmed response instead of making six calls itself; the web charting UI gets a richer one.
┌─────────────┐
all clients ─▶│ API Gateway │─▶ authn · rate-limit · TLS · route ─▶ contexts
└─────────────┘ (owns NO state — orchestration only)
web ─▶ Web BFF ─┐ aggregate + reshape ┌─▶ Identity
mobile ─▶ Mobile BFF ─┼──────────────────────▶├─▶ Charting
(each owns NO state) └─▶ Billing
The rule that keeps both honest: neither a gateway nor a BFF owns durable truth. The instant business logic or persistent state creeps into them, they stop being doorways and become a second, hidden authority — and you've violated single-source-of-truth at the edge.
Now the senior skill the title promises: writing the ADR. An Architecture Decision Record is a short, immutable document capturing one architecturally-significant decision. The format is four sections, and they are not optional:
- Context — the forces, constraints, and facts true at the time. What problem, what's pushing on the decision, what's fixed. (Context expires, which is why you date-stamp; a decision sensible in 2024's context may be wrong in 2026's, and the reader needs to know which world you were in.)
- Decision — stated in active voice: "We will run Pulsely as a single modular-monolith deployable." Not "we should consider"; a decision, made.
- Alternatives considered — each real option, with an honest why-not. This section is what separates engineering from marketing. An ADR with no rejected alternatives is a press release.
- Consequences — what becomes easier and what becomes harder. Both. An ADR that lists only benefits means you haven't understood the decision; every real decision trades something away, and naming the cost is the proof you saw it.
ADR hygiene, the part that separates senior from junior: one decision per ADR. Number them (0001, 0002, …) and never delete or edit an accepted one — when a decision changes, you write a new ADR that says "Supersedes ADR-0007" and mark the old one "Superseded by ADR-0023." The history is the value; an ADR you edit is a diary you've lied in. And store them in the repo, in /docs/adr/, next to the code — docs that live in a wiki die in a wiki, unread and unlinked. An ADR in the repo can be linked from the PR that implements it and required by review.
ADR vs design doc vs RFC — three documents, three jobs:
| Document | Scope | Lifecycle |
|---|---|---|
| ADR | one narrow, expensive-to-reverse decision | Proposed → Accepted → (later) Superseded; immutable |
| Design doc | the whole shape of a feature/system: diagrams, data model, rollout, risks | living until built, then a historical record |
| RFC | a proposal seeking review/consensus before a decision exists | comment → revise → decide; produces one-or-more ADRs once accepted |
The flow in practice: a non-trivial change starts as an RFC (a proposal, circulated for async comments, with named approvers and a decision log). Once the team converges, the accepted RFC's irreversible calls are extracted into ADRs (the durable record of what was decided and why), and the feature's full shape — the diagrams, the API contracts, the failure modes — lives in a design doc. The design-doc skeleton that survives review, in order: problem & goals/non-goals → current state → proposed design (diagrams) → alternatives → data model & API contracts → failure modes & rollback → security/privacy → rollout & metrics → open questions. That spine is, not coincidentally, the same one a system-design interview wants narrated aloud (Ch 41).
🏭 Drawing boundaries in practice, the field rules. (1) Start from bounded contexts and rate-of-change, never from the database schema — the data model is downstream of the boundary, not the source of it. (2) One owning context per table; cross-context access goes through the published contract (the
index.ts, the event), never a foreign-context join. (3) Resist extraction. A context stays an in-process module until it has a different scaling, deploy, or team-ownership need than its neighbors — extracting earlier buys you distributed-systems pain with no benefit. (4) Wrap legacy systems behind an anti-corruption layer. Pulsely's Billing/RCM context has to talk to a decades-old external billing engine whose data model is nothing like yours — its field names, its status codes, its very idea of a "patient" are all foreign. Don't let that model leak inward. Put a translation adapter — an anti-corruption layer (ACL), a seam that maps the legacy system's vocabulary to your domain's on the way in and back on the way out — so your cleanClaimaggregate never learns the legacy schema's quirks. The ACL is the one place the ugliness is allowed to live; everything behind it stays in your ubiquitous language. Operate the modular monolith well — single deploy artifact, but per-module CODEOWNERS, per-module metrics/logs, and a "no cross-module table joins" rule enforced in review — and you capture most of the organizational benefit of microservices (clear ownership, bounded blast radius) without paying the distributed tax.
6. Common pitfalls
Each is signature → fix: the symptom you'll observe, then the principle that resolves it.
The common/utils/shared god-module.
Signature: every feature imports shared, and shared has grown to contain claim logic, auth helpers, date formatting, and a database client — change anything in it and the whole system rebuilds and re-tests.
Fix: a catch-all shared is a coupling magnet that points every arrow at one volatile node. Split it by context; push only the truly universal, stable primitives (a Money value object, an assertNever) into a tiny kernel; and forbid domain logic in common outright. If it has a reason to change that belongs to a context, it belongs in that context.
"Microservices" that share one database. Signature: you have six services but a single Postgres instance every service connects to and queries across. Fix: that is a distributed monolith — the database is the coupling, and you've added a network on top of it. The real boundary is database-per-context: until you can split the data, you have not split the service. Splitting the code while sharing the schema is the most expensive no-op in this field.
The DTO == the DB row == the domain object.
Signature: a Claim is one class, used as the API response, the ORM entity, and the domain model; a DB column rename is a breaking public-API change, and the API can't evolve without a migration.
Fix: introduce distinct models — a transport DTO (what the API promises, governed by your versioning rules), a persistence entity (what the table is), and a domain object (what the rules operate on) — even though early on they look identical and the duplication feels wasteful. The duplication is the point: three models that can change independently is exactly the decoupling a leaky layer lacks.
Premature service extraction. Signature: six services, two engineers; every feature is a multi-repo, multi-deploy PR; nobody can run the system locally. Fix: collapse back to a modular monolith. Extract a context only when it has proven an independent rate-of-change, scaling, or team-ownership need — not because services are how "real" systems look. Two engineers can't staff six on-call rotations.
Chatty cross-context calls to render one screen. Signature: loading the encounter-detail page fans out into N synchronous calls across contexts — an N+1, now over the network. Fix: either the boundary is wrong (data read together should live together) or you're missing an aggregation point. Add a BFF that assembles the screen's payload in one place, or co-locate the co-read data. Don't make the client orchestrate a distributed read.
Ubiquitous-language drift.
Signature: code says Account, product says Guarantor, support tickets say Payer — and a bug report takes ten minutes to translate before anyone can act on it.
Fix: pick one word per concept per context, rename the code to match the domain's word, and put a glossary in the design doc. The translation tax compounds; pay it down once.
The ADR that's all upside. Signature: a decision record with a glowing "Consequences" section listing only benefits, reading like a vendor pitch. Fix: a mandatory honest negative consequences section. If you cannot name what this decision makes harder, you have not understood it well enough to make it — go find the cost before you commit.
The aggregate that's the whole database.
Signature: one save() updates patient, encounter, claim, and alert in a single transaction; lock contention is brutal and the transaction touches half the schema.
Fix: that is not an aggregate, it's your entire DB pretending to be one. Shrink to the true invariant boundary (a claim plus its service lines, say); make everything else eventual via an event. One transaction, one aggregate (§3).
7. Tradeoffs
Senior engineering is naming the spectrum and saying why you stand where you stand — and, crucially, what would move you.
Modular monolith ↔ microservices. A modular monolith optimizes for change cost and operational simplicity: one deployable, one local run, one stack trace, refactor a boundary with a compiler instead of a coordinated multi-service migration. Microservices buy independent deploy, independent scaling, and team autonomy — at the price of full distributed-systems complexity (network failure, eventual consistency, distributed tracing, version skew). You start modular-monolith and stay there far longer than fashion suggests. You reverse toward services when a specific trigger fires: org size makes deploy contention painful (twelve teams fighting over one pipeline), or one context has a genuinely different scaling profile (RPM ingestion needs 10× the boxes), or compliance forces hard isolation. Not before — and "we might need to scale someday" is not a trigger, it's a feeling.
🛑 What we deliberately did not explain. How to actually carve a service out of a running monolith without a rewrite — the strangler-fig pattern, the shadow-traffic comparison, the expand/contract data migration — is Ch 40's entire subject, because it's a brownfield problem, not a greenfield design problem. Here we've established when and why you'd extract, and built the port seam that makes it possible (§4); how to do it safely on a live system you didn't write is next chapter. We also deferred the system-design interview method — capacity math, the 7-step funnel — to Ch 41.
Hexagonal/clean ↔ "just put it in the controller." Ports-and-adapters costs upfront indirection — more files, an interface for every boundary, a layer of injection. It pays off precisely when adapters genuinely change (you'll swap the database, support multiple delivery channels) or when fast, I/O-free testing matters. For a true CRUD edge with no domain logic — an endpoint that validates and writes a row, full stop — the ceremony is pure waste; a thin controller-to-repository call is the honest design. Be ruthless about which modules earn the hexagon: the Claim aggregate with its money and payer-rule invariants, yes; the "update the clinic's display name" endpoint, no.
API Gateway ↔ BFF. One gateway is simpler to operate but becomes a one-size-fits-none as soon as web and mobile diverge — the mobile app over-fetches, or the gateway grows client-specific branches. Per-client BFFs give each frontend a clean, tailored payload but multiply the backends you build and operate. You lean gateway when clients are uniform; you reverse toward BFF when web and mobile needs diverge sharply enough that one shape can't serve both.
Strict bounded contexts ↔ shared models. Sharing a single Patient model across Scheduling and Billing is convenient — until the day the two contexts need it to mean different things, and every change becomes a negotiation between teams that want incompatible fields. The senior call, stated as a rule: duplicate the data shape, never the source of truth. Billing may keep its own lightweight patient projection (id, coverage, guarantor, balance) that it shapes freely; it must not keep a second authoritative copy of the problem list or the login credentials. Duplication-with-translation across a boundary is usually cheaper than a shared model that satisfies neither side.
Conway: change the org, or change the architecture? Sometimes the cheapest fix to a stubborn coupling problem is not a code refactor but a team boundary — give the contested context a single owning team and the seam will harden on its own. But reorgs are expensive, slow, and political in ways code changes aren't. Weigh both; the right lever depends on whether the coupling is fundamentally technical or fundamentally organizational.
Documenting ↔ shipping. An ADR or design doc costs hours now. Skipping it costs days later — in re-litigating a decision nobody recorded, in a boundary that eroded because its reason was invisible, in an onboarding that takes a month instead of a week. You reverse (skip the doc) only for genuinely trivial, easily-reversible calls — and the senior move is to say so in the PR ("no ADR — reversible config choice"), so the absence is a decision, not an oversight.
8. Security & scale notes
Architecture's seams are not only about change cost — they're also about blast radius, and in a HIPAA system that makes them first-class security controls.
A bounded context is also a trust boundary. Cross-context calls should carry and verify identity, not assume "we're all internal, so it's fine" — the trust boundary doesn't stop at the edge of the system; it recurs at every internal seam. The payoff is blast-radius limitation: when Charting and Billing own separate databases with separate credentials, a SQL-injection hole in Billing is a Billing breach, not a whole-company one — the clinical charts in Charting stay sealed off. Conversely, the shared database from §6 isn't only a coupling smell — it means one context's injection vulnerability is every context's PHI exfiltrated at once, which in this domain is a reportable HIPAA breach with notification duties and fines attached. Isolation isn't just an engineering nicety here; it's the difference between a contained incident and a breach you have to report to regulators and patients.
The gateway is a security choke point — and a fat target. Centralizing authentication, rate-limiting, TLS termination, and request validation at the edge is genuinely good: one audited place to enforce the rules, one place to patch. But it is also a single point of failure and the juiciest target in the system, so it must stay thin — no business logic, no secrets it doesn't strictly need to terminate TLS and verify a token. A gateway that accretes feature logic becomes both a deployment bottleneck and a breach with maximum reach.
A BFF is where you enforce minimum-necessary payloads. A BFF that blindly forwards whatever a downstream context returns will happily leak fields a client should never see — another patient's data, an internal risk score, a provider's private note, a coverage detail the front desk isn't entitled to. The BFF is exactly the right place to project the downstream response down to the minimal, minimum-necessary shape this client and this role are entitled to — the same minimum-necessary principle HIPAA requires of the humans, enforced in code at the edge. Over-fetching across the boundary becomes data leakage out the edge if the BFF doesn't trim.
🔑 Coupling is a failure-propagation channel. Synchronous cross-context call chains turn one slow context into system-wide latency — exactly the saturation-is-a-chain-property lesson, now at the architecture scale: one slow link stalls everything queued behind it. If signing an encounter synchronously calls the Alerts context to fan out a critical-value notification, an Alerts stall stalls the sign-off — the clinician is stuck staring at a spinner because a downstream feature hiccuped. The fix is to choose the edge type by criticality: critical-path consistency gets a synchronous call inside one aggregate's transaction; everything non-critical (alerts, worklist updates, search re-indexing) crosses the boundary as an async event, so a downstream stall degrades a feature instead of blocking clinical work. The distributed monolith's deepest sin is here: its lockstep synchronous chains multiply failure modes — partial deploys, version skew, partition-induced cascades — while delivering none of the isolation that would contain them. Worst of both worlds, under load, exactly when it hurts most.
Scale picks your extraction triggers. A modular monolith scales by replicating the whole artifact — perfectly fine until one context (RPM ingestion, chewing on a firehose of device vitals) needs 10× the capacity of the rest and you're paying to scale everything to feed the one hot path. That asymmetry is a legitimate extraction trigger (the one §7 promised): pull the hot context out so it can scale on its own axis, and leave the rest as a monolith. Scale doesn't argue for microservices in general; it argues for extracting the specific context whose resource curve has diverged.
9. Interview lens & exercises
Interview questions
Architecture questions probe whether you reason about tradeoffs or recite patterns. The level shows in whether you name the reversal trigger.
"Monolith or microservices for this?"
- Junior answer: "Microservices — they scale better and it's more modern."
- Senior answer: leads with reversibility and team size, defaults to a modular monolith, and names the specific trigger that would flip the decision: "Modular monolith now — one team, no proven scaling asymmetry, and I want to refactor boundaries with a compiler instead of a multi-service migration. I'd extract a context the day it needs independent scaling, deploy cadence, or ownership — for example if RPM ingestion needs 10× the boxes. 'Might scale someday' isn't a reason; a measured asymmetry is."
"Where would you draw the service boundaries here?"
- Junior: splits by technical layer (a "controller service," a "database service") or one-service-per-table.
- Senior: derives boundaries from bounded contexts + rate-of-change + ownership, and pre-empts the shared-database trap: "I'd cut by what-changes-together — Identity, Scheduling, Charting, Billing — give each its own data, and let cross-context access go only through published contracts. Splitting the code while sharing one schema is a distributed monolith; the database is the real boundary."
"API gateway vs BFF — when each?"
- Junior: "They're both proxies / kind of the same thing."
- Senior: "Gateway is one cross-cutting edge for all clients — authn, rate-limit, TLS, routing. A BFF is per-client aggregation and payload-shaping so mobile and web each get exactly their shape. Neither owns durable state — both are orchestration. I reach for BFFs when client needs diverge; a single gateway when they're uniform."
"Walk me through how you'd write down an architectural decision."
- Junior: "I'd put a note in the wiki."
- Senior: "An ADR in the repo: Context with the forces and a date, a Decision in active voice, Alternatives each with an honest why-not, Consequences including what gets harder. One decision per ADR, numbered, never edited — superseded with a link. An ADR with no downsides is marketing; if I can't name a cost I don't understand the decision."
"You inherited a system where every feature needs a 3-service coordinated deploy. What's going on, what do you do?"
- Junior: "Automate the deploy so the coordination is less painful."
- Senior: "That's a distributed monolith — the services are coupled by a shared database or synchronous lockstep calls, so they can't deploy independently. Automating the deploy treats the symptom. I'd re-cut the boundaries by what-actually-changes-together — likely recombining the falsely-split services back into a modular monolith and splitting the data, not just the code. How to do that safely on a live system is the strangler-fig migration." (That "how" is Ch 40 — knowing the boundary between this diagnosis and that execution is itself a senior signal.)
Exercises & the Pulsely increment
This chapter's increment formalizes the architecture documentation that's been implicit all book. Do it for real — it's a portfolio artifact.
-
Carve Pulsely's bounded contexts. From the domain you've been modeling all book, define the six contexts — Identity/RBAC, Scheduling, Charting/Clinical, Orders (labs/Rx/referrals), Billing/RCM, RPM-monitoring — and for each write a one-line ubiquitous-language glossary and the one reason it changes. Prove the boundaries are by rate-of-change, not by noun: explain why Identity (security cadence, under audit) and RPM-monitoring (alert thresholds tuned weekly) must not share a module.
-
Draw the bounded-context map. Six boxes; draw the allowed edges and label each as synchronous-call or async-event; annotate the database owned by each context. Mark the external legacy billing engine as an outside system that Billing/RCM reaches only through an anti-corruption layer, so its foreign model never leaks past the seam. Then mark which internal edges are critical-path (sync inside a transaction) and which are non-critical (async event), citing §8. The "no cross-context join" rule should be visible in that nothing reaches into another box's database.
-
Write the consolidated Pulsely design doc. Use the §5 skeleton: problem → current state (one architecture diagram) → the six contexts + glossary → the coupling map → data model & contracts → failure modes & rollback → security/privacy (PHI, minimum-necessary, audit) → rollout → open questions. This is the single document a new hire reads on day one.
-
Author the foundational ADRs, committed to
/docs/adr/, in full Context → Decision → Alternatives → Consequences form:- ADR-0001 — "Record architecture decisions in ADRs." The meta-ADR (status: Accepted). Context: decisions made all book left no durable trail. Decision: we will record significant decisions as numbered, immutable ADRs in the repo. Alternatives: a wiki (dies), tribal knowledge (leaves), commit messages (too granular). Consequences: +durable memory, +review gate; −a writing tax on every significant change. Writing this first is how the library itself gets justified.
- ADR-0002 — "Modular monolith over microservices for v1." Context: one small team, no proven scaling asymmetry, change-cost is the dominant concern. Decision: single modular-monolith deployable with CI-enforced context boundaries, and an anti-corruption layer isolating the legacy billing engine. Alternatives: microservices (rejected — distributed tax with no triggered benefit), big-ball-of-mud (rejected — no blast-radius control). Consequences: +simple ops and compiler-checked refactors; −must self-enforce boundaries that services would enforce by network, and −one hot context (RPM ingestion) can't scale alone until extracted.
-
Boundary-enforcement drill. Add the §4
no-restricted-importsrule (or wire a Nest module'sexports) for one Pulsely context. Prove it works by writing a deliberate violating import — Billing reaching into Charting's repository — and watching CI go red. A boundary you haven't seen reject something is a boundary you don't actually have. -
Leaky-layer refactor drill. Take Pulsely's path where the claim API DTO equals the DB row, and split it into distinct domain / persistence / transport models for the Billing context. Then measure the win: count the files a
charge_cents→chargeMinorcolumn rename touches before (the API breaks) versus after (only the persistence adapter and its mapper). That delta — in blast radius — is the value of the boundary, made numeric.
Key takeaways
- Architecture is the set of decisions expensive to reverse. Spend effort in proportion to reversal cost; defer everything cheap. The scoreboard is the cost of change, measured in human terms — time-to-understand, blast radius, coordination headcount — not CPU.
- Place every seam by asking "what changes together vs independently?" A module is a blast-radius container; coupling is a directed graph, and architecture is mostly deleting arrows and pointing them at stable abstractions.
- The governing law: high cohesion inside, low coupling across, depend on contracts not implementations. Layered, hexagonal, and clean architecture are three shapes of one rule — dependencies point toward stability/the domain.
- DDD-lite gives you the vocabulary: entity, value object, aggregate (= a consistency = transaction boundary; one transaction, one aggregate), bounded context ("Patient" means different things in Scheduling, Charting, and Billing), ubiquitous language — and an anti-corruption layer to keep a legacy system's model from leaking inward.
- Default to a modular monolith with CI-enforced boundaries; the distributed monolith (shared DB / lockstep deploy / synchronous chains) is the worst of both worlds. Extract a context only on a proven trigger: divergent scaling, deploy contention, or team ownership. Conway's Law means you can fix coupling with a team boundary, not only a code one.
- Gateways and BFFs own no state — gateway = cross-cutting edge for all clients, BFF = per-client shaping and minimum-necessary projection. Boundaries are trust boundaries: in a HIPAA system, isolation is the difference between a contained incident and a reportable breach.
- Half the job is writing it down. An ADR records one decision — Context → Decision → Alternatives → Consequences (including what gets harder) — numbered, immutable, superseded-not-edited, living in the repo. Design docs capture whole shapes; RFCs seek consensus and produce ADRs. An ADR with no downside is marketing.
← Previous: Ch 38 — CI/CD, IaC & Deployment · Up: Part VIII overview · Master TOC · Next: Ch 40 — Working in Existing & Brownfield Systems →