Domain-driven design

An aggregate root enforces the rules of its cluster in one transaction, and other bounded contexts react to its domain events later, in theirs.

Assembling the machine…

Listing

  1. // sales · order.ts
  2. class Order {
  3. addLine(line) {
  4. const sum = this.total + line.amount;
  5. if (sum > this.limit)
  6. throw new OverLimit(this.id);
  7. this.lines.push(line);
  8. }
  9. }
  10. // sales · commands.ts
  11. async function addLine(cmd) {
  12. const order = await orders.get(cmd.id);
  13. order.addLine(cmd.line);
  14. await orders.save(order); // versioned
  15. }
  16. async function placeOrder(cmd) {
  17. const order = await orders.get(cmd.id);
  18. order.place(); // records OrderPlaced
  19. await orders.save(order); // + its event
  20. }

Step 1 / 8

A buyer adds a line

Buyer A adds a 150 € line to order 42, whose approved limit is 1,000 €. The command reaches the application service.

Event log · 1
  1. 0.00 msCMDAddLine(order 42, 150 €) → application service

The concept

An aggregate root enforces the rules of its cluster in one transaction, and other bounded contexts react to its domain events later, in theirs.

Domain-driven design (DDD) is an approach to complex software, set out by Eric Evans in his book of the same name, in which the code follows a model of the business, worked out with domain experts and spoken in one language inside an explicitly bounded context. This machine runs two of its patterns: the aggregate, inside one context, and the boundary between two contexts.

An aggregate is a cluster of entities and values changed as one unit. One entity is its root: code outside the aggregate holds references to the root only, and the root enforces the rules that span the cluster. A purchase order is the classic example: its lines may not total more than its approved limit, so a line is added through the order, never on its own.

The aggregate is also the unit of a transaction. A repository loads and saves the whole aggregate, and a version on the root, checked at each save, stops two users from committing changes that are each valid and together break the limit. Vaughn Vernon's rule of thumb: change one aggregate per transaction, and keep aggregates small.

A rule that spans aggregates, or bounded contexts, is kept eventually consistent. The root records a domain event, OrderPlaced; Shipping, a bounded context with its own model of a shipment, reacts to it later in its own transaction, and a delivery that fails is tried again. Sales does not wait for Shipping, and Shipping being down does not undo an order.

Here the event is saved in the same transaction as the order and published afterwards by a relay: the transactional outbox, one common way to do it. Evans and Vernon leave the mechanism open; what they ask is that changes cross an aggregate's boundary asynchronously.

The run, step by step

Every scenario, in words.

What the machine plays, step by step. Beside a step, what a what-if switch plays in its place, or adds right after it.

Add a line

8 steps
  1. Play

    A buyer adds a line

    Buyer A adds a 150 € line to order 42, whose approved limit is 1,000 €. The command reaches the application service.

  2. Play

    Load the whole order

    The repository loads order 42 as one piece: the root, its two lines, and the version it was last saved at, 3.

    • With Add lines behind the root

      Play

      Straight to the lines

      The service builds the line and inserts it through a repository for lines. The order is never loaded and its root never runs: nothing checked the line. 950 € still fits, by luck.

  3. Play

    Through the root

    The service does not touch a line itself: it asks the order to add one. Order is the aggregate root, the one object outside code may call.

    • With Add lines behind the root

      Play

      One line too many gets in

      Buyer A adds another 100 €. The insert goes through the same way: order 42 now holds 1,050 € of lines on a 1,000 € limit, and no code compared them.

  4. Play

    The root checks the limit

    800 € + 150 € = 950 €, within 1,000 €: the root adds the line. The rule is checked where the lines live, whoever calls.

    • With Add lines behind the root

      Play

      201 for an order over its limit

      Both requests get 201. Order 42 breaks its own rule, and nothing will notice: the one place the rule is written was never called.

  5. Play

    Saved as one, version 3 to 4

    The repository saves the whole order in one transaction, on condition that it is still at version 3. It is: the line is in, and the order moves to version 4.

    • With Save without a version

      Play

      Saved as one

      The repository saves the whole order in one transaction: the line is in. Nothing checks which version it was loaded at.

  6. Play

    One line too many

    Buyer A adds another 100 €. The service loads the order again, now at 950 €, and asks the root to add the line.

  7. Play

    The root refuses

    950 € + 100 € = 1,050 €, over the limit. The root throws before touching its lines, and nothing is saved.

  8. Play

    The refusal goes back

    Buyer A gets 422: the line would take the order over its approved limit. The order and its lines are as they were.

Two buyers at once

6 steps
  1. Play

    Two buyers, one order

    Buyer A and buyer B each add a 150 € line to order 42, at the same moment. Each line, on its own, fits within the 1,000 € limit.

  2. Play

    Two copies of version 3

    Each command loads its own copy of order 42: 800 €, version 3. Neither copy knows about the other.

    • With Add lines behind the root

      Play

      Both lines go straight in

      Each command inserts its line through the lines repository. No root runs and no check: order 42 ends at 1,100 € on a 1,000 € limit.

  3. Play

    Each copy passes the check

    On each copy the root computes 800 € + 150 € = 950 €, within the limit. Each check is right about the copy it sees.

    • With Add lines behind the root

      Play

      201 for both

      Both buyers get 201, and the order breaks its rule. No version could catch it either: neither command loaded or saved the order.

  4. Play

    A commits first

    A's save finds the order still at version 3: its line goes in, and the order moves to version 4 at 950 €.

    • With Save without a version

      Play

      A commits first

      A's save goes through: its line is in, and the order is at 950 €.

  5. Play

    B's copy is stale

    B's save also asks for version 3, but the order is at version 4 now. No row matches: the save fails and its transaction rolls back, line included.

    • With Save without a version

      Play

      B commits too

      Nothing checks the version B loaded: its line goes in as well. Order 42 now holds 1,100 € on a 1,000 € limit, though each check passed.

  6. Play

    409 for buyer B

    B's line was never written: B gets 409 and reloads the order. If B tries again, the root sees 950 € and refuses the 150 €.

    • With Save without a version

      Play

      201 for both

      Both buyers get 201. The rule held on each copy and broke on the order: only a version checked at save time sees two copies of one order.

Place the order

6 steps
  1. Play

    Buyer A places the order

    Order 42 is complete, and buyer A places it. Shipping must then send it, but Shipping is another bounded context, with its own model and its own database.

  2. Play

    The root records OrderPlaced

    The service loads the order and calls order.place(). The root records a domain event, OrderPlaced: a fact the business cares about, kept with the order until it is saved.

  3. Play

    Order and event, one commit

    The repository saves the order and its event in one transaction: the event goes into an outbox table in Sales' own database. Both are saved, or neither is.

    • With Call Shipping before the commit

      Play

      Shipping, called inside the transaction

      Before committing, placeOrder calls Shipping's API to create the shipment. Shipping is down for a deploy: the call hangs until its 5 s timeout, with Sales' transaction open.

  4. Play

    Placed: Sales answers

    Buyer A gets 200 at once. Sales does not wait for Shipping, and does not need it to be up.

    • With Call Shipping before the commit

      Play

      The order rolls back

      The call failed, so placeOrder throws and the transaction rolls back: order 42 is not placed. Sales fails because Shipping is down. Sent as an event, the order would have stood.

  5. Play

    Shipping is down: the event waits

    The relay reads OrderPlaced from the outbox and delivers it to Shipping, which is down for a deploy. The event stays in the outbox for another try.

  6. Play

    Redelivered: a shipment, in Shipping's words

    Once Shipping is back, the relay delivers again. In its own transaction, Shipping creates shipment S-17: a parcel and an address for order 42, no prices. It acknowledges, and the event leaves the outbox.