Skip to Content
gentlemans-stack

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.md holds the rules an agent must follow, and CLAUDE.md imports it.
  • .claude/skills holds one skill per recurring task, for example api-endpoints, form-builder and domain-repository-tests.
  • Generators in tools/nx-plugin/generators create 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. fallow checks 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/lib splits the work into rate-limit-provider.ts (the storage port), rate-limiter.ts (the limit logic) and rate-limit.middleware.ts (the oRPC glue). A domains/* package is a Mongoose schema and a repository, and the fallow domains zone in .fallowrc.json only 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.ts each 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.ts and redis-cache-provider.ts both return a CacheProvider and both validate TTLs with the same assertValidCacheTtl. For rate limits, libs/rate-limit/src/lib/memory-rate-limit-provider.ts, redis-rate-limit-provider.ts and connectors/mongodb-connector/src/mongo-rate-limit-provider.ts all return a RateLimitProvider. The service in create-app.ts never learns which one is behind its rateLimiter.
  • 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. AuthProvider in libs/auth/src/provider.ts has one method, verifyToken. RateLimitProvider has one method, hit, and RateLimiter has one, check (both in libs/rate-limit/src/lib/rate-limit-provider.ts). CacheProvider stores strings, and CacheStore in libs/cache/src/lib/cache-store.ts adds 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. createTodoServiceApp in services/todo-service/src/lib/create-app.ts takes authProvider, cache and rateLimiter as parameters. services/todo-service/src/main.ts is 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.ts runs the update through runInTransaction and calls an audit hook with the session. The hook type, MemberAuditHook in domains/workspace-domain/src/audit-hook.ts, says the hook must write only through that session. Accepting an invite works the same way in domains/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 why LOCAL_INFRA/docker-compose.yml starts 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. loadConfigFromEnv in libs/configuration/src/lib/configuration.ts parses the environment with a Zod schema and throws an error that names each bad variable. services/todo-service/src/main.ts calls loadTodoServiceConfig() first, before it connects to anything.
  • How to spot a violation. process.env is 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-service reads them. pnpm check:iam-boundary runs scripts/check-iam-boundary.mjs, which fails when code outside that service names those collections. IAM_SERVICE_AUTH_DATABASE_NAME, read in services/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.ts defines todoSchema once and exports its type with z.infer. contracts/todo-contracts/src/todo.contract.ts uses the same schema as procedure output, and services/todo-service/src/lib/openapi-schemas.ts turns 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 example WORKSPACE_NAME_MAX_LENGTH from models/workspace-model/src/workspace-model.ts, used in apps/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.md says 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.json defines a zone for each layer with the zones it may import, for example domains may use only domains, foundation, models and standalone-libs, and boundary-violation is set to error. fallow architecture --boundaries exits 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, createMemoryCacheProvider and createRedisCacheProvider are examples. Variation comes from passing a different dependency, as in the Liskov entry above.
  • How to spot a violation. A new class, an extends, a this, 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-limit defines the RateLimitProvider port, and connectors/mongodb-connector/src/mongo-rate-limit-provider.ts is an adapter that implements it on MongoDB. The lib never imports the connector. createRedisCacheProvider in libs/cache is 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, AppError in libs/app-errors/src/app-errors/index.ts, which extends Error so 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, this or new of 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_URI and one gentlemans-stack database, so a domain package owns the collections for its entity and nothing else (see domains/todo-domain). scripts/check-iam-boundary.mjs fails 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.ts turns database, output-validation and unknown failures into INTERNAL_SERVICE_ERROR, with empty data and the generic description from models/app-error-model/src/app-error-model.ts. It spots a MongoDB driver error by its Mongo* name, and keeps the real cause in diagnosticContext for 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/generators has model, contract, domain, connector, deployable-service, deployable-web-app, mobile-app and mobile-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-run first.

Importing upward across layers

  • Rule. A layer imports only from the layers below it.
  • In this repo. The .fallowrc.json zones are listed under Separation of concerns and layering.
  • How to spot a violation. fallow architecture --boundaries fails.
  • 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-firebase holds the Firebase AuthProviders and exposes each one through its own subpath export, ./admin and ./jwks, so a service that does not use Firebase never loads the SDK. The platforms zone in .fallowrc.json lets a platform import foundation libs and models, and the core has no rule that lets it import a platform. The vendor-neutral createJwtAuthProvider ships in libs/auth instead.
  • How to spot a violation. A models/, libs/, connectors/, contracts/ or domains/ 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.ts defines each public code with its status and metadata. AppError takes the code as a typed argument, as in new AppError("RESOURCE_NOT_FOUND", { resource: "todo" }) in services/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-model and throw AppError with 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, as libs/server-setup/src/lib/orpc-server.ts shows, and start-up code uses the log export of evlog as topLogger, for example in services/todo-service/src/main.ts. Biome's noConsole rule is off in the ultracite preset, so nothing fails the build if you write console.log. The source of libs, services, domains, connectors, contracts and models has no console calls outside tests. Build-time scripts under scripts/ do use console.log.
  • How to spot a violation. A console. call in libs/, services/, domains/ or connectors/.
  • What to do instead. Use the request logger from context, or topLogger at 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.json exports ./* from src/lib, so code imports @gentlemans-stack/cache/cache-store and @gentlemans-stack/cache/cache.middleware and loads only what it uses. libs/contract-kit/package.json exports ./errors for the error helpers. Barrels are allowed (noBarrelFile is off in biome.shared.jsonc), for example the index.ts of models/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-firebase does.

On this page