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) { ... }wheredepscarries 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 aClearinghouseAdapter"); 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
ClaimServicelives, 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 definesClearinghouseGateway, 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 Express | Nest calls it | What it does |
|---|---|---|
app.use(fn) cross-cutting middleware | Middleware | runs on raw req/res, before DI-resolved metadata |
your requireAuth middleware | Guard | returns a boolean: may this request proceed? |
your asyncHandler / timing wrapper | Interceptor | wraps the handler: transform input/output, time it, cache it |
your per-route validate(schema) | Pipe | validate + transform the handler's arguments |
| the route handler itself | Controller method | the actual endpoint logic |
| your single terminal error middleware | Exception filter | catch thrown errors, shape the HTTP response |
| your forty-line manual composition root | DI container | build 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
importthe clearinghouse SDK. Instead, the rule depends on aClearinghouseGatewayinterface 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 anonSubmitprop instead of callingfetch('/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 aClearinghouseGatewayinterface 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
ClaimServiceis 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
submitClaimwas 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
exportslist is its public API; everything else is implementation you're free to change without consulting your neighbors.