Skip to main content

Aggregate Design Canvas

This page follows the ddd-crew Aggregate Design Canvas v1.1. It replaces the former "Aggregates & Invariants" page: everything that page said about invariants, BR3 and BR6 is kept here, re-checked against internal/domain/order on develop.

internal/domain has exactly one aggregate root, order.Order, with one entity inside it, order.OrderLine. Everything else in the domain package is a value object, a policy, a read model or the release-confirmation process manager (releaseconfirmation.Confirmation, ADR 0043) — see Not aggregates at the end.

Order​

1. Name​

Order (internal/domain/order.Order), with its entity OrderLine (order.OrderLine). Identity: shared.OrderId, minted by ports.OrderRepo.NextID (ord-<uuid> in Postgres, ord-<n> in memory).

2. Description​

The unit of consistency for intake, allocation, release, hold and cancellation of one customer order. It records what was asked for (lines: SKU, quantity, gift wrap), which process path each line resolved to, which inventory-storage reservation backs each allocated line, the delivery promise (per shipment group), and whether the order was held at intake or carries an external ship-by deadline. Every line mutation goes through an Order method, so no invariant can be bypassed from outside: order.New stores its own copy of each OrderLine, so the caller's pointers do not alias the aggregate's entities. Persisted state comes back through one entry point, order.Rehydrate(OrderSnapshot), which does not re-run construction invariants.

Key state (order.go): id, lines []*OrderLine, allowPartialShipment, promiseDate/promiseCptId/promiseBasis (a "latest cutoff" summary of promiseGroups), promiseGroups []PromiseGroup, heldAtIntake (the inverse of ReleaseOnAllocation()), requiredShipBy, and version (optimistic-concurrency metadata only, ADR 0024).

3. State Transitions​

The aggregate stores line states; the order-level Status is derived on every call (Order.Status()), never stored.

Line lifecycle — order.LineStatus and the Order methods that move it:

Source: internal/domain/order/order.go (Allocate, RetryAllocate, ReconfirmReservation, LoseReservation, MarkBackordered, Release, Cancel, and Ship/ShipAll in ship.go), internal/domain/order/status.go, internal/domain/order/order_line.go. Omits: the error returned by each illegal transition (listed under invariants below). Cancel moves every line at once and is refused if any line is Released.

Order status — derived by Order.Status() in this precedence order:

Source: Order.Status() in internal/domain/order/order.go. Omits: a held order (releaseOnAllocation=false) is deliberately not a separate status — it reads Allocated until ReleaseHeldOrder runs (ADR 0020).

4. Enforced Invariants​

InvariantEnforced byError
An order has at least one lineorder.Neworder.ErrNoLines
An order has an idorder.New, shared.NewOrderIdshared.ErrEmptyOrderID
SKU is non-emptyorder.NewOrderLine, shared.NewSKUshared.ErrEmptySKU
Quantity is greater than zeroorder.NewOrderLineshared.ErrNonPositiveQuantity
A line number addresses a real lineOrder.line (every mutator)order.ErrLineNotFound
A line cannot be allocated twiceOrder.Allocate, Order.MarkBackorderedorder.ErrLineAlreadyAllocated
Only a Pending line is allocated by the first pass — a Backordered line comes back only through retryOrder.Allocateorder.ErrLineNotPending
Only a Backordered line can be retriedOrder.RetryAllocateorder.ErrLineNotBackordered
Only an Allocated line can be released, reconfirmed or lose its reservationOrder.Release, Order.ReconfirmReservation, Order.LoseReservationorder.ErrLineNotAllocated
Only a Released line can ship; a Shipped line is terminal, and an order with no Released or Shipped line is not shippable (ADR 0051)Order.Ship, Order.ShipAllorder.ErrLineNotReleased, order.ErrOrderNotShippable
BR3 — a ship-complete order releases nothing while any line is unallocatedOrder.EnsureReleasableorder.ErrShipCompleteBlocked
BR6 — no cancellation once any line is Released or ShippedOrder.EnsureCancellable, Order.Cancelorder.ErrOrderAlreadyReleased
A held order must be ship-complete (ADR 0020)order.ValidateIntakeIntentorder.ErrHeldOrderMustBeShipComplete
Order Status is derived from lines, never storedOrder.Status() (no backing field)—
The promise summary always describes the group with the latest cutoffOrder.SetPromiseGroups—
No lost update between concurrent read-modify-savepostgres.OrderRepo.Save (WHERE id AND version)ports.ErrConcurrentModification

Checked in the use case, before the aggregate is persisted:

RuleEnforced byError
Each line's resolved path is active in the catalogue (ADR 0013)ReceiveOrder.buildDomainLinesshared.ErrUnknownProcessPath
Some active path admits the line's attributes (ADR 0016/0021)PathSelectionPolicy.Select via buildDomainLinesshared.ErrLineIneligibleForResolvedPath
Retry needs a backordered lineRetryAllocation.Executeusecases.ErrNoBackorderedLines
Release-on-demand only for a held orderReleaseHeldOrder.Executeusecases.ErrOrderNotHeld

BR2 (fail closed on ambiguity) lives at the port boundary: only ports.ErrInsufficientStock (inventory-storage's 409) backorders a line; any other error aborts the pass (allocateLines in internal/application/usecases/allocation.go). BR3 in practice: releaseAllocatedLines checks EnsureReleasable and, when it fails, releases nothing and returns no error — so the HTTP caller sees 200/201 with a Backordered order — BR3 is a hold, not an error, so there is no ship-complete-blocked problem type (pinned by br3_block_test.go).

5. Corrective Policies​

SituationCorrective policyCode
A line was backordered (409)Operator or caller retries: POST /orders/{id}/allocation-retries re-reserves only the backordered linesusecases.RetryAllocation
A reservation lapsed upstream before releaseReconfirm every previously allocated line right before release; a 409 now moves the line back to Backordered (LoseReservation) and, for a ship-complete order, blocks the releasereconfirmAllocatedLines, reconfirmBeforeRelease
Hard failure part-way through allocationKeep the lines that did allocate (their reservations are real), save, and raise OrderAllocationPartiallyFailedsalvageAllocationFailure
The building missed a CPT or manifested a packageRecompute the line's shipment group; if the promise moved, save and raise OrderRepromisedusecases.RepromiseOrder
Customer or network partner withdraws before releaseRevoke every allocated reservation, then cancel every lineusecases.CancelOrder
Concurrent writersSecond save fails with ErrConcurrentModification (HTTP 409, Kafka consumer retries then DLQ)postgres.OrderRepo.Save

Not corrected here (documented gaps): an orphaned hold is not swept by this service (network-fulfillment's SweepOrphanedHolds cancels it, ADR 0020 accepted deferral); released work is never clawed back after cancellation (ADR 0004).

6. Handled Commands​

CommandEntry pointAggregate methods
ReceiveOrderPOST /ordersorder.New, ValidateIntakeIntent, Hold, SetRequiredShipBy, then the allocation pass below
Allocation pass (internal, allocateAndRelease)inside ReceiveOrder, RetryAllocation, ReleaseHeldOrderAllocate / RetryAllocate / MarkBackordered, SetPromiseGroups, ReconfirmReservation / LoseReservation, EnsureReleasable, Release
RetryAllocationPOST /orders/{id}/allocation-retriesRetryAllocate, MarkBackordered, then release as above
ReleaseHeldOrderPOST /orders/{id}/releasesReconfirmReservation / LoseReservation, EnsureReleasable, Release
CancelOrderDELETE /orders/{id}EnsureCancellable, Cancel
RepromiseOrderKafka warehouse.fulfillment.eventsSetPromiseGroups

7. Created Events​

All events are built in internal/domain/shared/events.go and published as CloudEvents 1.0 with type = com.warehouse.wes.order-management.order.<EventName> (internal/adapters/kafka/cloudevents):

EventFull CloudEvents typeRaised by
OrderReceivedcom.warehouse.wes.order-management.order.OrderReceivedReceiveOrder
OrderLineAllocatedcom.warehouse.wes.order-management.order.OrderLineAllocatedallocation pass
OrderLineBackorderedcom.warehouse.wes.order-management.order.OrderLineBackorderedallocation pass, reconfirm
OrderAllocatedcom.warehouse.wes.order-management.order.OrderAllocatedallocation pass (status Allocated or Released)
OrderPartiallyAllocatedcom.warehouse.wes.order-management.order.OrderPartiallyAllocatedallocation pass (status PartiallyAllocated or PartiallyReleased)
OrderAllocationPartiallyFailedcom.warehouse.wes.order-management.order.OrderAllocationPartiallyFailedsalvageAllocationFailure
OrderCancelledcom.warehouse.wes.order-management.order.OrderCancelledCancelOrder
OrderRepromisedcom.warehouse.wes.order-management.order.OrderRepromisedRepromiseOrder
OrderLineReleasedcom.warehouse.wes.order-management.order.OrderLineReleasedallocateAndRelease (publishReleaseFacts), once per line released in the pass; analytics only
OrderReleasedcom.warehouse.wes.order-management.order.OrderReleasedallocateAndRelease (publishReleaseFacts), when the pass leaves every line Released; analytics only
OrderReleaseUnconfirmedcom.warehouse.wes.order-management.order.OrderReleaseUnconfirmedFlagUnconfirmedReleases (the housekeeping timeout, ADR 0043), not the aggregate: once per released line that wes-work-planning never confirmed; analytics only, only with RELEASE_CONFIRMATION_MODE=kafka

Topic routing and payloads are on Domain Events.

8. Throughput​

Estimate, not measured. Writes per order are a handful: one intake transaction plus one allocation transaction per POST /orders (both joined into the idempotency middleware's outer transaction when Postgres is on), one more per retry, hold release or cancellation, and one per re-promise that actually moves the promise. Concurrent writes to the same order are rare — a retry racing a cancel, or a re-promise racing a release — and are caught by the version guard rather than locks. Contention is per order, so throughput scales with order volume, not with the size of any single aggregate.

9. Size​

Estimate, not measured. An order holds N lines (no upper bound in code), up to N promise groups, and one reservation id per allocated line. Over its lifetime it typically produces N + 2 events for a clean ship-complete flow (OrderReceived, one OrderLineAllocated per line — the reconfirm step writes no event — and one OrderAllocated), plus one OrderLineBackordered per 409, one OrderRepromised per moved promise and one OrderCancelled if withdrawn. Lifetime runs from intake to Released (Shipped once the opt-in outbound-shipping consumer, ADR 0051, confirms the load) or Cancelled — minutes to hours for a released order; a held order lives until its caller releases or cancels it (no sweeper here; network-fulfillment's sweep cancels an undecided hold, see above).

Not aggregates: read models and policies​

These live in internal/domain (or feed it) but are not the Order aggregate: the read models and policies have no lifecycle of their own and enforce no cross-entity invariant, and the one process manager is kept outside the aggregate on purpose:

TypeKindNotes
order.PlannedCapacityWindowRead model (ADR 0031)Local copy of warehouse-planning's CapacityPlan, last-writer-wins per PlanID (Supersedes), validated by Validate (order.ErrInvalidPlannedCapacity); table planned_capacity_windows. Only annotates order responses (order.CapacityConstraints).
releaseconfirmation.ConfirmationProcess manager (ADR 0043)One row per released line, keyed by order id and line number: PENDING -> CONFIRMED, or PENDING -> UNCONFIRMED -> CONFIRMED (a late confirmation). Deliberately not on the Order: it records another context's behaviour, and a late or missing confirmation never changes an order's status or blocks a transition (there is no foreign key to orders either). Opened in the same unit of work as the release; table release_confirmations; used only with RELEASE_CONFIRMATION_MODE=kafka.
kafkacatalog.Consumer, kafkacptschedule.Consumer, kafkapathcapacity.ConsumerIn-memory read modelsFull-replay caches of process-path catalogue, CPT schedule and path capacity behind ports.ProcessPathCatalogue, ports.CPTScheduleCache, ports.PathCapacity.
report.Row (funnel_rollup, repromise_rollup)Analytics projection (ADR 0006/0019)Written only by cmd/order-projector.
order.PromisePolicy, order.LeadTimePolicy, order.PathSelectionPolicyDomain policiesStateless; compute promises and routing for the Order.
order.Promise, order.PromiseGroup, order.CPTWindow, order.FulfillmentClass, shared.Eligibility, shared.OrderId, shared.SKU, shared.PathIdValue objectsImmutable values. FulfillmentClass (SINGLE, SAME_SKU_MULTI, MULTI_LINE_MULTI) is derived on every call, never stored.

See the class diagrams for their shapes and the ER diagram for how the aggregate maps onto tables.