Software Architecture

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.

Updated on October 29, 2026

Content explored 0%
18px

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

Code dependencies will differ:

Presentation   -> Application
Application    -> Domain
Infrastructure -> Domain

server.ts connects concrete implementations.
Domain imports neither Express, Application, nor Infrastructure.

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:

app.patch('/orders/:orderId/confirmation', async (req, res) => {
  const row = await database.findOrder(req.params.orderId);
  if (!row) return res.status(404).json({ error: 'Pedido inexistente' });
  if (row.itemCount === 0 || row.status === 'cancelled') {
    return res.status(409).json({ error: 'No se puede confirmar' });
  }
  await database.updateOrder(row.id, { status: 'confirmed' });
  return res.json({ id: row.id, status: 'confirmed' });
});

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.

Complete example: confirm an order

Contract and demonstration boundaries

Our operation accepts this request:

PATCH /orders/order-1/confirmation
Content-Type: application/json

{}

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.

Structure and setup

layered-example/
  package.json
  domain/
    order.ts
    order-repository.ts
  application/
    confirm-order.ts
  infrastructure/
    memory-order-repository.ts
  presentation/
    app.ts
  server.ts
  example.test.ts

Create package.json with this content:

{
  "name": "layered-example",
  "private": true,
  "type": "module"
}

From that folder, install Express following its official installation procedure, selecting the major version used here:

npm install express@4

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:

export type OrderSnapshot = {
  id: string;
  itemCount: number;
  status: 'draft' | 'confirmed' | 'cancelled';
};

export class OrderRuleError extends Error {}

export class Order {
  #state: OrderSnapshot;

  constructor(state: OrderSnapshot) {
    if (!Number.isSafeInteger(state.itemCount) || state.itemCount < 0) {
      throw new OrderRuleError('Cantidad de artículos inválida');
    }
    if (state.status === 'confirmed' && state.itemCount === 0) {
      throw new OrderRuleError('Un pedido confirmado no puede estar vacío');
    }
    this.#state = { ...state };
  }

  confirm(): void {
    if (this.#state.status === 'cancelled') {
      throw new OrderRuleError('Un pedido cancelado no puede confirmarse');
    }
    if (this.#state.itemCount === 0) {
      throw new OrderRuleError('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.

File domain/order-repository.ts:

import type { Order } from './order.ts';

export interface OrderRepository {
  find(id: string): Promise<Order | null>;
  save(order: Order): Promise<void>;
}

The contract mentions neither tables, connections, nor HTTP. It also does not turn every storage failure into a business rejection.

2. Application coordinates without knowing Express

File application/confirm-order.ts:

import { OrderRuleError, type OrderSnapshot } from '../domain/order.ts';
import type { OrderRepository } from '../domain/order-repository.ts';

export type ConfirmationResult =
  | { kind: 'not_found' }
  | { kind: 'rejected'; reason: string }
  | { kind: 'confirmed'; order: OrderSnapshot };

export class ConfirmOrder {
  #orders: OrderRepository;

  constructor(orders: OrderRepository) {
    this.#orders = orders;
  }

  async execute(orderId: string): Promise<ConfirmationResult> {
    const order = await this.#orders.find(orderId);
    if (!order) return { kind: 'not_found' };

    try {
      order.confirm();
    } catch (error) {
      if (error instanceof OrderRuleError) {
        return { kind: 'rejected', reason: error.message };
      }
      throw error;
    }

    await this.#orders.save(order);
    return { kind: 'confirmed', order: order.snapshot() };
  }
}

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.

3. Infrastructure implements storage

File infrastructure/memory-order-repository.ts:

import { Order, type OrderSnapshot } from '../domain/order.ts';
import type { OrderRepository } from '../domain/order-repository.ts';

export class MemoryOrderRepository implements OrderRepository {
  #rows = new Map<string, OrderSnapshot>();

  constructor(initial: OrderSnapshot[]) {
    for (const state of initial) {
      const validated = new Order(state).snapshot();
      this.#rows.set(validated.id, validated);
    }
  }

  async find(id: string): Promise<Order | null> {
    const state = this.#rows.get(id);
    return state ? new Order(state) : null;
  }

  async save(order: Order): Promise<void> {
    const state = order.snapshot();
    this.#rows.set(state.id, state);
  }
}

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.

4. Presentation validates and translates to HTTP

File presentation/app.ts:

import express from 'express';
import type { ErrorRequestHandler } from 'express';
import type { ConfirmOrder } from '../application/confirm-order.ts';

export function createApp(confirmOrder: ConfirmOrder) {
  const app = express();
  app.use(express.json({ limit: '1kb' }));

  app.patch('/orders/:orderId/confirmation', async (req, res, next) => {
    try {
      const body: unknown = req.body;
      if (
        typeof body !== 'object' || body === null || Array.isArray(body) ||
        Object.keys(body).length !== 0
      ) {
        res.status(400).json({ error: 'Se esperaba un objeto vacío' });
        return;
      }

      const result = await confirmOrder.execute(req.params.orderId);
      if (result.kind === 'not_found') {
        res.status(404).json({ error: 'Pedido inexistente' });
      } else if (result.kind === 'rejected') {
        res.status(409).json({ error: result.reason });
      } else {
        res.status(200).json({ id: result.order.id, status: result.order.status });
      }
    } catch (error) {
      next(error);
    }
  });

  const handleError: ErrorRequestHandler = (error, _req, res, _next) => {
    if (error.type === 'entity.parse.failed') {
      res.status(400).json({ error: 'JSON inválido' });
    } else if (error.type === 'entity.too.large') {
      res.status(413).json({ error: 'Petición demasiado grande' });
    } else {
      res.status(500).json({ error: 'Error interno' });
    }
  };
  app.use(handleError);
  return app;
}

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.

5. Connect the pieces and observe the response

File server.ts:

import { ConfirmOrder } from './application/confirm-order.ts';
import { MemoryOrderRepository } from './infrastructure/memory-order-repository.ts';
import { createApp } from './presentation/app.ts';

const orders = new MemoryOrderRepository([
  { id: 'order-1', itemCount: 2, status: 'draft' },
  { id: 'order-empty', itemCount: 0, status: 'draft' },
]);

const confirmOrder = new ConfirmOrder(orders);
const app = createApp(confirmOrder);
app.listen(3000, '127.0.0.1', () => {
  console.log('Servidor disponible en http://127.0.0.1:3000');
});

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:

curl --request PATCH http://127.0.0.1:3000/orders/order-1/confirmation --header "Content-Type: application/json" --data "{}"

The response is 200 with this body:

{"id":"order-1","status":"confirmed"}

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.

Tests showing why separation is useful

File example.test.ts:

import assert from 'node:assert/strict';
import { once } from 'node:events';
import test from 'node:test';
import { Order } from './domain/order.ts';
import { ConfirmOrder } from './application/confirm-order.ts';
import { MemoryOrderRepository } from './infrastructure/memory-order-repository.ts';
import { createApp } from './presentation/app.ts';

test('Domain rechaza un pedido vacío sin cambiar su estado', () => {
  const order = new Order({ id: 'empty', itemCount: 0, status: 'draft' });
  assert.throws(() => order.confirm(), /vacío/);
  assert.equal(order.snapshot().status, 'draft');
});

test('Application confirma y guarda sin servidor HTTP', async () => {
  const orders = new MemoryOrderRepository([
    { id: 'ready', itemCount: 1, status: 'draft' },
    { id: 'cancelled', itemCount: 1, status: 'cancelled' },
  ]);
  const useCase = new ConfirmOrder(orders);
  assert.equal((await useCase.execute('ready')).kind, 'confirmed');
  assert.equal((await orders.find('ready'))?.snapshot().status, 'confirmed');
  assert.equal((await useCase.execute('ready')).kind, 'confirmed');
  assert.equal((await useCase.execute('missing')).kind, 'not_found');
  assert.equal((await useCase.execute('cancelled')).kind, 'rejected');
});

test('Presentation valida la entrada y traduce resultados a HTTP', async () => {
  const orders = new MemoryOrderRepository([
    { id: 'ready', itemCount: 1, status: 'draft' },
    { id: 'empty', itemCount: 0, status: 'draft' },
  ]);
  const server = createApp(new ConfirmOrder(orders)).listen(0, '127.0.0.1');
  try {
    await once(server, 'listening');
    const address = server.address();
    if (!address || typeof address === 'string') throw new Error('Puerto no disponible');
    const base = `http://127.0.0.1:${address.port}/orders`;
    const send = (id: string, body: string) => fetch(`${base}/${id}/confirmation`, {
      method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body,
    });

    assert.equal((await send('ready', '{')).status, 400);
    assert.equal((await send('ready', '{"status":"confirmed"}')).status, 400);
    assert.equal((await send('missing', '{}')).status, 404);
    assert.equal((await send('empty', '{}')).status, 409);
    const response = await send('ready', '{}');
    assert.equal(response.status, 200);
    assert.deepEqual(await response.json(), { id: 'ready', status: 'confirmed' });
  } finally {
    await new Promise<void>((resolve, reject) => {
      server.close(error => error ? reject(error) : resolve());
    });
  }
});

Run the tests with:

node --test example.test.ts

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.

Loading conversation…

Keep learning