A backend that stays changeable: domain-driven design for small teams
How a small team can organize a TypeScript backend by business capability, keep each rule in one place, and let tooling enforce the boundaries.
Structure is a convention until it becomes a constraint
A backend rarely becomes hard to change on purpose. It grows folder by folder: a service imports Prisma directly because it is faster, the same membership query gets written twice with small differences, and any module can reach into the internals of any other.
None of this is unusual. It is the default outcome when structure is only a convention. A small team, especially one working alongside AI coding agents, needs structure that is checked, not remembered.
Organize by what the business does
Top-level folders should say what the product does, such as learning, certification or identity, rather than what the code is, such as services, controllers or models. Someone new should understand the product from the folder list.
Draw module boundaries where the language changes. In one context a course is something you author and publish; in another it is something a learner progresses through; in a third it is only the reason a certificate was issued. Each context models only the slice it needs. A single god-object that every module reads and writes guarantees coupling.
- src/
- app/api/Thin HTTP layer: routes only
- be/
- modules/Bounded contexts, the business
- identity/users, roles, orgs, auth
- catalog/courses, modules, programs
- learning/enrollment, progress
- certification/eligibility, issuing
- reporting/read-only, may join across tables
- platform/Technical adapters, no business rules
- shared/Middleware, errors, http helpers
Spend design effort where the business is
Not every part of a system deserves the same care. Core subdomains, the reason customers choose you, justify a rich model with explicit invariants and thorough tests. Supporting subdomains need a service and a repository with light rules. Generic ones, such as authentication, file storage or a blog, should be plain CRUD or a vendor library.
Applying full domain-driven design everywhere is the most common way small teams fail at it. Structure should follow importance.
Core
Supporting
Generic
Give every rule exactly one home
Take the sentence “a certificate is issued only once, only after completion, and only if the final score meets the threshold.” It should map to one function. If the rule can be bypassed by querying the database from somewhere else, it is not a rule; it is a suggestion.
Keep that function pure: plain types in, plain result out, no I/O. It runs in milliseconds, needs no mocks, and is the single place the rule lives.
type Eligibility =
| { eligible: true }
| { eligible: false; reason: 'NOT_COMPLETED' | 'SCORE_TOO_LOW' | 'ALREADY_ISSUED' };
export function checkEligibility(i: {
completedAt: Date | null;
finalScore: number;
passingScore: number;
alreadyIssued: boolean;
}): Eligibility {
if (i.alreadyIssued) return { eligible: false, reason: 'ALREADY_ISSUED' };
if (!i.completedAt) return { eligible: false, reason: 'NOT_COMPLETED' };
if (i.finalScore < i.passingScore) return { eligible: false, reason: 'SCORE_TOO_LOW' };
return { eligible: true };
}Keep a clear request flow
Routes stay thin: they validate input, run authorization middleware, call a service and respond. Services orchestrate: they load data, call domain rules, persist results and trigger side effects. Only repositories touch the database, and they return domain-shaped data rather than raw ORM payloads.
Tenant scoping belongs at the repository. Every organization-owned query filters by an organization taken from validated server context, never from a client-supplied value.
- RouteValidate input, respond
- MiddlewareAuth, tenant scope, errors
- ServiceOrchestrate the use-case
- DomainPure rules, no I/O
- RepositoryThe only Prisma user
- certification/
- index.tsThe front door: the only allowed import path
- README.mdGlossary, owned tables, events
- domain/Pure TypeScript: no await, no I/O
- eligibility.tscheckEligibility(): the one home of the rule
- errors.tsCertificateAlreadyIssued, NotEligible
- application/Use-cases that orchestrate
- issue-certificate.ts
- on-enrollment-completed.tsEvent listener
- infrastructure/
- certificate.repository.tsThe only place Prisma is imported
- contracts/Zod schemas and event payloads
- __tests__/Pure rule tests need no mocks
Modules talk through a front door
Each module exposes one public interface, its index.ts file, that exports use-cases, contract types and events, and never repositories or internals. Other modules call those exported functions directly; it is an ordinary in-process function call, not an HTTP request. Each table has one owning module, and other modules ask the owner rather than reading its tables.
For side effects across modules, prefer domain events. When a learner completes a course, the learning module emits an event; certification and notifications react to it. Adding a new reaction means adding a listener, not editing the learning module. Keep transactions inside one module and accept eventual consistency between them.
- Learning → Event bus: emit EnrollmentCompleted
- Event bus → Certification: onEnrollmentCompleted
- Certification → Certification: check eligibility
- Certification → Event bus: emit CertificateIssued
- Event bus → Notifications: “certificate ready”
Let tools enforce it
Larger organizations often enforce boundaries with separate build modules. A small team can get most of the same guarantee more cheaply with dependency rules in CI: Prisma only in repositories, no deep imports into another module, routes calling only a module’s public interface, no frontend imports from the backend, and no cycles.
Introduce the rules as warnings first so violations become visible and countable. Fix them module by module, then switch each rule to an error so the structure cannot regress.
- Route → Service: Allowed import (A1)
- Service → Domain: Allowed import (A2)
- Service → Repository: Allowed import (A2)
- Repository → Prisma: Allowed import (A3)
- Route → Repository: Forbidden import (A1)
- Service → Prisma: Forbidden import (A3)
- Domain → Prisma: Forbidden import (A4)
- Learning → Certification: Allowed import (B1)
- Learning → Certification: Forbidden import (B2)
- Learning → Event bus: Allowed import (B5)
| Rule | What the check forbids |
|---|---|
| Prisma only in repositories | Importing @prisma/client anywhere else |
| No deep imports | Reaching into another module’s internals |
| Routes stay thin | Routes importing domain or infrastructure code |
| Frontend never imports backend | Any import from the frontend into backend code |
| No cycles | Two modules that depend on each other |
Interactive
Is this import allowed?
// app/api/certificates/post.ts import … from 'modules/certification (index.ts)'
Routes validate input and call a service through the module front door. That is all a route should do.
What to deliberately skip
Microservices add network latency, partial failure and operational cost, and solve nothing for a handful of developers with one database. CQRS and event sourcing are unnecessary when ordinary tables meet your audit needs. An interface for every class with a single implementation is noise; add ports only at real I/O boundaries such as storage, email or an AI provider.
A framework rewrite is also rarely the answer. Plain modules with enforced rules give the same boundaries without it.
| Pattern | Why not (for now) |
|---|---|
| Microservices | Adds latency, partial failure and ops cost for a few developers and one database. |
| CQRS / event sourcing | Ordinary tables already meet audit needs. |
| Interface for everything | One implementation needs no interface; add ports only at real I/O boundaries. |
| Framework rewrite | Plain modules with enforced rules give the same boundaries. |
Migrate in small steps
None of this requires a big-bang rewrite. Add lint rules as warnings, move database access out of services and routes, group folders into modules with a public interface, extract pure rules for the core subdomains, replace cross-module calls with events, move slow work to background jobs, then lock the rules in. Each step is a small pull request, and feature work continues in parallel.
The short version: modules own their data and rules, talk only through their front door or through events, and only repositories touch the database. A linter enforces all of it.
- Lint warningsMeasure violations
- Fix leaksMove Prisma out of services and routes
- Group modulesAdd a public index.ts
- Extract rulesPure domain rules for core areas
- Use eventsDecouple side effects
- Lock inFlip warnings to errors