Skip to content
← All insights
Engineering · 6 min readProject · FutureSkills

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.

Bartolomeus Delphito

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.

Top level: the folder list reads like the product
  • 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

Rich domain model
Why customers choose you: enrollment, scoring, certification. Explicit invariants and thorough tests.

Supporting

Service + repository
Needed but not differentiating: programs, surveys, discussions. Light rules.

Generic

Plain CRUD or a library
Solved problems: auth, file storage, notifications, blog. No DDD ceremony.

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.

One request through a module
  1. RouteValidate input, respond
  2. MiddlewareAuth, tenant scope, errors
  3. ServiceOrchestrate the use-case
  4. DomainPure rules, no I/O
  5. RepositoryThe only Prisma user
Inside a core module: each folder has one job
  • 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.

Completing a course, without learning importing certification
  1. Learning → Event bus: emit EnrollmentCompleted
  2. Event bus → Certification: onEnrollmentCompleted
  3. Certification → Certification: check eligibility
  4. Certification → Event bus: emit CertificateIssued
  5. 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.

Inside a module: which way imports may pointAllowed importForbidden import
  • 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)
Between modules: use the front door or eventsAllowed importForbidden import
  • Learning → Certification: Allowed import (B1)
  • Learning → Certification: Forbidden import (B2)
  • Learning → Event bus: Allowed import (B5)
RuleWhat the check forbids
Prisma only in repositoriesImporting @prisma/client anywhere else
No deep importsReaching into another module’s internals
Routes stay thinRoutes importing domain or infrastructure code
Frontend never imports backendAny import from the frontend into backend code
No cyclesTwo modules that depend on each other
Boundary rules worth checking in CI

Interactive

Is this import allowed?

// app/api/certificates/post.ts
import … from 'modules/certification (index.ts)'
AllowedRule A1

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.

PatternWhy not (for now)
MicroservicesAdds latency, partial failure and ops cost for a few developers and one database.
CQRS / event sourcingOrdinary tables already meet audit needs.
Interface for everythingOne implementation needs no interface; add ports only at real I/O boundaries.
Framework rewritePlain modules with enforced rules give the same boundaries.
Patterns skipped by default, and why

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.

A migration where every step ships on its own
  1. Lint warningsMeasure violations
  2. Fix leaksMove Prisma out of services and routes
  3. Group modulesAdd a public index.ts
  4. Extract rulesPure domain rules for core areas
  5. Use eventsDecouple side effects
  6. Lock inFlip warnings to errors