A NestJS service builds. Its unit tests pass. Its end-to-end suite boots it and every check is green. Then the container starts and dies before logging a single line:
Error: Cannot find module '@platform/common'Nothing in the code changed between the green run and the red one. Only the folder it ran from.
The second monorepo bug is quieter. One commit changes a gRPC contract, the server that implements it and both services that call it. Every test passes, because every test compiles all four against the same version of the contract. Then the services deploy one at a time, and for a while an old caller talks to a new server. No test ever ran that pair.
Both bugs come from one fact: a commit is atomic, but thirteen deploys are not. Here is how a platform of thirteen NestJS services and four shared libraries lives in one Nx workspace without either bug slipping through quietly, and what that costs. It is a prototype, so this is the design and the checks in the repository, not production numbers.
Why keep 13 NestJS microservices in one Nx monorepo?
At runtime these services are independent: each process starts, scales and crashes alone. At design time they are not. They share three things that must agree exactly:
- Contracts. gRPC
.protofiles, Zod schemas and versioned Kafka event envelopes. - Foundation code. Typed errors, pagination cursors, idempotency keys, correlation ids, graceful shutdown.
- Tooling. One lockfile, one TypeScript base config, one lint config, one Node version.
With a repository per service, each shared piece becomes a published package, and each change becomes a release plus thirteen version bumps. The most useful fact, who breaks if I change this field?, ends up scattered across thirteen repositories. In one workspace, a contract change and every line that uses it land in the same diff.
The picture I use is an apartment block. The flats share a foundation, a frame and the risers that carry water between floors; building those once is why the block exists. But every flat has its own front door and its own meter. Nobody walks through a neighbour's living room to get home, and nobody's bill depends on the flat next door.
A monorepo for microservices is the same deal: share the foundation on purpose, keep doors and meters separate on purpose. The two bugs above are a flat secretly wired to the corridor socket, and a riser swapped while people still live upstairs.
What goes in apps/ and what goes in libs/?
apps/
order-service/ project.json, package.json, Dockerfile, webpack config
order-service-e2e/ boots the real service; implicitly depends on it
(12 more service + e2e pairs)
libs/
contracts/ .proto files, Zod schemas, event contracts, split by owner
common/ primitives that more than one service reuses
config/ environment parsing and validation
object-storage/ a storage port and its S3 adapter (one consumer today)Each service declares the libraries it uses as workspace dependencies:
{
"name": "order-service",
"dependencies": {
"@platform/common": "workspace:*",
"@platform/config": "workspace:*",
"@platform/contracts": "workspace:*"
}
}workspace:* tells pnpm to link the local folder instead of downloading a published version. That link is the shared riser: edit contracts, and the type checker points at every consumer that broke, in the same commit.
Shared rooms need house rules. In contracts, a service edits only its own files (proto/<service>/v1/ and one TypeScript module). Code enters common only if more than one service needs it and it carries no business rule.
How do Nx module boundaries stop one service importing another?
Nx builds a project graph from imports and package.json dependencies. The @nx/enforce-module-boundaries lint rule checks every import against it. Even with no custom rules, it rejects importing an application, reaching into another project by relative path, and circular dependencies between projects.
Those are the front doors. Services are applications: you can't import one by package name, and you can't reach into one by relative path. So this fails lint:
// apps/reporting-service/src/app/totals.ts
// lint error: "Projects cannot be imported by a relative or absolute path"
import { sumOrderLines } from '../../../order-service/src/app/order-lines';If reporting needs that logic, it moves into a shared library with a name and a reason, or it goes over the wire. No service folder imports another today, so the doors hold.
Why wildcard tags enforce nothing
Tags add a second layer. Services carry scope:<name> and type:service; libraries carry scope:shared plus type:foundation, type:contract or type:infrastructure. In depConstraints you declare which tags may depend on which. Here is what the workspace actually declares:
depConstraints: [{ sourceTag: '*', onlyDependOnLibsWithTags: ['*'] }],Any project may depend on any library. The tags are nameplates on doors with no lock behind them. One service has an empty tag list, no end-to-end project has tags at all, and under the wildcard nobody notices.
That also makes the fix harder than it looks. Once a real constraint exists, Nx refuses to let a project whose tags match no constraint depend on any library, so every untagged project fails lint on the same day.
Why does one change in a shared library rebuild everything?
nx affected takes two commits, maps each changed file to the project that owns it, then walks the graph up to every project that depends on those. CI uses it for lint and type checking:
pnpm nx affected -t lint --base="$NX_BASE_SHA" --head="$NX_HEAD_SHA" --parallel=2
pnpm nx affected -t typecheck --base="$NX_BASE_SHA" --head="$NX_HEAD_SHA" --parallel=6You can ask the graph what a change will touch:
pnpm nx show projects --affected --files=libs/common/src/index.tsFor common, the answer is everything. All thirteen services depend on common, config and contracts, and each end-to-end project depends on its service. That isn't Nx being lazy; it's the graph being honest. Repair the foundation and every flat needs an inspection. affected is only as selective as your graph is narrow, and a fat shared library turns every small change into foundation work.
The cache only knows the inputs you declare
Before a task runs, Nx hashes its inputs: source files, configuration, dependency versions, arguments. If the hash matches an earlier run, Nx replays the saved output. A cache is a promise, same inputs, same output, and the promise is only as good as the input list.
Each service's webpack config copies the .proto files it loads into its bundle, and each build lists proto files as inputs, one by one (excerpt):
"inputs": [
"default",
"{workspaceRoot}/prisma/order/**/*",
"{workspaceRoot}/libs/contracts/proto/order/v1/order.proto",
"{workspaceRoot}/libs/contracts/proto/item/v1/item.proto"
]Two hand-kept lists of one fact. When I compared them, four services named proto files in their webpack assets that their build inputs never mention: seven files in all, three in the order service, one of which it loads at runtime to call another service. Edit that file and the build hash doesn't move, so a cached build would ship yesterday's contract.
The blast radius is small today: CI starts each job with an empty Nx cache and .nx is excluded from the Docker build context, so only a developer's machine can be bitten. It becomes a CI bug the day someone turns on remote caching. I found the gap by reading, not by being bitten.
The wrong fix is "be more careful". Either declare the whole folder, {workspaceRoot}/libs/contracts/proto/**/*, as two services already do (more rebuilds, never wrong), or generate both lists from one manifest.
Can each NestJS service deploy on its own?
Back to the first bug. Node resolves require('@platform/common') by walking up from the requiring file and checking each node_modules folder on the way. Inside the workspace, apps/order-service/node_modules/@platform/common is a pnpm symlink into libs/common, so the walk always succeeds. Copy only dist/ into an image, and the walk finds nothing.
Two tempting fixes are both wrong. Copying the whole workspace into the image boots, but ships thirteen services' code and proves nothing. Adding the missing package by hand starts a list that drifts on the first refactor.
The rule instead:
A service's build must produce an artifact that runs with no workspace around it.
In other words, each flat runs off its own meter. build compiles one service with webpack, leaving node_modules imports as runtime require calls. Then prune runs two Nx executors:
"prune-lockfile": { "executor": "@nx/js:prune-lockfile", "dependsOn": ["build"] },
"copy-workspace-modules": { "executor": "@nx/js:copy-workspace-modules", "dependsOn": ["build"] },
"prune": { "executor": "nx:noop", "dependsOn": ["prune-lockfile", "copy-workspace-modules"] }prune-lockfile writes a package.json and pnpm-lock.yaml into dist/ with only this service's dependencies. copy-workspace-modules copies the built shared libraries into dist/workspace_modules/, so the artifact carries its own copies instead of symlinks into libs/.
Then something has to prove it, which is the step most setups skip. A CI job copies each pruned artifact to a temporary directory outside the workspace, runs pnpm install --prod --frozen-lockfile against the artifact's own lockfile, and boots it with a guard preloaded. The service passes only when its liveness check answers.
Why a guard, if the artifact is already outside? The temporary directory is on the same machine, and the workspace is still on disk. An absolute path baked in at build time, or a symlink back into libs/, would still resolve, and the check would pass for the wrong reason. The guard turns "it happened to work" into "it cannot reach back". A trimmed version you can drop into any Node project:
// guard.cjs: run with node --require ./guard.cjs main.js
const Module = require('node:module');
const path = require('node:path');
const artifactRoot = path.resolve(process.env.ARTIFACT_ROOT ?? process.cwd());
const workspaceRoot = path.resolve(process.env.WORKSPACE_ROOT ?? process.cwd());
function isInside(parent, candidate) {
const relative = path.relative(parent, candidate);
return (
relative === '' ||
(relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
);
}
const resolveFilename = Module._resolveFilename;
Module._resolveFilename = function guardedResolve(request, ...rest) {
const resolved = resolveFilename.call(this, request, ...rest);
const escapes = isInside(workspaceRoot, resolved) && !isInside(artifactRoot, resolved);
if (path.isAbsolute(resolved) && escapes) {
throw new Error(`${request} resolved outside the artifact: ${resolved}`);
}
return resolved;
};Module._resolveFilename is internal and undocumented: fine for a CI check, not something to ship inside a service. A second script checks each artifact for the proto files and runtime dependencies it must contain.
The image build repeats the recipe. One parameterized Dockerfile produces twelve of the thirteen runtime images and all thirteen migration images (trimmed: corepack setup and cache mounts removed):
FROM node:24-bookworm AS build
WORKDIR /workspace
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
# Depends only on the lockfile, so source edits don't refetch packages.
RUN pnpm fetch --frozen-lockfile
COPY . .
RUN pnpm install --offline --frozen-lockfile
ARG SERVICE_NAME
RUN pnpm nx run-many -t build -p common config contracts \
&& pnpm nx run "${SERVICE_NAME}:build" \
&& pnpm nx run "${SERVICE_NAME}:prune"
FROM node:24-bookworm-slim AS runtime
WORKDIR /app
RUN chown node:node /app
USER node
ARG SERVICE_NAME
COPY --from=build --chown=node:node /workspace/apps/${SERVICE_NAME}/dist/ ./
RUN pnpm install --prod --frozen-lockfile
CMD ["node", "main.js"]The migration image gets only its own service's Prisma schema and migrations, so it cannot touch another service's database. Where the images run is a separate decision: Docker Compose or Kubernetes for 13 microservices.
How do you change a gRPC contract when deploys aren't atomic?
The meter check proves each flat runs alone. It says nothing about two flats on different versions sharing a riser. The compiler sees one version of every contract; production sees two, for as long as a rollout takes. Hence the second half of the rule:
Every contract change must work against the version of each peer that is already deployed.
The event conventions say it directly: backward-compatible additions within a version; anything breaking gets a new version and a migration window. That's why proto packages and Kafka topics carry v1. A breaking change then takes three deploys, not one commit:
- Expand. Add the new field next to the old one. The server accepts both.
- Migrate. Callers switch to the new field, one deploy at a time.
- Contract. When no deployed caller sends the old field, delete it and reserve its number and name.
A real shape from the contracts library, names changed. A boolean was replaced by an enum, and the boolean stayed:
enum RecomputeMode {
RECOMPUTE_MODE_UNSPECIFIED = 0;
RECOMPUTE_MODE_USE_CURRENT = 1;
RECOMPUTE_MODE_RECOMPUTE = 2;
}
message RecomputeScoreRequest {
string subject_id = 1;
string period = 2;
bool force_recompute = 3 [deprecated = true];
string idempotency_key = 4;
RecomputeMode recompute_mode = 5;
// Step 3, once no caller sends it, replaces field 3 with:
// reserved 3;
// reserved "force_recompute";
}The catch I only saw while reading the handler: it reads recompute_mode alone. An old caller still sending force_recompute = true gets a valid reply that ignores its request and uses the current value. No deployed caller sends the old field, so nothing breaks today. But "still on the wire" and "still honoured" are different promises, and deprecated only makes the first. During the window, the server should translate:
function effectiveMode(request: RecomputeScoreRequest): RecomputeMode {
if (request.recomputeMode && request.recomputeMode !== 'RECOMPUTE_MODE_UNSPECIFIED') {
return request.recomputeMode;
}
return request.forceRecompute ? 'RECOMPUTE_MODE_RECOMPUTE' : 'RECOMPUTE_MODE_USE_CURRENT';
}Why reserve numbers? Protobuf identifies fields by number, not name, so reusing one lets an old peer decode garbage without an error; the protobuf dos and don'ts put this near the top. For JSON and events, the mirror rule: a consumer that rejects unknown fields turns every addition into a breaking change.
What protects this today is a written convention plus code review, the weakest kind of protection. Nothing in CI runs an old caller against a new server.
Monorepo or polyrepo for microservices?
| Question | One Nx workspace | One repo per service |
|---|---|---|
| Change a shared contract | One diff: producer, consumers, tests | Publish a package, bump it everywhere |
| Know who depends on what | Computed from imports | A list someone maintains |
| Stop service-to-service imports | A lint rule | Nothing to import; coupling moves into copied code |
| Ship one service | Needs pruning and an isolation check | The default |
| Upgrade build tooling | Once | Thirteen times, drifting apart |
I wouldn't do this for teams with different release rhythms and few shared contracts, or for two services, where a folder and a script will do. And if nobody will enforce boundaries, a monorepo becomes a distributed monolith with thirteen Dockerfiles. (The workspace itself is a pinned submodule in a meta-repo next to the frontend, a separate decision covered in Git submodules in a meta-repo.)
What it costs
The shared library becomes the lobby where everyone leaves furniture. Services can't import each other, so coupling migrates into common, which over a thousand import statements now point at. Its written admission rule says no NestJS, no Kafka, no Prisma, no controllers or decorators, no retries. Today it exports a NestJS health controller, auth decorators, a rate-limit guard, a Kafka topic helper, a Postgres connection helper and a lease-and-retry policy for background workers. Each addition was reasonable on its day. Together they mean every service installs the Kafka client, and a Kafka helper change marks services that never publish an event as affected. The outbox relays themselves stayed inside each publishing service; they're the subject of the transactional outbox article.
CI time grows with the graph, not the change. Unit tests run from a fixed four-shard matrix, and the artifact job builds, prunes and boots all thirteen services on every pipeline.
Hand-kept copies drift. The proto list lives in three places per service. The Dockerfile recipe lives in fourteen: one per service for the local stack, plus the shared one for CI. They've already diverged: the per-service migration stage copies the whole workspace, the shared one only that service's schema.
Nx is load-bearing. Builds, pruning and serving all go through Nx plugins and executors, pinned to one exact version because they upgrade as a unit. Leaving Nx means rewriting all three for thirteen services.
The guard only sees what loads. A dynamic import() on a rarely used path escapes it until that path runs.
Even the decision record calls the monorepo a direction observed in a prototype, not a verified release workflow. That's the right label.
What I'd do differently
Lock the doors from day one, and ban frameworks in foundation code so the admission rule is checked by lint instead of memory:
depConstraints: [
{ sourceTag: 'type:service', onlyDependOnLibsWithTags: ['scope:shared'] },
{ sourceTag: 'type:contract', onlyDependOnLibsWithTags: ['type:foundation'] },
{ sourceTag: 'type:infrastructure', onlyDependOnLibsWithTags: ['type:foundation'] },
{
sourceTag: 'type:foundation',
onlyDependOnLibsWithTags: ['type:foundation'],
bannedExternalImports: ['@nestjs/*', 'kafkajs', '@prisma/*'],
},
],Then tag the untagged projects. Applied today, this fails on common, and the list of failures is the refactoring plan.
Split common by what it drags in: a framework-free core, plus separate NestJS HTTP, messaging and database libraries. Services that never publish events stop depending on Kafka, and affected narrows for free.
Generate lists instead of writing them: one proto manifest per service, read by webpack, build inputs and the verifier; one Dockerfile for the local stack and CI.
Check protos for breaking changes in CI. Buf's buf breaking compares contracts against the main branch and fails on a removed field or a reused number. It wouldn't catch the ignored boolean, but it takes a whole class of mistakes out of review.
Make unit tests affected-aware on merge requests, and keep the full run on the main branch.
None of this changes the core decision. One workspace keeps contracts visible and tooling consistent; the pruned, guarded artifact keeps each service in its own flat.
Key takeaways
- A commit is atomic; deploys are not. Design for the window when two versions run side by side.
- Every artifact must boot with no workspace around it. Prove it in CI: copy out, install from its own lockfile, boot behind a guard.
nx affectedis only as narrow as your graph, and the cache only as honest as your input list.- Wildcard tag constraints enforce nothing. Add real ones before untagged projects pile up.
- Change contracts by expand, migrate, contract, and check that the server honours the old field, not just accepts it.
The code lives in one place now, but the services still have to talk; REST, gRPC or Kafka is about which conversation gets which transport.