Principles
The ideas the stack is built on, from its philosophy and SOLID to data correctness and the anti-patterns it avoids.
This page says what the stack believes and shows where the code proves it. Every example names a file. If a claim has no file behind it, it is not on this page. The philosophy paragraphs are a draft for the maintainer to correct.
How to use this page when refactoring
Read the entry for the area you are changing before you edit. Each entry has a rule, the place in the repo that shows it, and a way to spot a violation. After the change, read the entries again and ask whether your diff breaks any rule. The anti-patterns at the end are the quick list of things a reviewer should push back on. The stack choices themselves, and why each library was picked, are on the stack page, and the layer map is in architecture.md.
Philosophy
Highly opinionated
The stack is a boilerplate with one answer for each choice, not a menu. There is one logging library, one test runner, one form stack and one package manager. If a project disagrees with a choice, the argument happens in the stack, not as a per-project override. That is why shared lint and format config is kept identical across projects and changed only in the stack (see Conventions in AGENTS.md).
API first and contract first
The contract comes before the handler. Each service has a contracts/<name>-contracts package, and the server handler is
written against it. services/todo-service/src/lib/create-app.ts builds its router with implement(todoContract), so a
handler that does not match the contract in contracts/todo-contracts/src/todo.contract.ts fails to compile. The contract
composes schemas from models/todo-model, so the shapes are written once.
RPC for our own clients and OpenAPI for everyone else
Our own TypeScript clients call typed oRPC endpoints under /rpc. Everyone else gets a generated OpenAPI document and
plain HTTP under /api. Both are served from the same router: libs/server-setup/src/lib/orpc-server.ts creates an
RPCHandler and an OpenAPIHandler for it. The OpenAPI document is not written by hand. .meta({ id }) on a model schema
names its component, and services/todo-service/src/lib/openapi-schemas.ts lists which schemas become components. The web
app calls the API through oRPC in apps/todo-ui/src/lib/orpc.ts.
AI native
The repo is set up so an AI agent needs little context and makes few wrong guesses.
AGENTS.mdholds the rules an agent must follow, andCLAUDE.mdimports it..claude/skillsholds one skill per recurring task, for exampleapi-endpoints,form-builderanddomain-repository-tests.- Generators in
tools/nx-plugin/generatorscreate new packages, so an agent runs a generator and does not copy code. - A code graph is preferred over grep. AGENTS.md says to use one when installed, and
.trail/holds the trail index and saved learnings.fallowchecks layer boundaries. - Packages are small and each has one job, which keeps the context an agent needs for a change short.
SOLID
Single responsibility
- Rule. A package does one job, and a file inside it does one part of that job.
- In this repo.
libs/rate-limit/src/libsplits the work intorate-limit-provider.ts(the storage port),rate-limiter.ts(the limit logic) andrate-limit.middleware.ts(the oRPC glue). Adomains/*package is a Mongoose schema and a repository, and the fallowdomainszone in.fallowrc.jsononly lets it import foundation libs, models and other domains, so it cannot reach HTTP or contracts. - How to spot a violation. You need the word "and" to describe a package, a repository method also formats an HTTP response, or a lib starts importing from a layer above it.
Open/closed
- Rule. Add behavior by adding a procedure or a middleware, not by editing code that already works.
- In this repo. In
services/todo-service/src/lib/create-app.tseach cross-cutting concern is one.use(...)in a chain (rate limit, authenticate, audit, intent guard, trace, cache). Adding a new concern is one more line, and adding an endpoint is a new key in the router. - How to spot a violation. A change to one endpoint edits a shared function, or you add an
if (procedure === "x")branch to a middleware that every procedure runs.
Liskov substitution
- Rule. Any implementation of a port must behave as its type promises, so a caller never needs to know which one it got.
- In this repo.
libs/cache/src/lib/memory-cache-provider.tsandredis-cache-provider.tsboth return aCacheProviderand both validate TTLs with the sameassertValidCacheTtl. For rate limits,libs/rate-limit/src/lib/memory-rate-limit-provider.ts,redis-rate-limit-provider.tsandconnectors/mongodb-connector/src/mongo-rate-limit-provider.tsall return aRateLimitProvider. The service increate-app.tsnever learns which one is behind itsrateLimiter. - How to spot a violation. A caller checks which provider it has, a provider throws an error the others do not, or one provider ignores part of the contract (for example a TTL).
Interface segregation
- Rule. A port has the fewest methods its callers need.
- In this repo.
AuthProviderinlibs/auth/src/provider.tshas one method,verifyToken.RateLimitProviderhas one method,hit, andRateLimiterhas one,check(both inlibs/rate-limit/src/lib/rate-limit-provider.ts).CacheProviderstores strings, andCacheStoreinlibs/cache/src/lib/cache-store.tsadds JSON, tags and stats on top, so a provider author does not implement those. - How to spot a violation. An adapter has to implement methods it does not use, or a test double needs more than a few lines.
Dependency inversion
- Rule. High-level code receives what it needs and depends on a type, not on a concrete adapter.
- In this repo.
createTodoServiceAppinservices/todo-service/src/lib/create-app.tstakesauthProvider,cacheandrateLimiteras parameters.services/todo-service/src/main.tsis where the concrete ones are chosen and passed in. - How to spot a violation. A handler or lib imports a driver (ioredis, Mongoose, a cloud SDK) directly, or builds its own client inside a function that should be given one.
Data and correctness
ACID
- Rule. A change that must be atomic with another change runs in one transaction.
- In this repo. A role change or member removal and its audit row commit or abort together. The repository method in
domains/workspace-domain/src/workspace.repository.tsruns the update throughrunInTransactionand calls anaudithook with the session. The hook type,MemberAuditHookindomains/workspace-domain/src/audit-hook.ts, says the hook must write only through that session. Accepting an invite works the same way indomains/workspace-domain/src/invitation.repository.ts: the user joins the workspace and the invite is marked used in one transaction, and the audit row is part of it. MongoDB transactions need a replica set, which is whyLOCAL_INFRA/docker-compose.ymlstarts a single-node replica set. - How to spot a violation. Two writes that must agree are made one after the other with no session, or an audit write happens outside the transaction it describes.
Idempotency
This is not built. It is a backlog item, listed under "Backend" in docs/backlog.md as idempotency keys and optimistic
concurrency on mutating endpoints. The code has no idempotency keys today, so do not rely on idempotency in new code,
and do not describe an endpoint as safe to retry unless you have checked it.
Fail-fast configuration
- Rule. Read the environment once, at start-up, through a schema, and stop if it is wrong.
- In this repo.
loadConfigFromEnvinlibs/configuration/src/lib/configuration.tsparses the environment with a Zod schema and throws an error that names each bad variable.services/todo-service/src/main.tscallsloadTodoServiceConfig()first, before it connects to anything. - How to spot a violation.
process.envis read inside business logic, or a missing variable becomes a silent default that hides a deploy mistake.
Least privilege
- Rule. Each service and each user gets access to the data it needs and nothing more.
- In this repo. Better Auth's collections hold password hashes, and only
services/iam-servicereads them.pnpm check:iam-boundaryrunsscripts/check-iam-boundary.mjs, which fails when code outside that service names those collections.IAM_SERVICE_AUTH_DATABASE_NAME, read inservices/iam-service/src/lib/config/index.ts, puts them in their own database, so other services can be given a Mongo user with no access to it. When it is unset, everything shares one database, as the IAM service README says. - How to spot a violation. A service reads another service's collections, or a Mongo user can reach more databases than its service uses.
Other principles
DRY
- Rule. A fact is written in one place and everything else is derived from it.
- In this repo.
models/todo-model/src/todo-model.tsdefinestodoSchemaonce and exports its type withz.infer.contracts/todo-contracts/src/todo.contract.tsuses the same schema as procedure output, andservices/todo-service/src/lib/openapi-schemas.tsturns it into an OpenAPI component. Forms are different on purpose: a form is rarely the API payload, so it keeps its own schema and reuses shared limits, for exampleWORKSPACE_NAME_MAX_LENGTHfrommodels/workspace-model/src/workspace-model.ts, used inapps/todo-ui/src/lib/form-schemas.ts. - How to spot a violation. A type, a limit or an error code is written twice, or a hand-written interface mirrors a Zod schema.
YAGNI and KISS
- Rule. Build the least that works, and build it only when it is needed.
- In this repo. The checklist in "Implementation principles" in AGENTS.md runs from "does this need to
exist" to "the minimum that works". The backlog shows the rule at work:
docs/backlog.mdsays BullMQ queues are planned and that BullMQ is not a dependency, so no queue code exists yet. - How to spot a violation. A flag, an option or an abstraction that has one caller, or code added for a feature that is only on the roadmap.
Separation of concerns and layering
- Rule. Dependencies point down the layers, and a layer never imports one above it.
- In this repo. The layers are in architecture.md.
.fallowrc.jsondefines a zone for each layer with the zones it may import, for exampledomainsmay use onlydomains,foundation,modelsandstandalone-libs, andboundary-violationis set toerror.fallow architecture --boundariesexits non-zero on a breach. - How to spot a violation. A model imports a lib, a domain imports a contract, or a lib imports a service. Run the fallow boundary check after any change to imports.
Composition over inheritance
- Rule. Build behavior by combining functions, not by extending classes.
- In this repo. The code is factory functions,
createX(deps) => ({ ...methods }):createTodoServiceApp,createMemoryCacheProviderandcreateRedisCacheProviderare examples. Variation comes from passing a different dependency, as in the Liskov entry above. - How to spot a violation. A new
class, anextends, athis, or a constructor that takes dependencies.
Ports and adapters
- Rule. The core defines a port, and an adapter at the edge implements it.
- In this repo.
connectors/holds the adapters to infrastructure.libs/rate-limitdefines theRateLimitProviderport, andconnectors/mongodb-connector/src/mongo-rate-limit-provider.tsis an adapter that implements it on MongoDB. The lib never imports the connector.createRedisCacheProviderinlibs/cacheis handed a connected client and does not own the connection. - How to spot a violation. A lib creates its own connection, or a connector imports a lib to reach into its internals instead of implementing its port.
Anti-patterns the stack avoids
Each entry says what the stack does instead.
Classes and inheritance trees
- Rule. Use factory functions, not classes.
- In this repo. Services, libs and domains are factories (see Composition over inheritance). There is one deliberate class,
AppErrorinlibs/app-errors/src/app-errors/index.ts, which extendsErrorso it can be thrown and carry a code. No other class exists in the source of libs, services, domains, connectors, contracts or models. This is a convention that review holds, since no lint rule enforces it. - How to spot a violation.
class,extends,thisornewof your own type in a new file. - What to do instead. Write
createX(deps) => ({ ...methods })and pass dependencies as one named-params object.
A shared database written by every service
- Rule. One database is shared, but each domain owns its collections, and only IAM writes Better Auth's.
- In this repo. Every service uses one
MONGO_URIand onegentlemans-stackdatabase, so a domain package owns the collections for its entity and nothing else (seedomains/todo-domain).scripts/check-iam-boundary.mjsfails when another service names Better Auth's collections. - How to spot a violation. Two services write the same collection, or one domain package reads another's schema.
- What to do instead. Ask the owner. Other services learn who the caller is through
createIamSessionAuthProvider, which calls IAM, and a second service that needs an entity imports its domain package instead of its collection name.
Leaking driver errors to clients
- Rule. A client sees a public error code it can act on, and never a database message.
- In this repo.
libs/app-errors/src/error-handler/index.tsturns database, output-validation and unknown failures intoINTERNAL_SERVICE_ERROR, with emptydataand the generic description frommodels/app-error-model/src/app-error-model.ts. It spots a MongoDB driver error by itsMongo*name, and keeps the real cause indiagnosticContextfor the log. - How to spot a violation. A handler catches a driver error and puts its message in the response, or a new public code exists for a failure the client cannot act on.
- What to do instead. Let the error reach the handler in
libs/app-errors, and log the detail.
Hand-copied code instead of generators
- Rule. New packages and apps are generated.
- In this repo.
tools/nx-plugin/generatorshasmodel,contract,domain,connector,deployable-service,deployable-web-app,mobile-appandmobile-app-rename. The Todo packages are the worked example to point a generator at and diff against. - How to spot a violation. A new package whose
package.json, tsconfig and project files match another package line for line, written with no generator run. - What to do instead. Run
pnpm nx g @gentlemans-stack/nx-plugin:<generator> --dry-runfirst.
Importing upward across layers
- Rule. A layer imports only from the layers below it.
- In this repo. The
.fallowrc.jsonzones are listed under Separation of concerns and layering. - How to spot a violation.
fallow architecture --boundariesfails. - What to do instead. Move the shared piece down to the lowest layer that both sides may import, or pass it in as a parameter.
Vendor lock-in in the core
- Rule. The core names no cloud. Cloud-specific code lives in
platforms/<cloud>/<pkg>. - In this repo.
platforms/gcp/auth-firebaseholds the FirebaseAuthProviders and exposes each one through its own subpath export,./adminand./jwks, so a service that does not use Firebase never loads the SDK. Theplatformszone in.fallowrc.jsonlets a platform import foundation libs and models, and the core has no rule that lets it import a platform. The vendor-neutralcreateJwtAuthProviderships inlibs/authinstead. - How to spot a violation. A
models/,libs/,connectors/,contracts/ordomains/file names GCP, Firebase or AWS. - What to do instead. Define a port in the core and write the adapter under
platforms/.
Magic strings for errors
- Rule. Error codes come from one typed list.
- In this repo.
models/app-error-model/src/app-error-model.tsdefines each public code with its status and metadata.AppErrortakes the code as a typed argument, as innew AppError("RESOURCE_NOT_FOUND", { resource: "todo" })inservices/todo-service/src/lib/create-app.ts, so an unknown code does not compile. - How to spot a violation. A string literal such as
"not_found"thrown or compared, or an error status written as a bare number in a handler. - What to do instead. Add the code to
models/app-error-modeland throwAppErrorwith it.
console.log
- Rule. Log through evlog, with a request-scoped logger.
- In this repo. The request logger travels in the oRPC context as
context.logger, aslibs/server-setup/src/lib/orpc-server.tsshows, and start-up code uses thelogexport of evlog astopLogger, for example inservices/todo-service/src/main.ts. Biome'snoConsolerule is off in the ultracite preset, so nothing fails the build if you writeconsole.log. The source of libs, services, domains, connectors, contracts and models has no console calls outside tests. Build-time scripts underscripts/do useconsole.log. - How to spot a violation. A
console.call inlibs/,services/,domains/orconnectors/. - What to do instead. Use the request logger from context, or
topLoggerat start-up.
Barrel abuse
- Rule. Use a barrel for a package's public entry point, and subpath exports for distinct concerns.
- In this repo.
libs/cache/package.jsonexports./*fromsrc/lib, so code imports@gentlemans-stack/cache/cache-storeand@gentlemans-stack/cache/cache.middlewareand loads only what it uses.libs/contract-kit/package.jsonexports./errorsfor the error helpers. Barrels are allowed (noBarrelFileis off inbiome.shared.jsonc), for example theindex.tsofmodels/todo-model. - How to spot a violation. A barrel that re-exports a whole package so that importing one function loads a vendor SDK it does not need.
- What to do instead. Add a subpath export for the separate concern, as
platforms/gcp/auth-firebasedoes.