Domain-Driven Design: Layered Architecture for organizing code and separating responsibilities
Learn to distribute responsibilities across Presentation, Application, Domain, and Infrastructure. Follow a complete endpoint with TypeScript and Express, distinguish calls from dependencies, and use clear rules to review your code and AI-generated code.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
A store has an endpoint for confirming orders. The controller validates JSON, queries the database, checks for items, changes the status, and returns a response. Everything works until another integration needs to confirm orders without going through HTTP.
The team copies the checks. Later a rule changes and only one of the two flows is updated. Now an empty order is rejected from the panel but confirmed from the integration.
The problem is not the controller's line count. It is that rules, coordination, and technical details are mixed. Layered Architecture distributes those responsibilities and establishes how they collaborate, so a new entry point does not need to reconstruct business behavior.
What Layered Architecture organizes
A layer groups related responsibilities and defines the services it offers other parts of the system. DDD traditionally distinguishes Presentation, also called User Interface, Application, Domain, and Infrastructure. The central purpose is to isolate the model and its rules from interface and technical support details. Evans develops this separation in the Layered Architecture section of his DDD reference.
These are code separations, not necessarily separate processes or servers. You can keep all four layers in one Node.js application and deploy it as a unit. Nor are they stages every datum must necessarily pass through: reading a list may require a different flow from executing an operation with rules.
Presentation: adapt the interaction
Presentation receives inputs and presents results. In an HTTP backend, it includes routes and controllers: it interprets parameters, validates request shape, and selects the HTTP response. It does not decide whether an order can be confirmed.
Application: coordinate an operation
Application implements Use Cases, the operations the system offers. It retrieves information, invokes Domain behavior, and coordinates saving. It can establish a local transaction boundary when the operation requires one. It does not need to know Request, Response, or SQL statements.
Domain: decide according to rules
Domain expresses business concepts and behavior. In our example it decides whether an order can be confirmed. That rule must still apply whether the operation comes from HTTP, a scheduled task, or a test.
Infrastructure: implement technical mechanisms
Infrastructure implements storage and external service access. It knows how to execute a query or HTTP request; it must not become the only place deciding whether the business permits an action.
The exact location of some contracts may vary. What matters is being able to explain which decision belongs to each responsibility and what dependencies your choice introduces.
A call is not the same as a dependency
When executing a Use Case, Application needs to retrieve data. That does not require directly importing a database client.
In this article we choose a Repository contract defined in Domain and an implementation in Infrastructure. A Repository offers model retrieval and saving; we will not explore that pattern in depth here. Application knows the contract and receives an implementation from outside.
The execution flow will be:
HTTP request
-> Presentation: validate and adapt
-> Application: coordinate ConfirmOrder
-> Infrastructure: load through the Repository contract
-> Domain: execute Order.confirm()
-> Infrastructure: save through the same contract
<- Presentation: translate the result to HTTP
An arrow in the second diagram means “imports or knows types defined in.” Infrastructure implements a Domain contract; Application can invoke that implementation during execution without importing its concrete class. This is known as Dependency Inversion.
This is the variant chosen to isolate Domain in the example. Layered Architecture does not by itself determine a single import graph. Some organizations use more direct downward dependencies; others invert technical dependencies. That is why “we have four folders” does not yet describe architectural rules.
Before: every decision in a route
This partial snippet uses a fictional database object. It illustrates the problem; it is not an executable server:
The rule exists only inside that route. Testing it requires going through Express or artificially extracting it. Changing storage also affects the controller.
The transformation will be gradual: extract the rule, create a Use Case, introduce the persistence contract, and leave only HTTP adaptation in the route. Each step must preserve or check expected behavior.
The chosen rules are simple: an empty or canceled order cannot be confirmed. Confirming an already confirmed order again returns its state without creating another effect. We will not model payments, stock, or notifications.
Validation is divided by purpose. Presentation requires an empty object; Domain checks order conditions; Application distinguishes a nonexistent identifier from a rejected operation. Correct JSON format does not imply a valid business action.
The following teaching project includes all its files. It uses Node.js 24.21.0 and Express 4.x. In-memory storage represents Infrastructure, but does not retain data after restarting or coordinate across processes. It includes no authentication: it listens only on the local interface and must not be exposed as a real service without access controls.
Node.js directly executes the following TypeScript syntax using type stripping, which removes type annotations. This does not perform static type checking. To check types with tsc, you would need to configure TypeScript and its corresponding declarations; this tutorial is limited to execution and behavior tests.
1. Domain protects the rule
File domain/order.ts:
exporttypeOrderSnapshot = {
id: string;
itemCount: number;
status: 'draft' | 'confirmed' | 'cancelled';
};
exportclassOrderRuleErrorextendsError {}
exportclassOrder {
#state: OrderSnapshot;
constructor(state: OrderSnapshot) {
if (!Number.isSafeInteger(state.itemCount) || state.itemCount < 0) {
thrownewOrderRuleError('Cantidad de artículos inválida');
}
if (state.status === 'confirmed' && state.itemCount === 0) {
thrownewOrderRuleError('Un pedido confirmado no puede estar vacío');
}
this.#state = { ...state };
}
confirm(): void {
if (this.#state.status === 'cancelled') {
thrownewOrderRuleError('Un pedido cancelado no puede confirmarse');
}
if (this.#state.itemCount === 0) {
thrownewOrderRuleError('Un pedido vacío no puede confirmarse');
}
this.#state.status = 'confirmed';
}
snapshot(): OrderSnapshot {
return { ...this.#state };
}
}
The constructor receives trusted data from our demonstration. If it came from external storage, the adapter would also need to validate its structure and allowed values before reconstructing the model. Types do not validate data at runtime.
Application transforms a known rejection into an explicit result. It does not respond 409: that code belongs to HTTP. An unexpected persistence failure propagates; it is not presented as though the order violated a rule.
Saving copies prevents modifying a retrieved object from changing storage before calling save. Replacing this implementation with SQL should not require rewriting Order.confirm().
That does not mean any replacement is automatic: the actual implementation must uphold the contract, handle failures, and protect against write conflicts. This in-memory Repository does not demonstrate those guarantees.
The route validates input shape, but does not count items again. HTTP mapping is defined in one place. We use try/catch and next(error) because in Express 4 asynchronous rejections must be explicitly propagated to the error handler; the Express documentation distinguishes this behavior from Express 5.
This assembly point is called the Composition Root: it knows concrete implementations and connects them. Passing them through the constructor is Dependency Injection; it requires no framework.
Run the server:
node server.ts
You can send the request from another terminal. On Windows use curl.exe if curl is a PowerShell alias:
With order-empty you get 409; with a nonexistent identifier, 404. Repeating confirmation of order-1 keeps confirmed. This repetition creates no further effect in the example; if you add charges or notifications, explicitly design how to avoid duplicate effects.
The first checks a rule without Express or storage. The second checks coordination and saving without HTTP. The third traverses the endpoint with the in-memory adapter. All three tests were run and passed with Node.js 24.21.0 and Express 4.22.3. No static TypeScript checking or test against a real database was performed: when introducing one, you will also need to check its integration.
Separation does not reduce errors by itself. It lets you locate decisions and check them with dependencies proportionate to each test.
Other scenarios: what changes and what is reused
Education: the same Use Case from a scheduled task
An academy enables certificates from an endpoint and from a nightly task. Presentation adapts the web request; the task is another entry point. Both can invoke the same Use Case, which obtains evidence and asks Domain to decide whether issuance is appropriate.
The lesson here is separating entry point from operation. The task must not fabricate a Request object to reuse the route. Nor should it copy the passing rule. The Use Case receives the data it needs, not framework objects.
Logistics: replace an integration without copying its model
A provider represents deliveries using external codes. Infrastructure implements an Anticorruption Layer, or ACL, that validates its HTTP response and translates it to the contract the consumer needs. Application coordinates the query; Domain evaluates what that evidence means for its own process.
If the provider does not respond, do not turn the failure into “delivery pending” as though it were a confirmed fact. The contract must distinguish absence of evidence from technical unavailability.
This case teaches separating translation from business interpretation. If there are several Bounded Contexts, boundaries where each model maintains consistent meaning, each retains its implementations: the example integrates through an HTTP ACL with consumer contracts, without cross-context imports. HTTP does not share the Repository's local transaction.
How to refactor without moving the mixture into other folders
Start with scenarios describing current behavior and agreed rules. Extract a specific rule into Domain and have the route invoke it. Then introduce Application to coordinate loading, operation, and saving. Finally separate storage details and connect implementations in the Composition Root.
Moving an entire controller to application/service.ts preserves the mixture if it still uses req, res, and SQL. Likewise, a Domain importing Express to throw HTTP errors retains a transport dependency even in another folder.
Define import rules you can review. In the example, Domain imports no other layers; Application imports neither Express nor Infrastructure implementations. You can start by checking this in review and automate when project size justifies it.
Layered, Hexagonal, Onion, and Clean Architecture
They share separation objectives, but emphasize different criteria:
Layered Architecture organizes responsibilities into layers and defines how they collaborate. Specific isolation also depends on dependency rules.
Hexagonal Architecture, described by Alistair Cockburn, distinguishes the application's interior from external interactions through ports and adapters: interaction contracts and implementations connecting concrete technologies.
Onion Architecture, presented by Jeffrey Palermo, places the model at the center and directs dependencies inward, leaving technical details outside.
Clean Architecture, explained by Robert C. Martin, separates policies and details through boundaries and a dependency rule pointing toward internal policies.
Our Repository contract and external assembly are compatible with several of these ideas. They do not automatically make the project a complete implementation of all of them. To discuss the design, showing responsibilities and allowed imports is more useful than choosing a label.
When to keep it simpler
An internal catalog with two fields and CRUD operations—create, read, update, and delete—can be handled with a small route, validation, and clearly separated data access. Creating a class that merely forwards every call to another adds little if there is no distinct responsibility.
Layered Architecture entails files, contracts, and assembly decisions. That cost is justified when you need to protect rules, reuse operations, or isolate technologies. It does not require a behavioral model for every read or a generic Repository for every table.
Prompts to guide and review AI work
Analyze mixed responsibilities
Analyze this confirmation controller. Classify HTTP validation, coordination, order rules, and persistence. Do not change files. Return evidence and a minimal extraction proposal preserving current responses. Do not add frameworks or business rules. A person will confirm the rules and review which scenarios must be protected before refactoring.
Implement limited separation
Refactor the operation with Presentation, Application, Domain, and Infrastructure. Domain imports neither Express nor infrastructure; Application depends on the Repository contract; the concrete implementation is connected outside. Maintain the agreed response format. Do not add authentication, queues, or new dependencies to the scope. Provide the change and tests for empty orders, canceled orders, and repeated confirmation. A person will run the tests and review preservation of the HTTP contract.
Review boundaries and guarantees
Review the diff against these import and responsibility rules. Look for duplicated logic in Presentation, HTTP in Domain, technical implementations imported from Application, and assumptions of shared transactions over HTTP. Do not edit files. Report each finding with evidence and an observable effect; separate questions from violations. A person will verify storage guarantees and concurrent scenarios not covered by the in-memory example.
A good prompt can make boundaries explicit. Human review must check that those boundaries exist in code and that behavior remains as agreed; a convincing folder structure proves neither.
Three exercises with reasoned solutions
1. Change the HTTP error
The product wants to respond 422 instead of 409 when confirmation is not allowed. Must Order.confirm() change?
Reasoned solution: in the example's design, Presentation changes, where rejected is translated. Domain retains the rule and Application its result. HTTP tests are updated for the new contract; rule tests should still pass. Changing a public response requires agreeing on its impact with consumers.
2. Reuse confirmation from an import
An administrative import proposes calling the controller by simulating req and res. What alternative would you use?
Reasoned solution: have the import entry point validate its own format and invoke ConfirmOrder.execute. It reuses coordination and rules without depending on HTTP transport. If it needs its own permissions or limits, define them explicitly; reusing the Use Case is not equivalent to authorizing every call.
3. Two people edit the same order
One confirms and the other cancels based on the same read state. The team claims the layers prevent the conflict. Is that enough?
Reasoned solution: no. Separation does not coordinate writes. Define the allowed outcome and apply concurrency control in persistence, for example through a version and conditional write within a local transaction. The Use Case must handle the conflict; the test needs to reproduce it against the corresponding storage.
How to recognize useful separation
Check whether you can explain who receives input, who coordinates, who decides, and who implements technical access. Then verify whether a rule can be tested without a server and another entry point can execute the Use Case without copying behavior.
When those answers match imports and tests, the layers provide real separation. If only folder names change, return to a concrete operation and review its responsibilities: that is where maintainable, verifiable code organization begins.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.