Software Architecture

Domain-Driven Design: Domain Events, how to represent business facts and decouple processes

Learn to record business facts from an Aggregate Root and process them with TypeScript handlers. An order case explores tests, idempotency, post-save failures, and when to incorporate a Transactional Outbox.

Updated on October 29, 2026

Content explored 0%
18px

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

A confirmed order can interest several parts of the system

A customer confirms an order. The application must save that change, update a commercial view, and prepare a notification. Initially, everything ends up inside Order.confirm(): one repository call, another to email, and a third to the statistics service.

The method starts knowing decisions that do not belong to it. An uncomfortable question also appears: if the order was saved but the notification fails, is the order confirmed or not?

A Domain Event expresses the fact originating those reactions: OrderConfirmed. The order records what happened; other components decide how to react. This separates responsibilities but does not itself solve delivery, retries, or transactions.

We will work with TypeScript and Node.js, initially in memory. The example is independent of any particular repository and adds no messaging services. We will revisit only what is needed from Aggregates and Repositories to follow a confirmation's path.

The event tells what happened, not what we want to try

A domain event preserves an occurrence relevant to the business. The central idea is that its meaning survives the technical detail producing it: “order confirmed” still makes sense if you change databases. Martin Fowler's classic Domain Event description focuses on remembering a significant fact and distinguishes when it occurred from when it was observed.

Separate four concepts:

  • Command: requests an action. ConfirmOrder may be rejected if the order fails a rule.
  • Domain Event: expresses a fact accepted by the model. OrderConfirmed does not ask permission to confirm; it records that the transition has already occurred in that model.
  • Integration Event: communicates to another system a fact the application decided to expose after committing its transaction. It is an exchange contract, not an automatic copy of the internal object.
  • Technical event: describes infrastructure, such as a closed connection or inserted row. It may be useful without necessarily representing a business decision.

“Already happened” needs clarification: the aggregate may record the event before commit. If persistence rolls back, you must not announce it externally as a confirmed fact. Later we will separate in-memory recording from durable publication.

Naming helps preserve that intent. OrderConfirmed, EnrollmentCancelled, and ShipmentDispatched speak in the past tense. SendEmail, UpdateStatistics, and NotifyWarehouse are instructions. Turning them into event names does not transform them into business facts.

When a Domain Event deserves to exist

You need not emit an event for every assignment. Ask whether a business person would recognize the fact, whether it has an identifiable moment, and whether a reaction needs to know about it without being embedded in the changed object.

Changing to “confirmed” may justify OrderConfirmed. An internal operation recalculating a temporary variable usually does not. Nor should you create OrderChanged for everything: it forces consumers to reconstruct what happened by reading current state.

In our example, confirmation means the order stopped being a draft and has a positive amount. It does not mean “payment collected” or “stock reserved.” Those would be different facts, and we cannot promise them with this event.

If you only want to apply a discount within the same aggregate before confirmation, an explicit call to the corresponding behavior may suffice. Events add value when making real collaboration visible; used to hide every call, they make the flow harder to follow.

Design the message: identity, time, and facts

OrderConfirmed will include an event identifier, order, customer, amount, currency, occurrence time, and aggregate version. The identifier enables recognizing redelivery; the version helps locate the change within the order.

The amount will be the confirmation amount, not a reference to a mutable object that might contain another value tomorrow. We will avoid including the whole aggregate, connections, repositories, or secrets. Consumers receive bounded data, not permission to modify the order.

No universal field list exists. A handler needing only the identifier does not justify copying all customer information. In an integration, you will also choose which data can leave, who can read them, and how the contract evolves.

We will use Readonly and Object.freeze. readonly is a type-checker restriction, not runtime freezing, as TypeScript documentation clarifies. Object.freeze is shallow: sufficient here because the event contains primitive values. With arrays or nested objects, you would need to design copies and protection for those values, without assuming automatic deep immutability.

Complete case: from Aggregate Root to handlers

The following example comes in three parts of the same domain-events.mts file. Paste them in order without adding separators. It uses only built-in Node.js modules. Sections represent logical responsibilities; in a real application, you would separate domain, application, infrastructure, and tests into their respective files.

It demonstrates in-memory delivery without guaranteed recovery after a crash. It does not attempt to implement an outbox, real email, HTTP server, or ORM. Tests deliberately include that limitation. Amounts are expressed as integers in USD cents; the model omits lines and other real-order rules.

domain-events.mts · 1/3

import assert from "node:assert/strict";
import test from "node:test";

type OrderConfirmed = Readonly<{
  type: "OrderConfirmed";
  eventId: string;
  occurredAt: string;
  orderId: string;
  customerId: string;
  totalCents: number;
  currency: "USD";
  aggregateVersion: number;
}>;

type OrderSnapshot = Readonly<{
  id: string;
  customerId: string;
  totalCents: number;
  status: "draft" | "confirmed";
  version: number;
}>;

type EventContext = Readonly<{
  eventId: string;
  occurredAt: string;
}>;

class Order {
  private state: OrderSnapshot;
  private events: OrderConfirmed[] = [];

  private constructor(snapshot: OrderSnapshot) {
    this.state = Object.freeze({ ...snapshot });
  }

  static draft(id: string, customerId: string, totalCents: number): Order {
    if (!id.trim() || !customerId.trim()) throw new Error("Missing identity");
    if (!Number.isSafeInteger(totalCents) || totalCents < 0) {
      throw new Error("Invalid total");
    }
    return new Order({ id, customerId, totalCents, status: "draft", version: 0 });
  }

  static restore(snapshot: OrderSnapshot): Order {
    // El repositorio de esta demo solo almacena snapshots creados por Order.
    return new Order(snapshot);
  }

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

  pendingEvents(): readonly OrderConfirmed[] {
    return Object.freeze([...this.events]);
  }

  confirm(context: EventContext): void {
    if (this.state.status === "confirmed") return;
    if (this.state.totalCents === 0) throw new Error("Cannot confirm an empty total");
    if (!context.eventId.trim() || Number.isNaN(Date.parse(context.occurredAt))) {
      throw new Error("Invalid event context");
    }

    const version = this.state.version + 1;
    const event: OrderConfirmed = Object.freeze({
      type: "OrderConfirmed",
      eventId: context.eventId,
      occurredAt: context.occurredAt,
      orderId: this.state.id,
      customerId: this.state.customerId,
      totalCents: this.state.totalCents,
      currency: "USD",
      aggregateVersion: version,
    });

    this.state = Object.freeze({ ...this.state, status: "confirmed", version });
    this.events.push(event);
  }

  pullEvents(): readonly OrderConfirmed[] {
    const result = Object.freeze([...this.events]);
    this.events = [];
    return result;
  }
}

The aggregate root protects the transition and records an event only if it occurred. Repeating confirm() on that already confirmed order does not add another confirmation. This makes this specific transition idempotent, not every application command: operations such as “add one unit” need another strategy to distinguish a retry from a new request.

The event context is injected. The application decides how to generate identifiers and obtain the clock; the aggregate imports no bus, AWS, or database client.

pendingEvents() allows reading without emptying; pullEvents() returns and clears the collection. Using the latter before saving and forgetting its result if saving fails would be an error. Deferred recording lets dispatch timing be decided afterward, a separation explained by Microsoft's domain-event guide.

domain-events.mts · 2/3

interface OrderRepository {
  get(id: string): Promise<Order>;
  save(order: Order, expectedVersion: number): Promise<void>;
}

class MemoryOrderRepository implements OrderRepository {
  private rows = new Map<string, OrderSnapshot>();
  failNextSave = false;

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

  async get(id: string): Promise<Order> {
    const snapshot = this.rows.get(id);
    if (!snapshot) throw new Error("Order not found");
    return Order.restore(snapshot);
  }

  async save(order: Order, expectedVersion: number): Promise<void> {
    if (this.failNextSave) {
      this.failNextSave = false;
      throw new Error("Save failed");
    }
    const next = order.snapshot();
    const previous = this.rows.get(next.id);
    if (!previous || previous.version !== expectedVersion) {
      throw new Error("Concurrent modification");
    }
    this.rows.set(next.id, next);
  }
}

interface OrderConfirmedHandler {
  handle(event: OrderConfirmed): Promise<void>;
}

class InMemoryDispatcher {
  private handlers: OrderConfirmedHandler[] = [];

  subscribe(handler: OrderConfirmedHandler): void {
    this.handlers.push(handler);
  }

  async dispatch(events: readonly OrderConfirmed[]): Promise<void> {
    for (const event of events) {
      for (const handler of this.handlers) await handler.handle(event);
    }
  }
}

class MemorySalesSummary implements OrderConfirmedHandler {
  private processed = new Set<string>();
  totalCents = 0;

  async handle(event: OrderConfirmed): Promise<void> {
    if (this.processed.has(event.eventId)) return;
    // No hay await entre el efecto y la marca en esta demo de un solo proceso.
    this.totalCents += event.totalCents;
    this.processed.add(event.eventId);
  }
}

class MemoryNotificationQueue implements OrderConfirmedHandler {
  readonly pending = new Map<string, Readonly<{ orderId: string; customerId: string }>>();

  async handle(event: OrderConfirmed): Promise<void> {
    if (this.pending.has(event.eventId)) return;
    this.pending.set(event.eventId, Object.freeze({
      orderId: event.orderId,
      customerId: event.customerId,
    }));
  }
}

class ConfirmOrder {
  private repository: OrderRepository;
  private dispatcher: InMemoryDispatcher;
  private nextEventId: () => string;
  private now: () => string;

  constructor(
    repository: OrderRepository,
    dispatcher: InMemoryDispatcher,
    nextEventId: () => string,
    now: () => string,
  ) {
    this.repository = repository;
    this.dispatcher = dispatcher;
    this.nextEventId = nextEventId;
    this.now = now;
  }

  async execute(orderId: string): Promise<void> {
    const order = await this.repository.get(orderId);
    const expectedVersion = order.snapshot().version;
    order.confirm({ eventId: this.nextEventId(), occurredAt: this.now() });
    if (order.pendingEvents().length === 0) return;

    await this.repository.save(order, expectedVersion);
    // Guardar primero evita anunciar una confirmación cuyo guardado falló.
    // NO elimina el intervalo de pérdida entre guardar y despachar.
    await this.dispatcher.dispatch(order.pullEvents());
  }
}

The flow is explicit: load, execute the rule, save with version control, and dispatch. The repository returns a reconstructed instance, not a reference to the same object it stores. Thus, a modification not yet persisted does not accidentally alter the in-memory “database.”

The dispatcher handles only OrderConfirmed. That limitation avoids introducing a generic framework to teach one event. Handlers are awaited sequentially; if one fails, later ones do not run. Their order is a visible implementation decision, not a guarantee to assume when changing buses.

The commercial summary and notification queue are test infrastructure. They are not domain services: they react to the fact and maintain auxiliary effects without deciding whether the order could be confirmed. They do not send real email either.

Sets and maps prevent repetition of the same event from duplicating those effects within this in-memory instance. Everything is lost upon restart. A RAM Set provides neither persistent idempotency nor coordination between processes.

Tests: also verify the uncomfortable case

The third part tests both successful results and relevant failures. Checking a handler was invoked is insufficient: when the order was saved, what happened on failure, and what a retry does matter.

domain-events.mts · 3/3

const instant = "2026-01-15T10:00:00.000Z";

function fixture() {
  const order = Order.draft("order-1", "customer-1", 2500);
  const repository = new MemoryOrderRepository([order.snapshot()]);
  const dispatcher = new InMemoryDispatcher();
  const sales = new MemorySalesSummary();
  const notifications = new MemoryNotificationQueue();
  const command = new ConfirmOrder(repository, dispatcher, () => "event-1", () => instant);
  return { repository, dispatcher, sales, notifications, command };
}

test("la regla registra un solo hecho inmutable", () => {
  const order = Order.draft("order-1", "customer-1", 2500);
  order.confirm({ eventId: "event-1", occurredAt: instant });
  order.confirm({ eventId: "event-2", occurredAt: instant });
  assert.equal(order.snapshot().version, 1);
  assert.equal(order.pendingEvents().length, 1);
  const event = order.pendingEvents()[0];
  assert.ok(event);
  assert.equal(event.totalCents, 2500);
  assert.equal(Object.isFrozen(event), true);
  assert.equal(order.pullEvents().length, 1);
  assert.equal(order.pendingEvents().length, 0);

  const empty = Order.draft("empty", "customer-1", 0);
  assert.throws(() => empty.confirm({ eventId: "event-3", occurredAt: instant }));
  assert.equal(empty.snapshot().status, "draft");
  assert.equal(empty.pendingEvents().length, 0);
});

test("el guardado precede a los handlers y una reentrega no duplica efectos", async () => {
  const f = fixture();
  const received: OrderConfirmed[] = [];
  f.dispatcher.subscribe({ async handle(event) {
    assert.equal((await f.repository.get(event.orderId)).snapshot().status, "confirmed");
    received.push(event);
  } });
  f.dispatcher.subscribe(f.sales);
  f.dispatcher.subscribe(f.notifications);
  await f.command.execute("order-1");
  await f.dispatcher.dispatch(received.slice(0, 1));
  await f.command.execute("order-1");
  assert.equal(f.sales.totalCents, 2500);
  assert.equal(f.notifications.pending.size, 1);
});

test("un guardado fallido no publica la confirmación", async () => {
  const f = fixture();
  f.dispatcher.subscribe(f.sales);
  f.repository.failNextSave = true;
  await assert.rejects(f.command.execute("order-1"), /Save failed/);
  assert.equal((await f.repository.get("order-1")).snapshot().status, "draft");
  assert.equal(f.sales.totalCents, 0);
});

test("fallar después de guardar no revierte el pedido ni repara la entrega", async () => {
  const f = fixture();
  f.dispatcher.subscribe(f.sales);
  f.dispatcher.subscribe({ async handle() { throw new Error("Notification unavailable"); } });
  f.dispatcher.subscribe(f.notifications);
  await assert.rejects(f.command.execute("order-1"), /Notification unavailable/);
  assert.equal((await f.repository.get("order-1")).snapshot().status, "confirmed");
  assert.equal(f.sales.totalCents, 2500);
  assert.equal(f.notifications.pending.size, 0);
  // El estado confirmado evita otro evento, pero el pendiente no está persistido.
  await f.command.execute("order-1");
  assert.equal(f.notifications.pending.size, 0);
});

test("dos instancias no pueden guardar sobre la misma versión", async () => {
  const f = fixture();
  const first = await f.repository.get("order-1");
  const second = await f.repository.get("order-1");
  first.confirm({ eventId: "first", occurredAt: instant });
  second.confirm({ eventId: "second", occurredAt: instant });
  await f.repository.save(first, 0);
  await assert.rejects(f.repository.save(second, 0), /Concurrent modification/);
});

To run the file with Node.js 24 and its type-stripping support, using only the compatible syntax shown here:

node --test domain-events.mts

That runs tests but does not perform static TypeScript checking. If your project already has TypeScript and Node types installed, also check:

tsc --noEmit --strict --target ES2022 --module NodeNext --moduleResolution NodeNext domain-events.mts

The post-save failure test is intentional: the operation returns an error, but the order remains confirmed. Repeating the command does not reconstruct the pending event. Persisting state is not equivalent to persisting delivery intent. The demonstration must not be used as guaranteed production notification.

Synchronous, asynchronous, and transactional are different decisions

In this dispatcher, every handler returns a promise and the application awaits it. That introduces neither a durable queue nor a separate process. Execution is in the same process, sequential, and awaited by whoever confirmed the order. An async function does not turn a call into distributed messaging.

Nor is replacing await handler.handle(event) with a call without await enough. You would have unawaited work that could fail or disappear when the process ends, without an explicit recovery policy.

This snippet is incorrect if you expect reliable delivery; it is not another part of the executable file:

await repository.save(order, expectedVersion);
void dispatcher.dispatch(order.pullEvents());
// Ignorar la promesa no crea una cola ni conserva los eventos ante una caída.

Awaiting the promise allows failure to be observed, as our tests do. Recovering from a crash also requires durably recording pending work; changing only await usage does not achieve that.

Distinguish two possible moments:

  1. Before commit: certain handlers can participate in the same local transaction if they truly share its persistence context. If a participating write fails, everything can roll back. Do not include email or an HTTP call assuming rollback will undo them.
  2. After commit: the order already exists in its new state. A reaction's failure does not roll it back. The reaction needs its own delivery and recovery policy.

Microsoft's guide to dispatch before or after commit emphasizes that this choice changes the transaction boundary. There is no shared atomicity merely because two operations occur inside the same method.

Eventual consistency describes a derived view or process catching up later. It does not mean “everything will turn out fine” by waiting: it requires delivery, retry, and recovery mechanisms. If a rule must hold immediately within the order, protect it during confirmation; do not delegate it to a handler that might run later.

When collaboration crosses contexts, an HTTP contract or message may serve as a boundary. Do not directly import another context's aggregate or present two HTTP calls as a shared local transaction.

From the loss window to Transactional Outbox

The preceding implementation leaves an interval between save() and dispatch(). The process can crash there. Publishing first does not fix it either: another component could act on a confirmation that is not subsequently saved.

The Transactional Outbox pattern records the order update and a pending message in the same transaction in the same database. A separate publisher reads those pending records and delivers them. AWS explains this dual-write problem and alternatives in its Transactional Outbox guide.

This SQL is a conceptual outline, not a migration or complete implementation:

BEGIN;

-- La aplicación debe comprobar que esta actualización afectó exactamente una fila.
UPDATE orders
SET status = 'confirmed', version = version + 1
WHERE id = :order_id AND status = 'draft' AND version = :expected_version;

-- El payload representa el contrato de integración elegido por la aplicación.
INSERT INTO outbox (event_id, event_type, payload, created_at)
VALUES (:event_id, 'orders.order-confirmed.v1', :payload, :created_at);

COMMIT;

If the update affects no row, the application must abort and not insert the message. If insertion fails, confirmation also rolls back. That atomicity covers state plus local pending work; it does not magically include the broker.

The publisher may send the message and crash before marking it sent. Upon recovery, it delivers it again. That interval and the need for idempotent consumers are also described in Chris Richardson's pattern. Marking it sent before transmission changes the risk: you could lose it.

Production still needs important details: pending-work claims among workers, lease expiration, retry limits, cleanup, metrics, and problematic-message handling. The event retains its identity on retry; you do not generate a new eventId on every attempt.

Consumer idempotency

Suppose a consumer updates a commercial summary in its own database. It can record a unique key consisting of consumer_name and event_id in the same transaction updating the summary. If the key already exists, that operation has already been applied and the amount is not added again.

Recording “processed” before the effect in separate transactions could lose the effect after a crash. Applying the effect first and recording afterward, also separately, could duplicate it. Protection must align with the resource being modified.

An email or payment provider sits outside that local transaction. There, study its support for idempotency keys and the particular meaning of “accepted,” “sent,” or “charged.” Neither an outbox nor a queue guarantees by itself that an external effect occurs exactly once.

Internal Domain Event and public Integration Event

The domain could continue using OrderConfirmed, while an application adapter produces a smaller external contract:

{
  "id": "event-1",
  "type": "orders.order-confirmed.v1",
  "occurredAt": "2026-01-15T10:00:00.000Z",
  "data": {
    "orderId": "order-1",
    "totalCents": 2500,
    "currency": "USD"
  }
}

This JSON is our illustrative contract, not the specific envelope of an AWS API. We omit the customer because the assumed consumer does not need it. Contract version indicates how to interpret its structure; it does not replace aggregate version.

Conceptually, EventBridge can help route facts to different targets, and SQS can keep work in queues for consumers. Choosing one, both, or neither depends on delivery, isolation, and operational needs; it is not a DDD requirement.

Standard SQS queues can redeliver a message, so AWS recommends designing consumers idempotent against redelivery. EventBridge has retry policies and dead-letter queues described in its target-delivery documentation. Configuring transport does not replace managing business errors, partial effects, or observability.

Two different orders can progress independently. If your consumer requires ordering within one order, design that need explicitly, identify its version, and decide how to handle a late event. Do not assume global ordering because a timestamp is present.

Three decisions that change with the business

Education: completing a lesson is not passing a course

LessonCompleted can update visible progress or prepare a recommendation. But CourseCompleted should only be recorded when course-completion rules are met. Naming every event ProgressUpdated would force each consumer to reinterpret those rules.

If issuing a certificate requires finishing every lesson, do not issue it upon receiving any LessonCompleted. The responsible process must verify the corresponding condition and prevent duplicate certificates. Here you learn to choose fact granularity and avoid confusing a reaction with a new rule.

Reservations: a late reaction does not protect a single place

For capacity-limited reservations, checking and consuming a place need a consistent strategy in the resource controlling availability. Emitting ReservationRequested and waiting for another handler to detect overbooking afterward does not maintain a rule that should have held immediately.

Once the reservation is accepted, ReservationConfirmed can feed a view or notification with tolerable delay. The lesson is not “everything must use events,” but separating the critical decision from deferrable consequences.

Logistics: each fact has its own moment

OrderConfirmed can start shipment preparation but does not mean ShipmentDispatched. The latter requires the logistics process to actually confirm departure. Announcing dispatch early solely to decouple modules makes system language unreliable.

Even within a monolith, you can maintain these collaborations through explicit calls if they are few and clear. A dispatcher deserves to exist when it simplifies varying reactions and their boundaries; if it merely disguises a fixed flow, review its usefulness.

Use AI without delegating consistency decisions

AI can generate message structures and tests, but also put a publisher inside the aggregate, create a new UUID on retry, or wrap HTTP and SQL in a supposed “transaction.” Request observable decisions and check them against concrete failures.

To analyze the model:

In this system, confirming an order changes its state and requires a positive amount. Statistics may be delayed. Propose business facts and distinguish each from commands and technical events. Do not add a broker. Explain which rule is protected immediately and which reaction can fail afterward. A person will review whether names match business language.

To implement the in-memory case:

Generate TypeScript with an Aggregate Root recording OrderConfirmed and a use case saving before dispatch. Inject clock and identifier. Use small handlers and tests for failed saving, redelivery, and post-save error. Do not present it as guaranteed delivery; identify the loss window and do not introduce new packages.

To review reliability:

Review this persistence and publication flow. Identify actual transaction boundaries and simulate a crash before commit, after commit, and after sending but before recording success. Look for duplicates and losses. If proposing an outbox, explain what it guarantees and what still needs idempotency. Do not assume email rolls back with SQL. Human review will check every scenario and executed test.

Prompts do not replace tests. Examine particularly whether an example uses mutable references, handlers make decisions belonging to the aggregate, or a later failure is incorrectly presented as an order rollback.

Exercises for applying what you learned

1. Distinguish intent from fact

One process receives SendOrderConfirmationEmail and another OrderConfirmed. Which works better as an order-domain event? What happens if the notification channel changes?

Reasoned solution: the first instructs a particular effect; the second expresses the order transition. A handler can decide to prepare email or another channel's message without changing confirmation's meaning. If the business needs to record a delivered notification, that is another, later, distinct fact.

2. Find the failure after saving

In the fourth test, change handler order: put the failing one first and the commercial summary afterward. Predict order state, summary, and notification queue. Will repeating the command repair them?

Reasoned solution: the order remains confirmed, the summary stays at zero, and the queue empty because the dispatcher stops at the first error. Repeating the command records no new event. Changing order alters partial effects but does not remove the absence of persistent pending delivery. Add assertions to check that prediction.

3. Make a persisted effect idempotent

A consumer receives the same event twice and adds 2500 cents each time. Propose preventing the second addition. Then consider summary updating succeeding but saving the processed marker failing.

Reasoned solution: use a unique consumer-and-event key and save both marker and summary update in one local transaction. If the second write fails, that transaction must roll back the first as well. On redelivery, the key's existence prevents repeating an already confirmed effect. If the effect is external, this local solution is insufficient: examine that provider's contract and idempotency.

What to review before incorporating events into your model

A good event precisely states what happened, preserves necessary data, and does not force the aggregate to know its consumers. A good implementation makes visible when state is committed, who reacts, and what happens when a reaction fails.

Start with those agreements and tests that can refute them. If explicit local collaboration suffices, keep it simple. When the reaction must survive a crash, incorporate pending-work persistence, recovery, and idempotency according to the real effect. The name OrderConfirmed provides language; reliability depends on the complete flow built around it.

Loading conversation…

Keep learning