Skip to content
Kavindu's Blog
Go back

Domain-Driven Design Goes Inside the Hexagon: DDD and Ports & Adapters in TypeScript

Kavindu Manahara

Domain-Driven Design Goes Inside the Hexagon: DDD and Ports & Adapters in TypeScript

I opened my Search Console report this week and found 92 impressions for “domain-driven design hexagonal architecture”, all pointing at my post about Clean and Hexagonal Architecture. That post doesn’t mention domain-driven design once. Not in a heading, not in a footnote. Google was sending people looking for one thing to a page about something next to it.

Which is fair, honestly. The two get searched together because they get taught together, usually badly, and usually as if they were the same idea. They aren’t. Hexagonal architecture tells you where the walls go. Domain-driven design tells you what to build inside them. This is the post those 92 people were actually looking for.

What is domain-driven design?

Domain-driven design (DDD) is an approach to building software where the code is organized around the business domain itself, modeled with the same words the business uses, instead of around database tables or framework layers. Eric Evans named it in his 2003 book Domain-Driven Design: Tackling Complexity in the Heart of Software, and it comes in two halves that people tend to learn in the wrong order.

The strategic half is about drawing boundaries. A ubiquitous language means developers and the business use the same words for the same things, in conversation and in code. A bounded context is the boundary inside which one of those words has one meaning.

The tactical half is the toolbox for the code inside one boundary: entities, value objects, aggregates, repositories, domain events. This is the half everyone blogs about, because it has code in it. It’s also the less important half, which I’ll come back to.

DDD vs hexagonal architecture: what’s the difference?

Hexagonal architecture decides how your application talks to the outside world, through ports and adapters, while domain-driven design decides how to model the business logic that sits in the middle. One is about the boundary, the other is about the contents. They answer different questions, which is exactly why they combine so well.

Hexagonal (Ports & Adapters) Domain-Driven Design
Question it answers How does my app connect to databases, HTTP, queues? How do I model the business rules themselves?
Main idea Dependencies point inward through ports Code mirrors the business language and its boundaries
Key pieces Ports, driving adapters, driven adapters Bounded contexts, aggregates, value objects, domain events
Says nothing about What the domain model looks like How you plug in Postgres or REST
Origin Alistair Cockburn, 2005 Eric Evans, 2003

Hexagonal architecture deliberately says nothing about how you structure the inside of the hexagon, which is exactly why DDD slots into it so easily. (Cockburn and Juan Manuel Garrido de Paz wrote a whole book on the pattern in 2024, Hexagonal Architecture Explained, if you want the long version.) DDD is one very good answer to “what goes in the middle?”, not a requirement.

flowchart LR
    HTTP[REST controller] --> UC
    subgraph Hexagon
        UC[PlaceOrder use case] --> AGG[Order aggregate]
        AGG --> VO[Money value object]
        UC --> REPO{{OrderRepository port}}
        UC --> PUB{{EventPublisher port}}
    end
    REPO --> DB[(Postgres adapter)]
    PUB --> MQ[Queue adapter]

Everything inside the box is DDD. Everything crossing the box’s edge is hexagonal. The two diamonds are where they shake hands.

Where each DDD building block lives inside the hexagon

Each tactical DDD pattern has a natural home in a ports-and-adapters layout, and once you see the mapping, most of the “how do these fit together” confusion goes away.

DDD pattern Lives in Job
Value object (Money) Domain An immutable value with rules, compared by its contents
Entity / aggregate (Order) Domain Something with an identity that guards its own invariants
Domain event (OrderPlaced) Domain A fact the domain announces after something happened
Repository interface Domain (it’s a port) Load and save aggregates, nothing else
Application service (PlaceOrder) Application One use case: load, call the domain, save, publish
Repository implementation Adapter The Postgres, Prisma or in-memory version of the port

The row that matters most is the repository. A DDD repository is a hexagonal port. Same interface, two names, much like the “three names for one idea” thing from the last post. The domain declares “I need to load and save orders”, and an adapter outside the hexagon decides that means Postgres.

The rest of this post builds that table in TypeScript. I compiled every snippet below under strict and ran it against a small set of assertions before publishing, so it should paste cleanly.

A value object: Money

A value object is a small immutable type defined entirely by its values, so two of them with the same contents are interchangeable. Money is the classic one, because passing money around as a bare number is how you end up adding rupees to dollars.

export class Money {
  private constructor(
    readonly cents: number,
    readonly currency: string,
  ) {}

  static of(amount: number, currency: string): Money {
    if (!Number.isFinite(amount) || amount < 0) {
      throw new Error(`Invalid amount: ${amount}`);
    }
    return new Money(Math.round(amount * 100), currency);
  }

  static zero(currency: string): Money {
    return new Money(0, currency);
  }

  add(other: Money): Money {
    if (other.currency !== this.currency) {
      throw new Error(`Cannot add ${other.currency} to ${this.currency}`);
    }
    return new Money(this.cents + other.cents, this.currency);
  }

  times(quantity: number): Money {
    return new Money(this.cents * quantity, this.currency);
  }

  equals(other: Money): boolean {
    return this.cents === other.cents && this.currency === other.currency;
  }
}

Two lines are doing the real work. The private constructor means the only way to make a Money is through of(), which rejects negative and non-numeric amounts, so an invalid one can’t exist anywhere in the program. And add() refuses to mix currencies. That rule now lives in exactly one place, instead of in every service that ever sums two prices.

Storing cents as an integer is the other quiet decision. 0.1 + 0.2 is still 0.30000000000000004 in JavaScript, and I’d rather not find that out on an invoice.

An aggregate: Order

An aggregate is a cluster of objects treated as one unit for changes, with one root entity that every change has to go through so the business rules can’t be bypassed. Here the root is Order, and the order lines can only be touched through it.

import { Money } from "./money";

export type OrderPlaced = { type: "OrderPlaced"; orderId: string; total: Money };

type OrderLine = { sku: string; quantity: number; unitPrice: Money };
type OrderStatus = "draft" | "placed";

export class Order {
  private lines: OrderLine[] = [];
  private status: OrderStatus = "draft";
  private events: OrderPlaced[] = [];

  private constructor(
    readonly id: string,
    readonly currency: string,
  ) {}

  static create(id: string, currency: string): Order {
    return new Order(id, currency);
  }

  // Rebuild from storage without re-running business rules or raising events.
  static restore(id: string, currency: string, status: OrderStatus, lines: OrderLine[]): Order {
    const order = new Order(id, currency);
    order.status = status;
    order.lines = lines.map(line => ({ ...line }));
    return order;
  }

  addLine(sku: string, quantity: number, unitPrice: Money): void {
    if (this.status === "placed") throw new Error("Cannot change a placed order");
    if (!Number.isInteger(quantity) || quantity <= 0) throw new Error("Quantity must be a positive whole number");
    if (unitPrice.currency !== this.currency) throw new Error(`Order is in ${this.currency}`);

    const existing = this.lines.find(line => line.sku === sku);
    if (existing) existing.quantity += quantity;
    else this.lines.push({ sku, quantity, unitPrice });
  }

  total(): Money {
    return this.lines.reduce(
      (sum, line) => sum.add(line.unitPrice.times(line.quantity)),
      Money.zero(this.currency),
    );
  }

  place(): void {
    if (this.status === "placed") throw new Error("Order is already placed");
    if (this.lines.length === 0) throw new Error("Cannot place an empty order");
    this.status = "placed";
    this.events.push({ type: "OrderPlaced", orderId: this.id, total: this.total() });
  }

  snapshot() {
    return { id: this.id, currency: this.currency, status: this.status, lines: this.lines.map(l => ({ ...l })) };
  }

  pullEvents(): OrderPlaced[] {
    const events = this.events;
    this.events = [];
    return events;
  }
}

Notice what’s missing: there’s no setStatus() and no public lines array. You can’t put an order into a weird state from outside, because the only doors in are addLine() and place(), and both check the rules first. A placed order can’t change. An empty order can’t be placed. A line in the wrong currency is rejected. That’s what people mean by an aggregate protecting its invariants, and it’s the opposite of the “anemic” model where Order is a bag of public fields and the rules are scattered across five services.

The create versus restore split looks like ceremony at first. Creating a new order and loading an existing one from the database are different events in the business. Loading shouldn’t re-validate history or fire OrderPlaced a second time, so it gets its own door.

The repository is just a port

A repository in DDD is an interface, declared in the domain, for loading and saving whole aggregates, and in hexagonal terms it’s a driven port. The domain says what it needs. It doesn’t say Postgres.

import { Order, OrderPlaced } from "./order";

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

export interface EventPublisher {
  publish(event: OrderPlaced): Promise<void>;
}

One repository per aggregate, not one per table. There’s no OrderLineRepository, because nobody outside the aggregate is allowed to load a line on its own. That rule sounds pedantic until you’ve seen a codebase where three services update order_lines directly and nobody can tell you which one broke the totals.

The application service stays boring

An application service runs one use case from start to finish: load the aggregate, ask it to do something, save it, and publish what happened. It holds no business rules of its own, and if it starts to, those rules belong in the domain.

import { EventPublisher, OrderRepository } from "../domain/ports";

export class PlaceOrder {
  constructor(
    private readonly orders: OrderRepository,
    private readonly events: EventPublisher,
  ) {}

  async execute(orderId: string): Promise<void> {
    const order = await this.orders.findById(orderId);
    if (!order) throw new Error(`Order ${orderId} not found`);

    order.place();
    await this.orders.save(order);

    for (const event of order.pullEvents()) {
      await this.events.publish(event);
    }
  }
}

PlaceOrder doesn’t know if an order can be placed. It asks the order, and the order throws if the answer is no. Testing it needs no database at all: an in-memory OrderRepository is about ten lines, and that’s what I ran the assertions against.

There’s an honest gap here though. If the process dies between save() and publish(), the order is placed and nobody hears about it. The real fix is a transactional outbox, writing the event to an outbox table in the same transaction as the order and publishing it from there. I left it out to keep the example readable, but I wouldn’t ship this exact loop for anything that moves money.

Wiring it into NestJS without leaking Nest into the domain

NestJS can inject interface-based ports through Symbol tokens, and a useFactory provider can build the application service, so not one decorator ends up in the domain or application code. TypeScript interfaces disappear at runtime, which is why the tokens are needed at all.

export const ORDER_REPOSITORY = Symbol("ORDER_REPOSITORY");
export const EVENT_PUBLISHER = Symbol("EVENT_PUBLISHER");

@Module({
  controllers: [OrdersController],
  providers: [
    { provide: ORDER_REPOSITORY, useClass: PrismaOrderRepository },
    { provide: EVENT_PUBLISHER, useClass: OutboxEventPublisher },
    {
      provide: PlaceOrder,
      useFactory: (orders: OrderRepository, events: EventPublisher) =>
        new PlaceOrder(orders, events),
      inject: [ORDER_REPOSITORY, EVENT_PUBLISHER],
    },
  ],
})
export class OrdersModule {}

PrismaOrderRepository and OutboxEventPublisher are the adapters, and they’re the only classes here allowed to import Prisma or know a queue exists. The controller injects PlaceOrder like any other provider. This module file is the one place where the outside world and the hexagon meet, which is the same job main.go did by hand in the Go version from the last post.

Bounded contexts are the part people skip

A bounded context is a boundary inside which every domain term has exactly one meaning, and it matters more than every tactical pattern above put together. “Order” in a sales context is a cart with prices and discounts. “Order” in a shipping context is a parcel with a weight and an address. Forcing both into one Order class is how you get a 2,000-line model that every team is scared to touch.

DDD’s answer is to let each context have its own model, even if the names overlap, and to have them talk through events instead of sharing tables. Sales raises OrderPlaced. Shipping listens and creates its own Shipment, with only the fields shipping cares about.

This is also where the two ideas fit together best. Each bounded context can be its own hexagon, with its own ports and adapters, whether it’s a separate service or just a folder in a modular monolith. That’s arguably the most useful sentence in this post, and it’s the one I’d put first if I were teaching this.

It’s also why DDD is having a bit of a second life right now. Evans used his Explore DDD 2024 keynote to talk about building with large language models, and a lot of 2025 and 2026 talks are about using bounded contexts to keep AI-agent codebases from turning into one giant prompt. Same problem, newer tooling: a big blob of logic with no boundaries is hard to change, whether a person or a model is doing the changing.

When DDD is overkill

DDD pays off when the business rules are the hard part of the system, and it’s wasted ceremony when the system is mostly moving data between a form and a table. If your Order would have no methods except getters and setters, you don’t have a domain model to protect. You have CRUD, and that’s fine.

The multi-tenant app from my CloudNativePG posts is a good example. It’s organized as plain NestJS feature modules, not bounded contexts, and most of it is exactly that kind of CRUD. The places where I’d reach for an aggregate are the few with real rules, like what’s allowed to happen to a tenant once it’s suspended. Doing DDD everywhere would have added a lot of files and protected very little.

A rough rule I’d use: start with the strategic half (shared language, clear boundaries) everywhere, because it’s cheap. Pull in the tactical patterns one aggregate at a time, only where an invariant has actually been broken, or obviously could be.

Those 92 searches now have a page that answers them. The next time Search Console shows me a gap like that, I’ll take it as a hint about what I’ve been explaining badly, not just as a keyword.


References


Share this post: