Software Architecture

Domain-Driven Design: Clean Architecture, how to protect the domain model through well-designed dependencies.

Refactor order confirmation from a coupled controller into Order, a use case, a port, and adapters. Learn the dependency rule, manual composition, and tests without infrastructure, using TypeScript and Express.

Updated on October 29, 2026

Content explored 0%
18px

The indicator keeps the furthest percentage explored; marking the article complete is your choice.

The controller that needs to know everything

Order confirmation starts as a small route. Then it incorporates checks for payment, stock reservations, states, and persistence. To test a rule, the team needs to start Express and prepare a database.

Changing a column name requires reviewing business logic. Executing the same operation through another entry point means copying part of the controller.

This is an instructional counterexample; db represents a SQL client not implemented here:

app.post("/orders/:id/confirm", async (req, res) => {
  const row = await db.findOrder(req.params.id);

  if (!row) {
    res.status(404).json({ error: "ORDER_NOT_FOUND" });
    return;
  }

  if (
    row.status === "CANCELLED" ||
    row.item_count === 0 ||
    !row.payment_confirmed ||
    !row.stock_reserved
  ) {
    res.status(409).json({ error: "ORDER_CANNOT_BE_CONFIRMED" });
    return;
  }

  await db.updateOrder(req.params.id, { status: "CONFIRMED" });
  res.json({ orderId: req.params.id, status: "CONFIRMED" });
});

Besides the omitted controls, the route mixes transport, data representation, and business decisions. Separating them into files will not suffice if dependencies still point toward technical details.

We will refactor this example within the Sales context. We assume the rules have already been discovered and the goal now is to protect them.

DDD and Clean Architecture answer different questions

DDD helps represent business knowledge and rules. Clean Architecture seeks to protect internal policies from details such as transport or storage.

Its Dependency Rule states that source-code dependencies point toward internal policies. An inner layer must not know types defined by an outer one. This does not simply refer to the order of calls during execution. Robert C. Martin: The Clean Architecture.

The classic model distinguishes:

  • Entities: general business policies.
  • Use Cases: application-specific behavior.
  • Interface Adapters: conversion between representations.
  • Frameworks & Drivers: external tools and mechanisms.

We can relate them to Domain, Application, Presentation, and Infrastructure, but these are not exact equivalents. For example, HTTP and persistence adapters conceptually belong to Interface Adapters, although a project may organize them in different directories.

Clean Architecture's “Entities” is not equivalent solely to DDD's Entity pattern either. What matters here is which knowledge we protect and who may depend on it.

Draw imports and calls separately

For our example, we propose:

Code dependencies:

HTTP controller ---> Use case ---> Order model
Memory adapter ----> OrderRepository port ---> Order model
Composition -------> Implementations it connects

During a request, the use case will invoke the concrete repository. However, its code will know only an internal contract.

That is dependency inversion: application behavior does not import the storage implementation; the adapter implements the capability the application needs.

No container is required to achieve this. A constructor receiving the dependency may suffice.

Scope and rules of the example

For this fictional store, we agree an order can be confirmed when:

  • It is not canceled.
  • It contains at least one line.
  • Sales has the corresponding payment and reservation confirmations.
  • Repeating confirmation of an already confirmed order does not change its state.

The payment and reservation indicators are previously verified local facts. They are not accepted from the HTTP body and do not by themselves demonstrate a complete integration.

We will not implement charges or reservations. If those facts come from other contexts, they must be obtained through consumer contracts and translations, without importing their entities.

An Order model that does not import Express

In sales/domain/order.ts:

export interface OrderSnapshot {
  readonly id: string;
  readonly status: "PENDING" | "CONFIRMED" | "CANCELLED";
  readonly itemCount: number;
  readonly paymentConfirmed: boolean;
  readonly stockReserved: boolean;
}

export class OrderRuleError extends Error {}

export class Order {
  private constructor(private state: OrderSnapshot) {}

  static restore(snapshot: OrderSnapshot): Order {
    if (!Number.isSafeInteger(snapshot.itemCount) || snapshot.itemCount < 0) {
      throw new OrderRuleError("Cantidad de líneas inválida");
    }

    return new Order({ ...snapshot });
  }

  get id(): string {
    return this.state.id;
  }

  get status(): OrderSnapshot["status"] {
    return this.state.status;
  }

  confirm(): void {
    if (this.state.status === "CONFIRMED") return;

    if (
      this.state.status === "CANCELLED" ||
      this.state.itemCount === 0 ||
      !this.state.paymentConfirmed ||
      !this.state.stockReserved
    ) {
      throw new OrderRuleError("El pedido no puede confirmarse");
    }

    this.state = { ...this.state, status: "CONFIRMED" };
  }

  snapshot(): OrderSnapshot {
    return { ...this.state };
  }
}

We use Order as the example's aggregate root without reconstructing its entire lifecycle. restore assumes an internal representation valid in its types; the real adapter must validate data read from storage.

There are no Request, SQL rows, or HTTP codes. OrderRuleError expresses that a rule cannot be fulfilled, not that a 409 must necessarily be sent.

Copying the snapshot avoids handing out a mutable reference to the state. It is not intended as a universal domain serializer or the API's public contract.

Define the port where it is needed

The application needs to load and save Order. We choose to place its contract in Application; other designs may locate it in Domain when it serves its responsibilities. The important condition is that it must not live inside the technical adapter.

In sales/application/order-repository.ts:

import type { Order } from "../domain/order.js";

export interface LoadedOrder {
  readonly order: Order;
  readonly revision: number;
}

export interface OrderRepository {
  findById(id: string): Promise<LoadedOrder | null>;
  save(order: Order, expectedRevision: number): Promise<boolean>;
}

The save contract requires comparing the expected revision and applying the write atomically. false represents a conflict that prevented saving.

This is a bounded decision to show concurrency without an ORM. It does not mean every application must use this exact interface.

Avoid defining a port that returns SqlRow, a persistence-framework object, or an HTTP Response. A signature can also leak a dependency even if the import is marked type.

The use case coordinates without knowing storage

In sales/application/confirm-order.ts:

import type { OrderRepository } from "./order-repository.js";

export class OrderNotFoundError extends Error {}
export class OrderConflictError extends Error {}

export class ConfirmOrderUseCase {
  constructor(private readonly orders: OrderRepository) {}

  async execute(input: {
    orderId: string;
  }): Promise<{ orderId: string; status: "CONFIRMED" }> {
    const loaded = await this.orders.findById(input.orderId);

    if (!loaded) throw new OrderNotFoundError();

    if (loaded.order.status !== "CONFIRMED") {
      loaded.order.confirm();

      const saved = await this.orders.save(
        loaded.order,
        loaded.revision,
      );

      if (!saved) throw new OrderConflictError();
    }

    return { orderId: loaded.order.id, status: "CONFIRMED" };
  }
}

The use case knows the contract and model. It does not call new SqlOrderRepository(), select connections, or return an entity for direct serialization to the client.

Revision checking prevents lost changes if the port implementation fulfills its guarantee. It does not replace all process consistency rules.

Two concurrent requests could produce one success and one conflict; a later attempt may observe the confirmed order. We do not promise every concurrent repetition will succeed without examining the result.

A persistence adapter without a database

To focus on dependencies, we implement in-memory storage. In sales/infrastructure/in-memory-order-repository.ts:

import { Order, type OrderSnapshot } from "../domain/order.js";
import type {
  LoadedOrder,
  OrderRepository,
} from "../application/order-repository.js";

export class InMemoryOrderRepository implements OrderRepository {
  private readonly rows = new Map<string, {
    snapshot: OrderSnapshot;
    revision: number;
  }>();

  constructor(initial: readonly OrderSnapshot[] = []) {
    for (const snapshot of initial) {
      this.rows.set(snapshot.id, {
        snapshot: { ...snapshot },
        revision: 0,
      });
    }
  }

  async findById(id: string): Promise<LoadedOrder | null> {
    const row = this.rows.get(id);
    return row
      ? { order: Order.restore(row.snapshot), revision: row.revision }
      : null;
  }

  async save(order: Order, expectedRevision: number): Promise<boolean> {
    const current = this.rows.get(order.id);

    if (!current || current.revision !== expectedRevision) {
      return false;
    }

    this.rows.set(order.id, {
      snapshot: order.snapshot(),
      revision: current.revision + 1,
    });
    return true;
  }
}

The adapter knows the internal port and how to reconstruct the model. The application does not know this Map.

Comparison and writing contain no intervening wait and work for a single in-memory instance. This is neither durable storage nor a concurrency solution for multiple processes.

A SQL adapter would need to compare and update atomically, verify the result, and translate errors and representations. Reading a revision and updating afterward without protection is insufficient.

Changing it involves real implementation, testing, and operational work. The architecture prevents that detail from redefining Order's rules; it does not make migration free.

The controller transforms HTTP into a simple input

We use Express 5 for the entry point. Errors from asynchronous handlers propagate to error middleware; that behavior must be considered when using another version or framework. Express: error handling.

In sales/presentation/http.ts:

import express, {
  type Request,
  type ErrorRequestHandler,
} from "express";
import {
  ConfirmOrderUseCase,
  OrderNotFoundError,
  OrderConflictError,
} from "../application/confirm-order.js";
import { OrderRuleError } from "../domain/order.js";

export class OrderAccessError extends Error {
  constructor(readonly status: 401 | 403) {
    super("Access denied");
  }
}

export type AuthorizeConfirmation = (
  request: Request,
  orderId: string,
) => Promise<void>;

export function createOrderHttpApp(
  confirmOrder: ConfirmOrderUseCase,
  authorize: AuthorizeConfirmation,
) {
  const app = express();
  app.disable("x-powered-by");

  app.post("/orders/:id/confirm", async (req, res) => {
    const orderId = req.params.id;

    if (
      typeof orderId !== "string" ||
      !/^[A-Za-z0-9_-]{1,64}$/.test(orderId)
    ) {
      res.status(400).json({ error: "INVALID_ORDER_ID" });
      return;
    }

    await authorize(req, orderId);
    const output = await confirmOrder.execute({ orderId });
    res.status(200).json(output);
  });

  const errors: ErrorRequestHandler = (error: unknown, _req, res, _next) => {
    if (error instanceof OrderAccessError) {
      res.status(error.status).json({ error: "ACCESS_DENIED" });
      return;
    }

    if (error instanceof OrderNotFoundError) {
      res.status(404).json({ error: "ORDER_NOT_FOUND" });
      return;
    }

    if (
      error instanceof OrderRuleError ||
      error instanceof OrderConflictError
    ) {
      res.status(409).json({ error: "ORDER_CONFIRMATION_CONFLICT" });
      return;
    }

    res.status(500).json({ error: "INTERNAL_ERROR" });
  };

  app.use(errors);
  return app;
}

authorize is a required dependency that must authenticate and check permission for that order. No fictional production implementation is provided. If the entry point uses cookies, it must also apply the corresponding protection against cross-site requests.

This tutorial separates HTTP control to limit the example. If the use case is exposed through other entry points, each must apply the necessary authorization policy; a common application policy can live within Application through its own contracts.

The client cannot mark payment or reservation valid by sending booleans: the route does not accept them as input.

Manual composition: knowing details in the right place

In composition.ts:

import { ConfirmOrderUseCase } from "./sales/application/confirm-order.js";
import { InMemoryOrderRepository } from "./sales/infrastructure/in-memory-order-repository.js";
import {
  createOrderHttpApp,
  type AuthorizeConfirmation,
} from "./sales/presentation/http.js";

export function composeExample(
  authorize: AuthorizeConfirmation,
) {
  const repository = new InMemoryOrderRepository([{
    id: "order-100",
    status: "PENDING",
    itemCount: 2,
    paymentConfirmed: true,
    stockReserved: true,
  }]);

  const confirmOrder = new ConfirmOrderUseCase(repository);
  return createOrderHttpApp(confirmOrder, authorize);
}

The composition root knows concrete implementations because its responsibility is to connect them. That does not authorize the domain to import them back.

The example does not start a server or include authentication or project configuration. It assumes TypeScript, Node.js, Express 5, and their types are available, with suitable ESM compilation. It is not a production-ready deployment.

The files shown contain the pieces of the instructional walkthrough. We do not need Inversify to understand how an implementation connects to a contract.

Walk through the operation

With valid authorization, a POST /orders/order-100/confirm request loads a copy of the pending order, applies its rule, and saves the new revision.

The response is:

{
  "orderId": "order-100",
  "status": "CONFIRMED"
}

A subsequent repository read observes the new state. In memory, it is lost on restart; the limitation is explained rather than hidden behind the name “persistence.”

Test without Express or a real database

These proposed tests use built-in Node.js APIs and assume files compiled to ESM JavaScript. They have not been run as part of the article.

In confirm-order.test.ts:

import test from "node:test";
import assert from "node:assert/strict";
import { OrderRuleError } from "./sales/domain/order.js";
import { ConfirmOrderUseCase } from "./sales/application/confirm-order.js";
import { InMemoryOrderRepository } from "./sales/infrastructure/in-memory-order-repository.js";

test("confirma y conserva el resultado en el adaptador de pruebas", async () => {
  const repository = new InMemoryOrderRepository([{
    id: "order-100",
    status: "PENDING",
    itemCount: 2,
    paymentConfirmed: true,
    stockReserved: true,
  }]);

  const useCase = new ConfirmOrderUseCase(repository);
  assert.deepEqual(await useCase.execute({ orderId: "order-100" }), {
    orderId: "order-100",
    status: "CONFIRMED",
  });

  assert.equal(
    (await repository.findById("order-100"))?.order.status,
    "CONFIRMED",
  );
});

test("no guarda una confirmación cuando falta el pago", async () => {
  const repository = new InMemoryOrderRepository([{
    id: "order-100",
    status: "PENDING",
    itemCount: 2,
    paymentConfirmed: false,
    stockReserved: true,
  }]);

  const useCase = new ConfirmOrderUseCase(repository);
  await assert.rejects(
    () => useCase.execute({ orderId: "order-100" }),
    OrderRuleError,
  );

  assert.equal(
    (await repository.findById("order-100"))?.order.status,
    "PENDING",
  );
});

These are use-case tests with a controlled adapter. They do not cover transport, authorization, or a real database.

Cancellation, repetition, a nonexistent order, and revision conflicts must also be checked. A real adapter needs its own contract and concurrency verification.

Technical independence makes it possible to test decisions without starting the whole application. It does not make integration tests unnecessary.

Detect violations before they grow

Review imports and signatures, not just folders.

Concrete signals:

  • Order imports Express or a database client.
  • ConfirmOrderUseCase creates the SQL adapter directly.
  • OrderRepository returns driver-specific rows.
  • The controller decides an unpaid order can be confirmed.
  • A use case receives Request or modifies Response.
  • Composition is imported from the domain.

TypeScript removes interfaces when compiling, but that does not stop them from leaking technical concepts during design. import type does not turn an incorrect dependency into a correct one.

Architecture checks can automate import restrictions. Reviews and tests remain necessary to detect misplaced decisions or insufficiently expressive contracts.

Boundaries between contexts and overengineering

Clean Architecture does not authorize importing the Payments aggregate into Sales because it is “domain.” Protecting internal layers and respecting boundaries between contexts are distinct conditions that must be maintained together.

If Sales needs evidence from another context, its application can define a port and receive a translation through an HTTP ACL. The call does not automatically form part of its local transaction.

Nor must all these pieces be repeated for a trivial operation. A small administrative query can use a read representation without reconstructing an aggregate that adds no behavior.

In an educational platform, a rule allowing completion of an activity deserves separation from screen or storage details. A static tag list may only need a simple function.

In reservations, an overlap policy can be tested without a framework. A bounded text export may not need an interface for every transformation.

The level of structure must reflect real value and complexity. Multiplying delegating classes without their own responsibilities can make behavior harder to follow.

Give AI verifiable rules

For Cursor, Codex, or Claude, specify which dependencies are permitted.

To implement:

Work in Sales with Domain free of framework dependencies. ConfirmOrderUseCase receives OrderRepository defined in Application. The adapter implements that port and composition is manual. Do not import entities from other contexts or accept financial evidence from HTTP.

To review:

Review imports, input and output types, and dependency creation. Identify where an internal policy knows Express, SQL, or external DTOs. Propose minimal changes and explain which behavior they protect. Do not evaluate architecture solely by folder names.

To test:

Design use-case tests without a server or real database for confirmation, rejection, and conflicts. Separate those tests from the ones needed for the persistence adapter and authorization. Do not claim the in-memory double demonstrates durability or concurrency between processes.

A person must confirm rules and guarantees. An agent can respect the folder tree while still placing the business decision in the wrong place.

Exercises

1. The interface placed outside

OrderRepository lives beside the SQL client, and Application imports it from there. What would you review?

2. The convenient HTTP type

The use case accepts Request to read a header and save an input object. What dependency does it introduce?

3. More folders, the same decision

The controller calls a service that confirms any order and then checks payment before sending the response. Has the rule been protected?

Reasoned solutions

1. Who defines the need. If the port belongs to the application, it must be able to exist without knowing the technical adapter. Moving the contract and eliminating driver types can correctly invert the dependency.

2. The use case becomes tied to transport and its types. The entry point must translate what is needed into its own representation, or use an application contract for the required capability.

3. No. The rule is checked afterward and remains outside the protected behavior. Confirmation must not be persisted before evaluating its conditions. Changing filenames does not correct order or responsibility.

Protect policies through visible decisions

Clean Architecture complements modeling when rules can be understood and tested without depending on how a request arrives or where data is stored.

The evidence lies in dependencies, contracts, and tests, not in reproducing a circle diagram.

Start with a relevant rule and a clear boundary. Add the pieces that sustain them, keeping explicit the guarantees the example does not yet implement.

Loading conversation…

Keep learning