Skip to main content

Chapter 14 — NestJS, Dependency Injection & Application Architecture

Part III · APIs as Contracts | Prerequisites: Ch 13 | Builds: Pulsely restructured into Nest modules with layered/hexagonal architecture

Earlier you de-magicked Express down to its bones: an ordered array of functions sharing one mutable (req, res) pair, each handed a next baton. You proved you could build the framework in sixty lines, and that proof was the point — once you've seen the engine, the framework stops being a thing to memorize and becomes a thing to reason about. But somewhere around the fifteenth route, the twentieth new SomeClient(), and the third copy of the same mock in three test files, Express's honesty curdles into a tax. The framework that hides nothing also organizes nothing. Every dependency you need, you fetch by hand; every object's lifetime, you manage by hand; every boundary between "your clinical rule" and "the clearinghouse vendor's SDK," you draw by hand — or, more often, fail to draw at all.

This chapter is about what disciplined teams reach for when hand-wiring stops scaling: dependency injection as a principle (not a NestJS feature), and application architecture — layered and hexagonal — as the structure that keeps your domain from rotting into the framework. NestJS is our lab, because it ships a real DI container and a named, ordered request pipeline. But almost nothing here is about Nest. It's about a convergence: every serious backend ecosystem — Spring on the JVM, Nest on Node, Dagger and Guice, ASP.NET Core's built-in container — independently arrived at the same three ideas (a container, scopes, a composition root) because the same pain forced them there. We're going to feel that pain in Pulsely first, then build the cure, then map every Nest abstraction back onto the Express pipeline you already understand. Map, don't memorize.


1. The problem: hand-wiring is a tax you pay forever​

Let me show you the exact moment Express stops being a gift.

Here is the Pulsely submitClaim handler you were left with at the end of the last chapter. It works. It shipped. It looks completely reasonable:

import { Clearinghouse } from 'clearinghouse-sdk';
import { db } from '../db'; // a module-level singleton pool
import { sendMessage } from '../messaging'; // imports a template loader, which imports fs

export async function submitClaim(req: Request, res: Response) {
const clearinghouse = new Clearinghouse(process.env.CLEARINGHOUSE_KEY!); // (1) constructs a vendor
const { encounterId } = req.validated.body;

const encounter = await db.query('SELECT * FROM encounters WHERE id=$1', [encounterId]);
if (encounter.status !== 'signed') throw new EncounterNotSignedError(encounterId);

const ack = await clearinghouse.submit837(buildClaim(encounter)); // (2) real network
const claim = await db.query('INSERT INTO claims ... RETURNING *', [/* ... */]); // (3) real DB
await sendMessage(encounter.providerId, 'claim-submitted', { claim }); // (4) real messaging

res.status(201).json(claim);
}

Now do one thing with it: write a unit test for the signed-before-billed rule. Just that one rule — "if the encounter isn't signed, refuse to bill it." It's a pure clinical-billing decision, the kind of thing you'd hope to test in two milliseconds with no infrastructure.

You can't. To even call submitClaim, you have to instantiate the world. Line (1) reads process.env.CLEARINGHOUSE_KEY and constructs a live clearinghouse client. Line (2) will try to reach the clearinghouse's API over the network. Line (3) imports a module-level db that opened a real Postgres pool the instant it was imported. Line (4) drags in the messaging SDK, which drags in a template loader, which drags in fs, which means your "unit" test of a single status check now requires a database socket, a messaging server, a clearinghouse key, and an internet connection. The rule you wanted to test is welded to four pieces of infrastructure it has no business knowing about. The handler doesn't receive its collaborators; it summons them. And anything a function summons, a test cannot replace.

That's the headline failure. Underneath it sit four more, each one a thing you've probably already lived through.

The wiring tax compounds. Every new dependency means editing four places: the constructor or call site, the route registration, the test setup, and the mocks. They drift. You add an EligibilityCheck dependency to submitClaim, update three of the four, and the fourth — the test mock — silently keeps returning the old shape until it bites you in CI a week later. A "small" service grows a forty-line manual composition root at the top of index.ts that nobody dares touch because the ordering is load-bearing and undocumented.

Lifecycles go wrong quietly. Two modules each import-and-new their own database pool (a connection pool is a fixed, shared set of reusable DB connections the whole server borrows from) because that was the easy thing in the moment; under load you hit too many connections and spend an afternoon discovering you have two pools where you thought you had one. A cache you believed was a singleton turns out to be re-created per request because it lived inside a closure that the router rebuilt. Graceful shutdown leaks sockets because nothing owns "close all the things" — there's no object whose job is the application's lifecycle, so the lifecycle is everyone's job, which means it's no one's.

Coupling hides in the import graph. ClaimService imports MessagingService imports TemplateLoader imports fs. The clinical rule "a claim submission notifies the billing worklist" is now structurally fused to Node's filesystem and your specific messaging vendor. Want to swap one messaging vendor for another? Want to test the rule without sending a message? You're editing four files across three layers, because the dependency arrows all point outward, toward the volatile vendor, instead of inward, toward your stable rule.

Blast radius becomes unknowable. One afternoon the messaging vendor has an outage. Because messaging and claims live in the same process with a tangled import graph and no boundary between them, a hung send call inside the claim path holds connections, the pool drains (you've already seen this exact saturation chain), and now claim submission is down because messaging is down. On-call cannot reason about what depends on what, because there is no map. The import graph is the map, and it's spaghetti.

Strip these to the bone and the diagnosis is singular: dependencies are implicit, summoned, and unowned. The fix is to make them explicit (declared, not summoned), swappable (named by an interface, not a vendor), and owned (a container manages their lifetime). That is what dependency injection and architectural layering buy you. They are not framework ceremony. They are the mechanism that turns testability, lifecycle correctness, and decoupling from things you achieve by discipline (and therefore eventually fail at) into things that are true structurally (and therefore hard to get wrong).

🧭 A useful distinction. "Dependency injection" sounds like a framework feature, and the framework versions are loud about themselves — decorators, containers, magic. But strip all of that away and DI is a single, almost embarrassingly simple idea: a function or object should be handed what it needs, rather than reach out and grab it. function submitClaim(deps) { ... } where deps carries the database and the clearinghouse gateway is already dependency injection — manual DI, no container in sight. The container is an optimization for when manual injection's bookkeeping gets heavy. Keep the principle and the tool separate in your head all chapter; the principle is what makes you a better engineer, the tool is just ergonomics over it.


2. The mental model: invert control, then draw rings​

Two pictures carry this chapter. The first is about who constructs whom. The second is about which way dependencies are allowed to point. Hold both.

Inversion of control​

In the bad submitClaim, the handler is in charge of construction: it decides to new Clearinghouse(), it decides which db to import. Control flows from your code out to the dependencies it picks. Inversion of control flips the arrow. Your code stops naming concrete sources. Instead it declares what it needs — usually as constructor parameters — and an external assembler decides what to actually hand it:

class ClaimService {
constructor(
private readonly claims: ClaimRepository, // "I need something that stores claims"
private readonly clearinghouse: ClearinghouseGateway, // "I need something that submits claims"
private readonly notifier: Notifier, // "I need something that notifies"
) {}
// The service never says HOW claims are stored or WHO transmits them to the payer.
}

The service no longer summons the clearinghouse; it asks for "a thing that can submit a claim" and trusts that someone, somewhere, will provide one. Who provides it — the real clearinghouse in production, a fake in a test — is decided elsewhere, by the assembler. This is the old Hollywood line made literal: "Don't call us, we'll call you," applied to object construction. The class is now a pure consumer of collaborators it can't see the type of.

The container as the single composition root​

That "external assembler" needs a home, and that home is the container. The container is the one place in your system that knows the full recipe for building the object graph: it knows ClaimService needs a ClaimRepository, that the production ClaimRepository is a PrismaClaimRepository which itself needs a PrismaClient, and so on down. You ask the container for a finished ClaimService and it hands you one with every collaborator already wired in, recursively. It also owns object lifetimes — it decides whether you get the same shared instance every time (a singleton) or a fresh one. The pile of manual news and the forty-line composition root from §1 collapse into a thing the framework runs for you, correctly, once.

🧭 Mental model. A DI container is a factory for your entire application graph plus a registry of lifetimes. You register recipes ("when someone needs a ClearinghouseGateway, build a ClearinghouseAdapter"); the container topologically sorts the graph and constructs it on demand. Your business code shrinks to declaring needs and using what arrives. Everything else in this chapter — modules, providers, scopes, the request pipeline — is detail in service of those two jobs: build the graph, own the lifetimes. When Nest confuses you later, come back here and ask: is this about building the graph, or about owning a lifetime? It's almost always one of the two.

The rings: dependencies point inward​

The second picture is spatial, and it's the one that survives long after you've forgotten Nest's decorator names. Imagine your application as concentric rings:

┌──────────────────────────────────────────────────────────┐
│ OUTBOUND ADAPTERS PrismaClaimRepo · ClearinghouseAdapter│
│ · SecureMessageNotifier · SearchIndex │
│ ┌──────────────────────────────────────────────────┐ │
│ │ OUTBOUND PORTS (interfaces the inside OWNS): │ │
│ │ ClaimRepository · ClearinghouseGateway · Notifier│ │
│ │ ┌──────────────────────────────────────────┐ │ │
│ │ │ DOMAIN Claim entity, "signed-before- │ │ │
│ │ │ billed" invariant, pure, no I/O │ │ │
│ │ └──────────────────────────────────────────┘ │ │
│ │ APPLICATION / USE-CASES: ClaimService │ │
│ │ (orchestration, transactions, "do the steps")│ │
│ └──────────────────────────────────────────────────┘ │
│ INBOUND ADAPTERS HTTP controller · queue consumer · CLI │
└──────────────────────────────────────────────────────────┘
every dependency arrow points INWARD ──▶

The rules:

  • The domain sits dead center: entities and their invariants ("a claim can only be submitted for a signed encounter"), pure rules, zero I/O. It is the most stable thing you own and it depends on nothing concrete — not Nest, not Prisma, not the clearinghouse SDK.
  • The application/use-case layer wraps it: this is where ClaimService lives, orchestrating the steps ("check the encounter is signed, build the 837, transmit, record, notify") and owning transaction boundaries. It depends on the domain and on ports, never on vendors.
  • Ports are interfaces defined by the inside — ClaimRepository, ClearinghouseGateway, Notifier. Crucially, the domain owns these contracts; the clearinghouse vendor does not get to define what "submit a claim" means to Pulsely. Pulsely defines ClearinghouseGateway, and the vendor adapter is forced to fit it. Never the reverse.
  • Adapters live at the edge. Inbound adapters (an HTTP controller, a queue consumer that drains an 837 batch, a CLI command) translate the outside world into use-case calls. Outbound adapters (PrismaClaimRepository, ClearinghouseAdapter, SecureMessageNotifier) implement the ports, translating your domain's needs into vendor calls.

The single law that makes this architecture rather than a folder convention: dependencies point inward only. The domain never imports an adapter. The application layer never imports the clearinghouse SDK. The arrows always run from volatile outer rings toward stable inner ones. Get this one rule right and your domain becomes a library you could lift into another runtime entirely — swap Nest for Fastify, swap the HTTP controller for a gRPC handler, and the inner rings don't notice.

A Nest module is a ring boundary with a public API​

Where does NestJS enter? A Nest module is the unit that makes these boundaries real and enforceable. A module declares three things: providers (what it knows how to build), exports (what neighboring modules are allowed to borrow), and imports (whose exports it consumes). That's not a folder — it's a package boundary with an explicit public API. A provider you don't export is private to its module, full stop; another module physically cannot inject it. This is the structural cure for the import-graph spaghetti of §1: cross-module access must go through a declared, exported contract, so the tangle can't silently reform.

And here is the move that makes the whole chapter easy. Every Nest abstraction is a named slot in the pipeline you already hand-built in Express. You don't need to learn Nest's request lifecycle from scratch; you need to recognize it:

You built this in ExpressNest calls itWhat it does
app.use(fn) cross-cutting middlewareMiddlewareruns on raw req/res, before DI-resolved metadata
your requireAuth middlewareGuardreturns a boolean: may this request proceed?
your asyncHandler / timing wrapperInterceptorwraps the handler: transform input/output, time it, cache it
your per-route validate(schema)Pipevalidate + transform the handler's arguments
the route handler itselfController methodthe actual endpoint logic
your single terminal error middlewareException filtercatch thrown errors, shape the HTTP response
your forty-line manual composition rootDI containerbuild the graph, own the lifetimes

Nest didn't invent these jobs. It named them, gave them a fixed order, and put a container underneath. Everything that follows is filling in that table.


3. Theory & invariants​

A mental model tells you how to picture things. Invariants tell you what must stay true or the whole structure is a lie. These are the load-bearing rules of disciplined application architecture.

🔑 The dependency-inversion invariant. In plain terms: your claim-submission rule must never import the clearinghouse SDK. Instead, the rule depends on a ClearinghouseGateway interface that lives in the rule's own layer, and the clearinghouse adapter is forced to implement it. If you write React, you've already done exactly this: it's a component that takes an onSubmit prop instead of calling fetch('/clearinghouse') itself — the parent decides the real implementation, the component just declares the shape it needs. Formally, this is the "D" in SOLID: high-level policy must not depend on low-level detail; both depend on an abstraction owned by the high-level side. It is the spine of the rings picture. "Policy" is your claim-submission rule; "detail" is the fact that you happen to route claims through today's clearinghouse vendor. The rule must not import that vendor. Instead, the rule depends on a ClearinghouseGateway interface that the rule's own layer defines, and the vendor adapter depends on (implements) that interface. The arrow that used to point from your domain out to the vendor now points from the vendor in to your domain. Distinguish the principle from the technique: dependency inversion is the goal (arrows point inward, toward stability); dependency injection is merely one mechanism for achieving it (hand the abstraction in through the constructor). You can do DI without inverting anything (inject a concrete clearinghouse client and you've gained testability but kept the bad coupling), and you can invert without a container (define the port, wire it by hand). The two ideas travel together but they are not the same idea.

🔑 The constructor-injection invariant. Prefer constructor injection over property/setter injection, because it makes "this object cannot exist without its dependencies" a structural fact rather than a hope. With constructor injection, a ClaimService is never observable in a half-built state — the moment it exists, every collaborator is present and typed; the dependency graph is statically analyzable by reading constructors; and a test that wants to substitute a collaborator has exactly one, obvious place to do it. Property/setter injection makes dependencies optional and mutable — the object can exist incompletely, can be mutated after construction, and hides its real requirements. Use it only for genuinely optional collaborators, and treat its use as a small confession.

Now the lifecycle invariants, which are where most production DI bugs actually live:

Scope vocabulary, and the rule that ties it together. A provider has a scope that governs how many instances exist and for how long:

  • Singleton — one instance per container, created once, shared everywhere. This is the default, and it carries an obligation: a singleton must be stateless (or otherwise safe to share), because every request touches the same object.
  • Request-scoped — one instance per inbound request. Useful for things that legitimately carry per-request context (the current user, a request id), but it has a sharp cost we'll return to.
  • Transient — a fresh instance every time it's resolved.

🔑 The scope-containment invariant. A wider-scoped provider may never depend on a narrower-scoped one without an explicit proxy. A singleton depending on a request-scoped provider is a contradiction: the singleton is built once and lives forever, but its dependency is supposed to be rebuilt every request — so which request's instance does the singleton hold? There are only two outcomes, both bad. Either you've smuggled one request's state into a shared object — a data leak where patient A's chart is handed to the clinician serving patient B, which in healthcare is a reportable breach, not a nuisance. Or the container takes its only other option: it rebuilds the singleton on every request too, quietly turning it request-scoped. But now anything that depends on that provider must also go request-scoped. The escalation ripples up the whole graph. Reuse disappears everywhere, and throughput collapses. The fix is almost always to make the inner provider stateless and pass per-request context as an explicit argument, not to escalate scope. Default to singleton; pass context, don't scope it.

Resolution is a DAG — a dependency graph with no cycles. Asked for an object, the container builds the pieces that need nothing first, then the things that depend on those, working inward until it reaches the object you asked for. (That bottom-up order — leaves first — is the one called topological order.) This only works if the graph is acyclic: no object may, directly or through a chain, depend on itself. It's the same reason two React hooks — or two ES modules — can't import each other in a cycle: there's no valid order to initialize them in. A circular dependency (A needs B needs A) is not a feature to be worked around; it's a design defect. It almost always means one of two things: that A and B are really one concept that got split, or that there's a missing third collaborator both of them should depend on instead of on each other. Frameworks offer escape hatches (forwardRef, lazy resolution), and they are bandages over a smell, not cures.

Depend toward stability. The Stable Dependencies Principle says: point your dependency arrows toward the things least likely to change. Your domain rules change rarely (the meaning of "a clean claim" is stable across vendor swaps and framework upgrades); your vendor adapters change constantly (the clearinghouse ships a new SDK, or you migrate off it entirely after an outage — in this industry, clearinghouses really do go dark and get swapped). So the stable domain sits at the center and the volatile adapters orbit it, depending inward. Layer boundaries exist precisely to keep the arrows pointing this way. When you catch an arrow pointing outward — a domain entity importing the Prisma client — you've found a future maintenance fire.

🔑 The testability invariant (restated as a property of wiring). If every collaborator arrives through a constructor and is typed by an interface (a port), then a unit test can replace every external effect with a fake without touching any global state. Notice what this says: the testability of a unit is a property of how it's wired, not of how clever the code inside it is. The bad submitClaim was untestable not because its logic was complex but because its dependencies were summoned. Invert and inject, and testability falls out for free. This is the deepest practical payoff of the whole chapter, and it's why "is this testable?" is a fast proxy for "is this well-architected?"

🔑 The module-encapsulation invariant. Within a module, a provider that is not exported is private. Cross-module access must go through an exported public contract. This is plain old information hiding, enforced by the container rather than by convention — and it is exactly what stops the §1 spaghetti from re-growing. A module's exports list is its public API; everything else is implementation you're free to change without consulting your neighbors.

📎 Borrowed on credit: where the boundaries between services go. Everything in this chapter is about structure inside a single process — rings, layers, modules, ports. We are deliberately not deciding where to split Pulsely into separate deployable services, what a bounded context is, or whether claims and messaging should be one program or two. Those are different questions — they're about network boundaries, independent deployment, and team ownership, not about in-process dependency arrows — and they get their own treatment in Chapter 39. For now, hold the assertion: clean in-process layering is the precondition for ever splitting cleanly later. A module with a well-drawn port boundary is a module you could extract into its own service; a tangle is not. Get the in-process architecture right first; the cross-service question is downstream of it.


4. Under the hood: how the container actually resolves, and the pipeline in exact order​

Let's kill the magic, the way we always do. Two mechanisms to understand: how Nest builds the graph (and the TypeScript wrinkle that makes hexagonal awkward), and the exact order of the request pipeline.

How resolution works, and why reflect-metadata matters​

When you mark a class @Injectable() and the TypeScript compiler has emitDecoratorMetadata turned on, the compiler emits a hidden piece of metadata alongside the class: design:paramtypes, an array of the constructor parameters' types. At startup, Nest reads that array (via the reflect-metadata library — which is why you must import 'reflect-metadata' exactly once, at the entrypoint) and now knows: "to build a ClaimService, I need to first build a ClaimRepository, a ClearinghouseGateway, and a Notifier." It resolves each of those the same way, recursively, until it bottoms out at things with no dependencies, then constructs back up. That's the whole trick. The decorator isn't doing anything mystical; it's a hook that asks the compiler to leave behind a list of types the container can read at runtime.

This is also why two tsconfig flags — experimentalDecorators and emitDecoratorMetadata — are non-negotiable for Nest. Without them there is no design:paramtypes, and the container is blind.

🏭 This compiler-metadata trick is the single most important thing to understand about Nest, because it explains its biggest sharp edge. The container resolves dependencies by their type. And TypeScript types are erased at runtime — they exist only at compile time. For classes this is fine: a class is also a runtime value (a constructor function), so design:paramtypes can record it. But for interfaces — which is exactly what your ports are — there is nothing left at runtime to record. ClearinghouseGateway as an interface evaporates the moment tsc runs. So you cannot inject a port by its type.

Tokens: the workaround the erasure problem forces​

Because an interface has no runtime identity, you inject it by a token instead — a string or a symbol that stands in for the contract:

export const CLEARINGHOUSE_GATEWAY = Symbol('ClearinghouseGateway'); // the runtime stand-in for the port

@Injectable()
class ClaimService {
constructor(
@Inject(CLEARINGHOUSE_GATEWAY) private readonly clearinghouse: ClearinghouseGateway, // inject by token
) {}
}

// In the module, bind the token to a concrete implementation:
@Module({
providers: [
ClaimService,
{ provide: CLEARINGHOUSE_GATEWAY, useClass: ClearinghouseAdapter }, // "for this token, build a ClearinghouseAdapter"
],
})
export class ClaimsModule {}

Name this loudly, because tutorials skate past it: type erasure is the practical reason hexagonal architecture in TypeScript needs explicit tokens. In a language with reified interfaces (or one that resolves by name like Spring), you'd inject the interface directly. In TS you pay a small, permanent ceremony tax — a token per port — to get the dependency-inversion benefit. It's worth it for the rings to be real, but you should know exactly why you're typing @Inject(CLEARINGHOUSE_GATEWAY) and not pretend it's incidental.

Provider recipes: the three ways to bind a token​

Nest gives you three "recipes" for how a token gets satisfied, and they cover everything:

  • useClass — instantiate this class. The everyday case, and the swap point: useClass: ClearinghouseAdapter in production, useClass: FakeClearinghouseGateway in a test module.
  • useValue — use this exact object. For config objects, constants, and injecting pre-built fakes (useValue: { submit: jest.fn() }).
  • useFactory — call this function to build the value, and inject: its own dependencies. This is the controlled escape hatch back to manual wiring — for async or computed construction, like "open a database pool (which is async) and inject the live pool":
{
provide: 'DB_POOL',
useFactory: async (config: ConfigService) => {
const pool = new Pool({ connectionString: config.databaseUrl });
await pool.connect(); // async construction the container can't express otherwise
return pool; // ONE pool, owned by the container, injected everywhere
},
inject: [ConfigService],
}

That factory is the structural fix for the "two pools" lifecycle bug from §1: there is now exactly one pool, the container builds it once, and every consumer injects the same instance.

The request lifecycle, in exact order — mapped to Express​

Here is the pipeline a Nest request flows through, and the order is not arbitrary — it encodes real decisions. Each stage is labeled with the Express thing you already built that it corresponds to:

(the wrapping is symmetric:
incoming request interceptors see the response too)
│
▼
┌──────────────┐ ┌────────┐ ┌───────────────┐ ┌───────┐ ┌────────────┐ ┌───────────────┐ ┌──────────────────┐
│ MIDDLEWARE │──▶│ GUARDS │──▶│ INTERCEPTORS │──▶│ PIPES │──▶│ CONTROLLER │──▶│ INTERCEPTORS │──▶│ (response out) │
│ app.use │ │ authz/ │ │ (pre) │ │ valid │ │ handler │ │ (post) │ │ │
│ raw req/res │ │ authn │ │ wrap/observe │ │ +xform│ │ logic │ │ map return │ │ │
└──────────────┘ └────────┘ └───────────────┘ └───────┘ └────────────┘ └───────────────┘ └──────────────────┘
│ throws
▼
┌──────────────────┐
│ EXCEPTION FILTER │ catch → shape HTTP response
│ (your try/catch │
│ error mapper) │
└──────────────────┘

Walk it once, slowly:

  1. Middleware — your app.use. Runs on the raw req/res, before Nest has resolved any route metadata. Use it for the genuinely framework-agnostic things: request-id assignment, raw-body capture for verifying an inbound callback's signature — a lab result posting back, a 271 eligibility response, an e-Rx status update all arrive as signed callbacks whose signature must be checked against the raw bytes — and security headers. It can't see which handler you're heading toward, so it can't make route-specific decisions.
  2. Guards — your requireAuth. A guard returns a boolean (or throws): may this request proceed at all? Authentication and authorization live here. Guards can read route metadata (more on that next), so a guard can ask "does this handler require the provider role?" and decide accordingly.
  3. Interceptors (pre) — your asyncHandler/timing wrapper. An interceptor wraps the handler call, so it sees both the way in and the way out. The "pre" half runs before the controller: start a timer, attach context, set up logging.
  4. Pipes — your validate(schema). Pipes validate and transform the handler's resolved arguments — turn the raw body into a validated DTO instance, coerce the :id param from string to number, reject malformed input with a 400/422.
  5. Controller method — the handler. Your actual endpoint logic, now receiving clean, typed, validated arguments and injected services.
  6. Interceptors (post) — the same interceptors, now on the way out: map the return value into a response envelope, attach caching headers, record the latency the timer measured.
  7. Exception filters — your single terminal error middleware. If anything in the chain throws, the matching filter catches it and shapes the HTTP response. This is the one place that knows how a domain error becomes a status code.

🏭 The ordering guards-before-pipes is a real engineering decision, not an accident, and it's the answer to the obvious interview question. Authorization (guards) runs before validation (pipes). That means an unauthorized request is rejected before you spend CPU parsing and validating a potentially huge, hostile request body. If pipes ran first, an attacker could make you do expensive validation work on bodies you were going to reject anyway — a cheap denial-of-service. Put the cheap "are you even allowed here?" check first, the expensive "is your payload well-formed?" check second. This is the same security-through-ordering principle you met in Express earlier, now baked into the framework's fixed sequence so you can't get it wrong.

Reading route metadata: ExecutionContext and Reflector​

How does a generic guard know that this particular handler needs the provider role? You decorate the handler — @Roles('provider') — which attaches metadata to it, and the guard reads that metadata back at runtime through Nest's Reflector:

@Injectable()
class RolesGuard implements CanActivate {
constructor(private reflector: Reflector) {}
canActivate(ctx: ExecutionContext): boolean {
const required = this.reflector.get<string[]>('roles', ctx.getHandler()); // read @Roles metadata
if (!required) return true;
const { user } = ctx.switchToHttp().getRequest();
return required.some((r) => user.roles?.includes(r)); // generic authz decision
}
}

This is the mechanism that replaces the scattered if (req.user.role !== 'provider') checks you'd otherwise sprinkle across twenty controllers. The decision is written once, generically, in a guard; the policy (which roles where) is declared declaratively on each handler. ExecutionContext is the abstraction that lets the same guard work whether the request arrived over HTTP, gRPC, or a WebSocket — it's "the current invocation, transport-agnostic."

Lifecycle hooks: where the container owns shutdown​

Remember the §1 leak — nothing owns "close all the things." The container does, through lifecycle hooks. A provider can implement onModuleInit (open the pool), onApplicationBootstrap (everything is wired, start consumers), and crucially onModuleDestroy / beforeApplicationShutdown / onApplicationShutdown (drain in-flight work, close the pool, disconnect consumers). With app.enableShutdownHooks(), a SIGTERM (the signal a deploy or autoscaler sends) triggers these in dependency order — leaves last, so nothing closes a pool another provider is still draining through. The lifecycle now has an owner. The leak is structurally impossible.

🏭 The JVM lens (skippable — you never touch Java for any of this; the only takeaway is the convergence). Spring, the big Java framework, resolves the very same object graph, but classically does it eagerly at startup: it finds your service classes, reads their constructors, and builds the entire graph before serving a single request. Here's the one load-bearing contrast: because Spring wires everything at boot, a missing dependency crashes the app at startup — you find out on deploy, not at 3 a.m. on one rarely-hit route — at the cost of slower boot. (Newer Spring pushes this even earlier, to build time, for near-instant startup; the vocabulary there isn't worth learning for our purposes.) Nest, by contrast, resolves more lazily and per-module. Spring's factory-method providers are the conceptual twin of Nest's useFactory — both are "a function that builds a dependency, with its own injected inputs." And Spring's scopes map almost one-to-one onto Nest's, with the identical scope-bubbling footgun. The transferable lesson — the reason this contrast earns its place — is that every serious backend ecosystem independently converged on the same three primitives: a container, a set of scopes, and a single composition root. When two unrelated communities — one on a single-threaded event loop, one on a thread-per-request server — arrive at the same architecture, that architecture is not a fashion. It's a response to a real and recurring problem. Learn the shape; the annotations are just dialect.

🛑 What we deliberately did not explain. How Nest dispatches to the right controller method under the hood (it builds on the same path-to-regexp routing you de-magicked in Express). How class-validator actually walks an object's decorators to validate it. How reflect-metadata polyfills the not-yet-standard Reflect API. How the JVM's reflection and classloader machinery resolves Spring beans. Each is mechanism we located but didn't open, because the chapter's job is to make you fluent in the architecture, not to reimplement the container. The one thing worth internalizing is the resolution model — types-in, instances-out, recursively, as a DAG — because every confusing Nest error message is an error in that model.


5. In production: layout, config, and the pipeline that actually runs​

The toy version of Nest is decorators on a single file. The version that survives three years and seventeen engineers has a shape, and the shape is worth knowing before you need it.

Project layout that survives growth. Organize by feature module, not by technical layer. A patients/, a claims/, a scheduling/ — each a self-contained Nest module — beats a top-level controllers/, services/, repositories/ that forces every feature to smear across three directories. Inside each feature module:

claims/
claims.module.ts # the DI boundary: providers, imports, exports
claims.controller.ts # INBOUND ADAPTER — HTTP in, calls the use case
claims.service.ts # APPLICATION — orchestration, transaction boundary
domain/
claim.entity.ts # DOMAIN — the Claim, its invariants, no I/O
claim.repository.ts # PORT (interface) — "what storage must provide"
clearinghouse.gateway.ts # PORT (interface) — "what claim transmission must provide"
infra/
prisma-claim.repository.ts # OUTBOUND ADAPTER — implements the port via Prisma
clearinghouse.adapter.ts # OUTBOUND ADAPTER — implements the port via the vendor SDK

Plus a thin CoreModule/SharedModule for genuinely cross-cutting providers — the logger, the config service, the database pool — exported once and imported where needed. Resist the god AppModule that imports everything and owns providers; it becomes the new spaghetti. The module graph is your architecture diagram; keep it legible.

Configuration done right — and this is where most teams quietly leak reliability. Do not read process.env in business code. Instead, build a typed ConfigModule (Nest ships @nestjs/config) that loads env at boot, validates it against a schema (Zod, Joi, or class-validator), and exposes a strongly-typed ConfigService. The validation is the point: if CLEARINGHOUSE_KEY is missing, the process should refuse to start, loudly, at boot — not silently run with undefined until the first claim submission at 2 a.m. surfaces it as a 500. Namespace it (config.database.url, config.clearinghouse.key) and inject the slice where it's needed.

// config.schema.ts — the boot-time gate
const schema = z.object({
DATABASE_URL: z.string().url(),
CLEARINGHOUSE_KEY: z.string().min(1), // missing? the app won't boot. Good.
PORT: z.coerce.number().default(3000),
});
export const loadConfig = () => schema.parse(process.env); // throws → process exits at startup

🏭 Fail at boot, not under load. This is the production instinct the bad path violates. A config error caught at startup costs you a failed deploy and a clear log line. The same config error caught lazily costs you a partial outage on a specific code path, a confusing 500, and a debugging session — because the failure is now far in time and space from its cause. The general rule, which you'll meet again when we get to reliability engineering: move failures as early and as loud as you can. Boot-time config validation is the cheapest place to enforce it.

One global validation pipeline as your input-trust boundary. Register ValidationPipe globally with three flags that matter: whitelist: true (silently strip properties not declared on the DTO), forbidNonWhitelisted: true (or reject unexpected properties outright — stronger), and transform: true (hand the controller a real DTO instance, with coerced types, not a plain object). Paired with DTO classes carrying class-validator decorators, this is the structural version of the "validate at the boundary" refrain you've already met — now enforced once, globally, instead of per-handler:

class SubmitClaimDto {
@IsUUID() encounterId!: string;
@IsString() payerId!: string;
// a client that also sends `chargeAmountCents: 1` or `status: 'paid'`? whitelist strips it;
// forbidNonWhitelisted rejects it — those fields are server-owned, never client-supplied.
}

That last comment is the overposting attack, structurally defeated: the client cannot smuggle a chargeAmountCents or status field into your domain, because the DTO doesn't declare one and the pipe drops it before your code ever runs. In a billing system that's not cosmetic — a client that could set its own charge amount or mark a claim paid is a fraud vector.

Cross-cutting concerns as global interceptors and filters, registered once. Request-id propagation, structured logging, timing metrics — interceptors. The uniform error envelope (domain error → HTTP status → problem+json body, the format you've already seen) — an exception filter. The discipline: domain code throws domain exceptions (EncounterNotSignedError, ClaimNotFoundError); the filter is the only place that knows those map to 409 and 404. Status codes live in exactly one file, so they can't drift across twenty handlers.

Async/dynamic modules for things that need config at registration. A database or cache module can't be configured at import time because it needs your ConfigService, which is itself a provider. The forRootAsync pattern threads it through: DatabaseModule.forRootAsync({ useFactory: (cfg) => ({ url: cfg.databaseUrl }), inject: [ConfigService] }). This is how a third-party module receives your config without you reading process.env inside it.

Testing that the layering makes cheap. Two tiers, both fast because of the ports:

// Fast use-case test: swap real ports for fakes, no DB, no network, sub-millisecond.
const moduleRef = await Test.createTestingModule({ providers: [ClaimService, /* ... */] })
.overrideProvider(CLEARINGHOUSE_GATEWAY).useValue(fakeGateway) // no clearinghouse
.overrideProvider(CLAIM_REPOSITORY).useValue(inMemoryRepo) // no Postgres
.compile();
const service = moduleRef.get(ClaimService);
// now test the signed-before-billed rule in isolation — the thing we COULDN'T do in §1.

The exact test that was impossible against the hand-wired handler is now trivial, and that's not a coincidence — it's the testability invariant cashing out. For end-to-end coverage, run supertest against the real assembled pipeline (so guards, pipes, and filters actually execute) but with fakes substituted at the outermost ports.

Operability. Health checks via @nestjs/terminus, split into liveness (am I running?) and readiness (can I serve? — includes a DB ping at the port level), so your load balancer routes only to instances that can actually answer. Graceful shutdown via the lifecycle hooks, draining in-flight requests and closing pools in dependency order on SIGTERM.

🏭 The honest cost the tutorials skip. Nest is not free. Decorator metadata and DI resolution add measurable boot time. The container is a runtime with its own learning surface and stack traces that point into framework internals rather than your code. Module boundaries need ongoing curation — exports lists creep, and "just export it" is how the public API quietly becomes everything. And request-scoped providers degrade throughput in ways that don't show up until load. The senior move with Nest is not adding more of its magic; it's constraining the magic: default to singletons, keep exports lists tight, validate config at boot, and treat every request-scoped provider as a decision you have to justify. Production discipline with a batteries-included framework is mostly about not using the batteries you don't need.


6. Common pitfalls​

Written as signature → fix: the symptom you'll observe, then the principle that resolves it.

"Nest can't resolve dependencies of X (?, Y)." Signature: the app dies at boot with that cryptic message and a ? where a dependency should be. Fix: resolution is module-scoped. The missing provider is either not listed in this module's providers, or it lives in another module that didn't export it (so you can't borrow it) or that you didn't import. The ? is the unresolved slot. Export the contract from the owning module; import the module here. This single error accounts for most of the early Nest frustration, and it's always one of those two omissions.

Injecting an interface yields undefined (or fails outright). Signature: you typed a constructor param as a port interface and the container can't find it. Fix: TypeScript erased the interface at runtime, so there's no type for the container to resolve by. Switch to a string/symbol token: @Inject(CLEARINGHOUSE_GATEWAY) on the param, and { provide: CLEARINGHOUSE_GATEWAY, useClass: ClearinghouseAdapter } in the module. This isn't a bug; it's the erasure tax that hexagonal-in-TS always pays.

Stale data leaking across requests from a "singleton" service. Signature: a service intermittently returns another patient's data; it's worse under load and impossible to reproduce in a single-request test. In healthcare that intermittent leak is not a nuisance — it's a reportable HIPAA breach. Fix: the singleton is holding mutable per-request state on a shared instance — this.currentPatient = ... on an object every request touches. Make it stateless and pass context as an explicit argument, or (knowing the cost) make it request-scoped. Never store request data on a shared instance. This is the scope-containment invariant being violated in the wild.

The whole app silently becomes request-scoped and throughput craters. Signature: you made one provider request-scoped, and now p99 latency climbed across endpoints that don't even use it. Fix: "scope bubbling" — a singleton that depends on a request-scoped provider must itself become request-scoped to keep its dependency fresh, and that propagates up the entire graph, disabling reuse everywhere. Break the dependency (make the inner provider stateless), or use durable providers / ContextIdFactory to inject request context without infecting scope. Audit what made you reach for request scope; it's rarely necessary.

Circular dependency error between two services. Signature: A needs B needs A; Nest reports a cycle. Fix: it's a design smell, not a wiring puzzle. Extract the shared concept into a third provider both depend on, or invert one direction through an event/port. forwardRef() exists, but it hides the smell rather than removing it — reach for it only when the cycle is genuinely irreducible (rare), and treat its presence as a TODO.

Validation "works" but unknown fields reach the database. Signature: a client sends { encounterId: '...', status: 'paid' } and status ends up persisted on the claim. Fix: whitelist/forbidNonWhitelisted aren't set on the global ValidationPipe, so the DTO accepted extra properties — a mass-assignment / overposting hole. Turn them on; the DTO's declared shape becomes the hard allow-list.

A config var missing only blows up in production, under one specific route. Signature: everything works until a rarely-hit endpoint reads config.clearinghouse.key and finds undefined. Fix: there's no boot-time schema validation. Validate the entire config object at startup so the process refuses to boot with a missing required var — turning a lurking runtime landmine into a loud, immediate deploy failure.

The domain layer imports @nestjs/common or the clearinghouse SDK. Signature: your Claim entity has import { Injectable } from '@nestjs/common' or reaches for a Prisma type. Fix: a boundary violation — the inner ring grew an outward dependency, breaking the one law of the rings. The framework decorator or vendor type belongs in an adapter; the domain depends only on ports it owns. If your domain can't be unit-tested without importing Nest, the architecture has already started to rot.

Connection pool exhaustion under load. Signature: too many connections errors despite "having a pool." Fix: some provider news its own pool instead of injecting the shared one — you have N pools where you meant to have one. Centralize the pool as a single provider (useFactory) and inject the one instance everywhere. The container is precisely what makes "exactly one pool" enforceable rather than aspirational.


7. Tradeoffs​

Senior engineering is naming the spectrum and saying why you stand where you stand. The central decision of this chapter is layered-vs-hexagonal, so start there.

Layered ↔ hexagonal — and the asymmetry that resolves it. Plain layering (controller → service → repository, the repository typed as a concrete class) is cheap, obvious, and what most CRUD wants. Its cost: the domain depends on the ORM/vendor — your service imports the Prisma repository directly, so "the rule" and "the storage tech" are fused, and you can't unit-test the rule without a database. Hexagonal adds port interfaces and adapter indirection — more files, the token ceremony — to buy true swappability and genuinely pure domain tests. The naïve instinct is to pick one and apply it uniformly. The senior instinct is asymmetry: spend hexagonal's ceremony where it pays — high-value, rule-rich, integration-heavy modules like claims, eligibility, messaging, which have real invariants and volatile external partners behind ports (clearinghouses, payers, and messaging vendors all change, and some go dark) — and use plain layering for the thin, anemic modules like a patient-search read-model or a worklist projection, where the domain is barely more than a DTO and no second adapter will ever exist. Uniformity is not a virtue. Match the ceremony to the volatility and the value. This asymmetry is the chapter's ADR.

DI container ↔ manual wiring. A container removes boilerplate and centralizes lifecycle, but it adds a runtime, metadata magic, and stack traces that point into framework internals. For a tiny service or a library, a twenty-line hand-rolled composition root is more honest — you can read the whole graph in one screen and there's no magic to debug. Reverse toward manual wiring when the graph is small and startup determinism matters more than convenience. The container earns its keep when the graph is large and the lifecycle is real.

Constructor injection ↔ service locator (moduleRef.get). Constructor injection is statically analyzable and test-friendly: the dependencies are right there in the signature. The service-locator pattern — reaching into the container at runtime to get what you need — hides dependencies inside method bodies and defeats the entire point of DI (you're back to summoning, just through a fancier door). Allow the locator only for genuinely dynamic resolution where the dependency isn't known until runtime; treat every other use as a code smell.

Singleton ↔ request scope. Singletons are fast and shared but force statelessness. Request scope is ergonomic for carrying per-request context but costs a fresh subgraph allocation per request and risks scope bubbling. Default to singleton plus explicit context-passing; escalate to request scope only at a measured, contained boundary, and never let it bubble into a hot singleton.

Global ↔ per-module/per-route providers. Global interceptors/pipes/filters are DRY and consistent — register validation, error-shaping, and logging once and they cover everything. Per-route is precise but easy to forget (a new endpoint silently ships without validation). Prefer global for the security- and correctness-critical concerns (validation, authz scaffolding, error shaping); reserve per-handler overrides for true exceptions.

Nest's batteries-included opinion ↔ minimal Express. Nest buys structure, a testing harness, and team consistency — seventeen engineers write recognizably the same code. It costs a steeper mental model and framework lock-in inside your adapters. But notice the escape: the hexagonal boundary is precisely how you cap that lock-in. The Nest-isms live in the controllers and the adapter ring; the domain stays portable. You're not avoiding lock-in, you're containing it to the outer ring on purpose.

🚫 A framing this book rejects. "Hexagonal architecture is always cleaner, so apply it everywhere." This is how a five-route CRUD service grows forty files, a port-and-adapter pair for a table that will only ever be Postgres, and a token registry nobody can navigate. Architecture has a cost, paid in indirection and files and onboarding time, and that cost is only justified by volatility and value. A module whose domain is anemic and whose storage will never change is worse with ports, not better — you've added ceremony that buys nothing. The discipline isn't "always invert"; it's "invert where the dependency is volatile or the rule is valuable, and stay flat everywhere else." Cleanliness that ignores cost is just a different kind of mess.


8. Security & scale notes​

Security and scale aren't a separate chapter; they're properties of the architecture you just built. Here's where this chapter's structure first touches each.

The input-trust boundary is now structural. The global ValidationPipe is your first line against mass-assignment and injection-shaped payloads — and because it's global and DTO-driven, "did we validate?" stops being a per-handler question you can forget. forbidNonWhitelisted blocks overposting (the client can't set fields your DTO doesn't declare — no self-set charge amounts, no client-forced claim status); transform coerces types before they reach domain logic. And the ordering is itself a control: guards run before pipes, so you authorize before spending validation CPU on a hostile body. Cheap rejection first, expensive parsing second.

Authorization belongs in guards, read via metadata — not scattered in controllers. Centralizing authz in guards that read @Roles/@Permissions metadata through the Reflector shrinks the surface where a check can be forgotten, and — just as important — makes "is every chart-access route guarded?" an auditable property. You can grep for the decorator and the guard registration; you cannot grep for the absence of a forgotten if. In a PHI system a single missing check is a reportable breach, so making the check structural rather than incidental is a compliance win, not just a tidiness one. (The full auth model — tokens, sessions, RBAC vs ABAC, minimum-necessary access, break-glass — is its own chapter later; here we only establish where the check structurally lives.)

Exception filters must not leak internals. Domain exceptions map to safe, generic HTTP envelopes; stack traces, SQL errors, and vendor messages never reach the client. Because exactly one filter owns that mapping, there's no per-handler path through which an internal detail — a raw payer error, a patient identifier in a stack trace — can accidentally escape. The leak surface is one file you can review, not twenty.

Boot-time config validation is a security control, not just a reliability one. A missing or empty secret that fails fast can't silently disable auth or run the app with a default/blank signing key. The §5 schema that refuses to boot without CLEARINGHOUSE_KEY is the same mechanism that refuses to boot with an empty JWT secret — fail closed at startup beats running insecure.

Now scale:

The container is what makes "exactly one pool" enforceable. Singleton providers plus a single shared, injected pool/HTTP-client keep connection counts bounded under concurrency — and bounded connections are what keep you off the saturation cliff. The bad path's two-pools bug wasn't just untidy; it was a path to connection exhaustion under load. DI turns "one pool" from a convention into a structural guarantee.

Request-scoped providers are a load footgun. Every request-scoped provider forces a fresh subgraph allocation per request and disables provider reuse; at high RPS this multiplies GC pressure (and on the single event loop, GC pauses are everyone's latency). Measure before adopting request scope, and never let it bubble into a hot singleton — the throughput regression is real and sneaky.

Module boundaries are the precondition for limiting blast radius. Explicit imports/exports give you the dependency map that §1 lacked. That map is what lets a failing messaging adapter — or the clearinghouse itself going dark, which really happens — be isolated behind its port, with a fallback or a queued retry, rather than synchronously dragging claim submission down with it. The port boundary is the seam at which you can later insert a circuit breaker, a timeout, a bulkhead. You can't isolate what you can't draw a line around; the module is the line.

🔑 Boundaries are a prerequisite, not a bonus. Every resilience pattern you'll meet later — timeouts, retries, circuit breakers, bulkheads, fallbacks — needs a seam to live in. A port is that seam. So the in-process architecture you draw in this chapter isn't separate from reliability; it's the substrate reliability is built on. A tangle has nowhere to insert a circuit breaker. A clean port boundary has an obvious one. Architecture earns its keep first in testability, and second — often more valuably — in giving failure somewhere to be contained.


9. Interview lens & exercises​

Interview questions​

The same question separates levels by whether you reason about the consequences of the design or merely recite its parts.

"Why use a DI container instead of just importing what you need?"

  • Junior answer: "so you don't write new everywhere." True but shallow — it treats DI as boilerplate reduction.
  • Senior answer: frames it as three things at once — lifecycle ownership (one place builds and disposes the pool, fixing leaks and double-pools), testability (every collaborator arrives by constructor so a test substitutes fakes with zero global state), and dependency inversion (the domain depends on ports, not vendors). Then names the costs honestly — runtime magic, boot time, harder stack traces — and says when they'd skip the container: a tiny service or library where a twenty-line manual root is more honest. Knowing when not to use the tool is the senior signal.

"Walk me through Nest's request lifecycle, and name one decision the ordering forces."

  • Junior: lists "middleware, guards, pipes, controller, filters" — the names, no consequence.
  • Senior: recites middleware → guards → interceptors → pipes → controller → interceptors → filters, and draws out that guards run before pipes, so authorization happens before you pay to validate a large hostile body — a deliberate DoS-resistance ordering. The ordering consequence, not the list, is the answer.

"How do you inject an interface in TypeScript, and why is it awkward?"

  • Junior: "just inject the class." Misses that an interface isn't a class.
  • Senior: explains type erasure — the interface has no runtime identity for the container to resolve by — so you need a string/symbol token plus @Inject(TOKEN) and a { provide, useClass } binding, and ties it directly to why hexagonal architecture in TS specifically needs explicit ports where a language with reified types wouldn't.

"Layered vs hexagonal — when do you actually pay for hexagonal?"

  • Junior: "hexagonal is always cleaner."
  • Senior: gives the asymmetric answer — full ports-and-adapters for high-value, volatile, integration-heavy modules (claims, eligibility, messaging); plain layering for anemic CRUD where no second adapter will ever exist — and cites the concrete cost (more files, token registries, indirection) that makes uniform hexagonal a mistake. Names the spectrum, then places the decision on it per-module.

"A service starts intermittently returning another patient's chart. What's the DI angle?"

  • Junior: blames a caching bug and stops.
  • Senior: immediately suspects per-request state stored on a singleton — a scope mismatch where a shared instance accumulated one request's context and served it to the next — and gives the fix (make it stateless and pass context explicitly, or go request-scoped knowing the throughput cost). In a PHI system they also flag it as a reportable breach, not just a bug. The reflex to reach for scope as the cause is the senior tell.

Exercises & the Pulsely increment​

Do these in order; each builds the muscle the next one needs.

  1. Restructure Pulsely into Nest feature modules. Take the hand-wired Express surface from earlier and split it into PatientsModule, EncountersModule, SchedulingModule, ClaimsModule, WorklistModule, AlertsModule, SearchModule, plus a CoreModule for the logger, config, and database pool. Draw the module graph with import/export edges before you write code — if you can't draw it, you don't yet understand your own boundaries.

  2. Make ClaimsModule fully hexagonal. Define ClaimRepository and ClearinghouseGateway as port interfaces the domain owns. Provide a PrismaClaimRepository and a ClearinghouseAdapter as outbound adapters, bound via symbol tokens and useClass. Then write the unit test that was impossible in §1: instantiate ClaimService through Test.createTestingModule with both ports overridden by fakes, and assert the signed-before-billed rule rejects a claim for an unsigned encounter — with no database and no network touched. If that test runs in single-digit milliseconds, your wiring is right.

  3. Port auth and validation from Express to Nest. Convert the hand-wired auth middleware into an AuthGuard that reads @Roles metadata via the Reflector, and the per-route validation into DTO classes behind a global ValidationPipe with whitelist/forbidNonWhitelisted/transform. Prove the win: send an overposting payload ({ encounterId: '...', chargeAmountCents: 1, status: 'paid' }) and assert the server-owned fields are rejected before any handler runs — the overposting attack, structurally dead.

  4. Build a fail-fast ConfigModule. Load env, validate against a schema at boot, expose a typed ConfigService. Then remove a required secret and confirm the process refuses to start with a clear error — contrast that against the old behavior of crashing mid-request on a specific route. Internalize the difference in where in time the failure surfaces.

  5. Induce and fix the two classic DI failures. Deliberately create a circular dependency between two services and a "scope bubbling" throughput regression (make a hot singleton depend on a request-scoped provider). Diagnose each from its symptom, then fix it the right way (extract a third collaborator / invert via an event; make the inner provider stateless) rather than the bandage way (forwardRef; escalating scope).

  6. Write ADR-014 — "Layering vs hexagonal boundary for Pulsely." Record the central asymmetric decision: which modules get full ports-and-adapters (claims, eligibility, messaging — rule-rich, external partners volatile) and which stay plain-layered (patient-search, worklist — anemic, single-adapter), where exactly the framework/domain seam sits, and the cost you knowingly accept for that asymmetry (two architectures in one codebase, a token registry, the discipline to keep the domain framework-free). The rejected alternative — uniform hexagonal everywhere — and why you rejected it (ceremony with no payoff for anemic modules) is the most valuable paragraph in the document.


Key takeaways​

  • Hand-wired code summons its dependencies; that makes it untestable, leak-prone, and tangled. DI inverts the arrow: code declares what it needs and a container provides it. The principle (be handed your collaborators) is bigger than any framework; the container is just ergonomics over it.
  • Architecture is rings with inward-only arrows: domain at the center (pure, stable, depends on nothing concrete) → application → ports (interfaces the inside owns) → adapters (vendors, at the edge). The domain becomes a portable library; vendors fit your contract, never the reverse.
  • Dependency inversion (arrows toward stability) is the goal; dependency injection (constructor-handed collaborators) is one technique for it — keep them distinct. Constructor injection makes "can't run without X" a structural fact, not a hope.
  • Scope discipline is where DI bugs live: default to stateless singletons and pass context explicitly; a singleton depending on a request-scoped provider either leaks cross-request state (in PHI systems, a reportable breach) or bubbles scope until throughput collapses.
  • Every Nest abstraction is a named slot in the Express pipeline you already built: middleware → guards → interceptors → pipes → controller → interceptors → exception filters. The ordering is load-bearing — guards before pipes means authorize before you pay to validate.
  • In TypeScript, interfaces erase at runtime, so ports must be injected by string/symbol tokens — the specific reason hexagonal-in-TS carries a token tax. Worth paying where volatility and value justify it.
  • Match ceremony to value: hexagonal for rule-rich, vendor-volatile modules; plain layering for anemic CRUD. Uniformity is not a virtue; asymmetry is the senior choice (and Pulsely's ADR).
  • Validate config at boot and input at the global pipe — fail fast, fail loud, fail closed. A port boundary is also the seam every later reliability pattern (timeout, retry, circuit breaker, bulkhead) needs to exist; clean in-process architecture is the precondition for both testing and resilience.

← Previous: Ch 13 — Express From First Principles · Up: Part III overview · Master TOC · Next: Ch 15 — Relational Foundations →