Domain Events: Facts, Not Calls

Lesson 5 of the DDD course · State + events out, handlers in the shell · ~25 minutes

1 · Value objects 2 · Entities & identity 3 · Aggregates 4 · Lifecycle state machines 5 · Domain events 6 · Bounded contexts 7 · Context mapping 8 · Functional core 9 · Capstone
Why this matters for your mission Side effects — emails, analytics, warehouse feeds — are where young codebases rot. Today's pattern keeps every one of them out of your domain core, so business logic stays testable and new integrations stop requiring surgery on old functions.

Your transitions are pure — which raises the obvious question: how does anything actually happen? The answer is the last functional pattern you need: return the facts, let someone else act on them.

1 · The problem: the function that wants everything

The day after launch, the requests arrive. When an order is placed, we must:

The naive path: place() grows parameters — emailService, warehouseClient, analytics — and calls them. Now the heart of your domain depends on I/O. It can't be tested without mocks, can't run in a script, can't be reused by the bulk-import job without faking four services. And adding the Slack integration means editing — and re-risking — the most critical function you own.

2 · The reframing: announce facts

A domain event is a statement about something that happened, named in the business's past tense — OrderPlaced, not PlaceOrder.[Khononov] Two properties make them powerful:

The pattern Transitions return state and events: { placed, events: [...] }. The core stays pure — it computes facts. The shell (Lesson 8) takes those facts and does the I/O: send the email, call the warehouse, fire analytics.

3 · Events as a discriminated union

Same machinery as Lesson 4 — events are just more data:

type OrderEvent =
  | { readonly type: "OrderPlaced";
      readonly orderId: OrderId;
      readonly customerId: CustomerId;
      readonly total: Cents }
  | { readonly type: "OrderShipped";
      readonly orderId: OrderId;
      readonly shipment: Shipment };

And the transition changes shape:

interface Placed<O> { readonly placed: O; readonly events: readonly OrderEvent[] }

export function place(d: DraftOrder, p: Payment): Result<Placed<PlacedOrder>, PlaceError> {
  // …same three validations as Lesson 4…
  const placed: PlacedOrder = { kind: "placed", id: d.id, lines: d.lines,
                                 total: d.total, paymentId: p.id };
  const events = [{ type: "OrderPlaced", orderId: d.id,
                    customerId: d.customerId, total: d.total }];
  return { ok: true, value: { placed, events } };
}

Note what the failure path returns: { ok: false, error } — and no events. A rejected placement never happened; facts are only minted on success. That single rule is what keeps “OrderPlaced” trustworthy everywhere downstream.

4 · Handlers live in the shell

// shell — the only place that knows about email
function dispatch(events: readonly OrderEvent[]): void {
  for (const e of events) {
    switch (e.type) {
      case "OrderPlaced":  emailer.sendConfirmation(e.orderId, e.total);
                           warehouse.enqueue(e.orderId);
                           analytics.track("order_placed", { total: e.total });
    }
  }
}

The wholesale-Slack request arrives next quarter. You add a case — or a new subscriber — and the core function you tested to death in Lesson 4 doesn't change by a byte. That is the whole point: new side effects must not require touching proven logic.

Gotchas (1) Name events in past tense, always — “OrderPlaced”, never “OrderPlacing”; a fact about an intent is a lie. (2) Payloads must be self-sufficient: consumers get ids and values, not instructions to re-load your aggregates. (3) Don't confuse events with commands: PlaceOrder is a request (may fail); OrderPlaced is a fact (already true). (4) Storing events to rebuild state later is event sourcing — powerful, and explicitly out of our scope until the basics are load-bearing.

5 · Practice: events on success only

6 · Retrieval check

7 · Where this goes next

Your model is now functionally complete at the scale of one module. But Meridian is more than orders — catalog, billing, shipping — and the word “product” means something different in each. Next lesson goes strategic: bounded contexts.

Your teacher is the agent A great review question to bring me: “which of my side effects are facts about my domain, and which are just integration details?” Splitting that list correctly is the judgment this lesson exists to build.
Primary source for this lesson Read Khononov's treatment of domain events in *Learning Domain-Driven Design* (domain events chapter), then see the same idea as “workflows return events” in Wlaschin's *Domain Modeling Made Functional*, part 3.
← Lesson 4: State machines Patterns cheat sheet →