Skip to main content

Aggregate Design Canvas

As built

Derived from network/model/model.yaml. This context's service is built; the model carries its as-built contracts, and identifiers (Err... names, routes, CloudEvents types) are the names the service uses.

Following the ddd-crew Aggregate Design Canvas v1.1. The context has two aggregate roots: FulfillmentAssignment, and the small versioned SourcingPolicy document (below). Everything else it holds is a read model fed by sibling events.

FulfillmentAssignment​

1. Name​

FulfillmentAssignment (proposed package internal/domain/assignment, assignment.FulfillmentAssignment), identified by assignmentId.

2. Description​

One shipment group of one customer order, its promise constraints, the current candidate node and path, and the history of releases. From release until the end of its life, or until the merge is dissolved, it may be a member of a consolidation merge: the carrier (the due assignment) or a follower absorbed into the carrier's release.

It carries:

PartShape (model value_objects and event data)
Identity and correlationassignmentId; orderId, groupNo
DestinationdestinationPostalPrefix, from CustomerOrderPlaced; needed to find the delivery station of a candidate path. The model's value objects do not list it (open question on the canvas)
Promise constraintPromiseConstraint{promiseId, tier (five values, CONSOLIDATED included), deliverByEarliest (optional), deliverByLatest, witnessNodeId}
Lineslines(catalogItemId, listingId, quantity), as released; listingId is resolved per node from AvailabilityView
Current candidateCandidate{nodeId, pickupDepartureId, legs[], deliveryWaveId, eta, cost, estimatedCostCents, effectiveCostCents, policyVersion, estimatedCo2eGrams, emissionComplete}; the two carbon fields are recorded and never ranked on (service ADR 0017)
ConsolidationConsolidationLink{consolidationKey, consolidatedInto (follower), members (carrier)}; the key is optional and never exposed on REST
Release pointreleaseAt (VirtualQueue)
Release historyRelease{releaseNo, nodeId, releasedAt, requiredShipBy, outcome(ACCEPTED, REJECTED, EXPIRED, PENDING, WITHDRAWN), reasonCode}
ExclusionsExcludedNode{nodeId, reason}
ConcurrencyassignmentVersion (strictly increasing)
Lock and outcome factslockedAt, lockReason, trackingNumbers, shippedAt, deliveredAt (from the event data)

It owns no stock and no capacity. It does not compute the promise, and it does not run the purchase-order clock (ackBy belongs to vendor-connectivity).

3. State Transitions​

Derived from: model.yaml → contexts[order-sourcing].aggregates[FulfillmentAssignment].states, .transitions, .commands (the initial QueueAssignment edge, which the transitions list does not spell out).

Omitted: DELIVERED and CANCELLED are drawn as final because no transition leaves them; the model does not name terminal states for this aggregate. UNSOURCEABLE is not final: ApplyRevisedPromise re-queues it (and applies in every other non-terminal state without a state change). A merge is not a state: the carrier and its followers are all RELEASED (then LOCKED, SHIPPED, DELIVERED), and Requeue returns every member of a dissolved merge to QUEUED. The self-transition QUEUED → QUEUED covers both a change of candidate and a re-optimisation that keeps the same one. In RELEASED exactly one release is PENDING (a purchase order sits at the node); from LOCKED on, the node never changes.

4. Enforced Invariants​

InvariantEnforced by
A released candidate's eta <= deliverByLatestReleaseToNode, HandleNodeRefusal (re-queue), ReoptimiseAssignment → ErrCandidateBreaksPromise
No change of node after LOCKEDReoptimiseAssignment, HandleNodeRefusal on a locked assignment → ErrAssignmentLocked
A node that refused this group is never released to again for the same promise revisionReleaseToNode, ReoptimiseAssignment (candidate selection) → ErrNodeExcluded
At most one release PENDING at a timeReleaseToNode while RELEASED; ReoptimiseAssignment while RELEASED → ErrReleaseInFlight
assignmentVersion strictly increasesevery save (optimistic concurrency) → ErrStaleAssignmentVersion
Cancel only before LOCKED; a request on a locked assignment is refused with FulfillmentCancelRefusedCancelAssignment → ErrCancelAfterLock, then RefuseCancel
A member of a live merge (carrier or follower, RELEASED, not yet LOCKED) is not cancelled: the cancel is refused with reason CANCEL_WHILE_MERGED, the state does not change and the merge stays intactCancelAssignment → ErrCancelWhileMerged, then RefuseCancel

Derived from: model.yaml → aggregates[FulfillmentAssignment].invariants. Which command checks which invariant is this pack's reading of the rule text; the model attaches each rule to the aggregate, not to a command.

5. Corrective Policies​

Own policies (contexts[order-sourcing].policies):

  • VirtualQueue: releaseAt = pickup cutoff of the best candidate - node handling time - vendor ack budget; release immediately for SAME_DAY. A re-optimisation that changes the best candidate moves releaseAt with it.
  • AssignmentCost: money first (effectiveCostCents, see RegionalBudget), then legs + crossRegionPenalty + scorecardPenalty + bookPressurePenalty as tie-breakers; ties go to the witness node. Only candidates with eta <= deliverByLatest that are not excluded are ranked.
  • RegionalBudget (SourcingPolicy): effectiveCostCents = estimatedCostCents + crossRegionSurchargeCents for a cross-region candidate. Among candidates within cheapest + floor(cheapest x maxCostDeviationPercent / 100) an in-region one beats a cross-region one; the rule is active only when the percent is above 0, so with nothing published the ordering is the one before the policy.
  • ConsolidatedHold: a CONSOLIDATED group is searched with NotBefore = deliverByEarliest and released at the LATEST pickup that still reaches the chosen wave (after money, before the ordinal penalties), so the queue holds it as long as the shopper's day allows.
  • ConsolidationAtRelease: at release the due carrier absorbs compatible QUEUED CONSOLIDATED groups of the same key and destination (the pure sourcing.Merge, rules c1 identity, c2 node, c3 window overlap, c4 one covering owner per summed item, c5 caps), up to consolidationMaxAssignments; otherwise it releases alone.
  • ConsolidationDissolution: a refused or expired carrier release re-searches every member on its own; a promise revision that excludes the merged eta withdraws the release (FulfillmentReleaseWithdrawn) and re-queues every member. After the lock nothing dissolves.
  • ReassignOnRefusal: on PurchaseOrderRejected or PurchaseOrderExpired, exclude the node and re-queue; if no candidate meets deliverByLatest, UNSOURCEABLE.
  • LockOnCommit: on PurchaseOrderAccepted the assignment is LOCKED (the vendor-node equivalent of the item being picked).

Neighbours' reactions that close the loops:

Neighbour policyTrigger from this aggregateEffect
vendor-connectivity IssueOnReleaseFulfillmentReleasedToNodeIssues a purchase order; poNumber is idempotent on assignmentId + releaseNo.
vendor-connectivity ExpireUnacknowledged(its own sweep)ISSUED past ackBy → PurchaseOrderExpired, which drives HandleNodeRefusal.
vendor-connectivity CancelOnSourcingCancelFulfillmentCancelledCancels the ISSUED purchase order of that release.
delivery-promise RepromiseOnRiskFulfillmentUnsourceableRecomputes and revises the promise (PromiseRevised → ApplyRevisedPromise); if nothing is feasible even at STANDARD, reports PromiseBroken at judgement time.
vendor-connectivity CancelOnReleaseWithdrawnFulfillmentReleaseWithdrawnCancels the ISSUED purchase order of that releaseNo (never the latest release).
linehaul-transportation BookOnLockFulfillmentLocked; FulfillmentCancelled or reassignmentBooks one package on the pickup departure; releases it on cancel or reassignment.
linehaul-transportation FollowerLockBooksNothingFulfillmentLocked with consolidatedIntoA follower's lock books nothing; the carrier's lock books the one package.
customer-ordering CancelOnUnfulfillableFulfillmentUnsourceable and no feasible revisionCancels the group (CustomerOrderCancelled); an UNSOURCEABLE assignment can be cancelled.

6. Handled Commands​

CommandTransitionIssued by
QueueAssignment[*] → QUEUEDKafka consumer of CustomerOrderPlaced, one per group
ReoptimiseAssignmentQUEUED → QUEUEDre-optimisation sweep over QUEUED rows (scheduler); planner POST /assignments/{assignmentId}/reoptimisations
ReleaseToNodeQUEUED → RELEASED or QUEUED → UNSOURCEABLErelease timer at releaseAt; at once for SAME_DAY, right after QueueAssignment
ReleaseConsolidatedQUEUED → RELEASED (the carrier)ReleaseToNode, when the policy is on and a follower fits
ReleaseAsFollowerQUEUED → RELEASED (each follower, at the carrier's candidate)the same unit of work
RequeueRELEASED → QUEUED (every member of a dissolved merge)Kafka consumer of PromiseRevised
HandleNodeRefusalRELEASED → QUEUED or RELEASED → UNSOURCEABLEKafka consumer of PurchaseOrderRejected, PurchaseOrderExpired
LockAssignmentRELEASED → LOCKEDKafka consumer of PurchaseOrderAccepted
MarkShippedLOCKED → SHIPPEDKafka consumer of VendorShipmentConfirmed
MarkDeliveredSHIPPED → DELIVEREDKafka consumer of PackageDelivered
CancelAssignmentQUEUED → CANCELLED, an unmerged RELEASED → CANCELLED or UNSOURCEABLE → CANCELLEDKafka consumer of CustomerOrderCancelled, per groupNos
RefuseCancelLOCKED, SHIPPED, DELIVERED, or a merged RELEASED member, unchanged (version + 1)same consumer, when CancelAssignment hits ErrCancelAfterLock or ErrCancelWhileMerged
ApplyRevisedPromiseevery non-terminal state (replaces the constraint; UNSOURCEABLE → QUEUED when a candidate exists; a revision that dissolves a merge goes through Requeue)Kafka consumer of PromiseRevised

7. Created Events​

All are published as com.retailnetwork.commerce.order-sourcing.assignment.<EventName> on retailnetwork.order-sourcing.events (the analytics-only ones on retailnetwork.order-sourcing.analytics), subject assignmentId.

EventRaised whenFull CloudEvents type
FulfillmentQueuedQueueAssignment savedcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentQueued
FulfillmentReassignedthe candidate node changes: ReoptimiseAssignment picks another node, or HandleNodeRefusal re-queues on another nodecom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentReassigned
FulfillmentReleasedToNodeReleaseToNode → RELEASEDcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentReleasedToNode
FulfillmentUnsourceableReleaseToNode or HandleNodeRefusal → UNSOURCEABLEcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentUnsourceable
FulfillmentLockedLockAssignmentcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentLocked
FulfillmentShippedMarkShippedcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentShipped
FulfillmentDeliveredMarkDeliveredcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentDelivered
FulfillmentCancelledCancelAssignmentcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentCancelled
FulfillmentCancelRefusedRefuseCancelcom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentCancelRefused
FulfillmentConstraintRevisedApplyRevisedPromise, always (analytics only)com.retailnetwork.commerce.order-sourcing.assignment.FulfillmentConstraintRevised
FulfillmentSourcingDecidedReleaseToNode, one per release (analytics only, ADR 0013)com.retailnetwork.commerce.order-sourcing.assignment.FulfillmentSourcingDecided
FulfillmentReleaseWithdrawnRequeue after a promise revision dissolved a mergecom.retailnetwork.commerce.order-sourcing.assignment.FulfillmentReleaseWithdrawn
AssignmentsConsolidatedReleaseConsolidated (analytics only)com.retailnetwork.commerce.order-sourcing.assignment.AssignmentsConsolidated
AssignmentsDeconsolidateda merge ends before the lock (analytics only)com.retailnetwork.commerce.order-sourcing.assignment.AssignmentsDeconsolidated

Derived from: model.yaml → aggregates[FulfillmentAssignment].events, .transitions; publishes[*].data. The model lists the events but not which command raises which; the pairing above follows the transitions and each event's data (FulfillmentReassigned carries fromNodeId, toNodeId). ApplyRevisedPromise always raises FulfillmentConstraintRevised (analytics only, ADR 0002 A9); a ReoptimiseAssignment that keeps the same node raises nothing.

8. Throughput​

Estimate. The model says "medium-high; re-optimisation sweeps touch QUEUED rows only". One QueueAssignment per shipment group at the order rate; one release, one lock, one shipment and one delivery per group on the happy path. The sweeps dominate writes while the queue is long (STANDARD groups wait the longest). Contention points: a sweep and a purchase-order outcome on the same assignment, and the planner's re-optimise. assignmentVersion turns every such race into ErrStaleAssignmentVersion and a retry from a fresh load. Kafka keys by assignmentId, so one assignment's events are ordered.

9. Size​

Estimate. The model says "one row per shipment group + releases". A group has a handful of lines; releases are usually one and are bounded by the number of candidate nodes, because each refusal excludes a node; exclusions grow by one per refusal. Lifetime: from checkout to delivery (days), then a closed record. Events per instance on the happy path: FulfillmentQueued, zero or more FulfillmentReassigned, FulfillmentReleasedToNode, FulfillmentLocked, FulfillmentShipped, FulfillmentDelivered; each refusal adds FulfillmentReassigned (or FulfillmentUnsourceable) and another FulfillmentReleasedToNode.

SourcingPolicy​

A single versioned document, copied from delivery-promise's PromisePolicy: one current version, every publish creates version n + 1, versions are kept, and version 0 is the built-in default (nothing published). The search reads it once per search through the repository and takes it as an input; the domain makes no call.

PartContent
Fields (all integers)crossRegionSurchargeCents 0 to 100000 (default 0), maxCostDeviationPercent 0 to 200 (default 0), consolidationMaxAssignments 0 to 10 (default 0; 0 and 1 mean consolidation is off)
Invariantsa publish is version current + 1 (ErrVersionNotNext; a lost race is retried once, then 409 concurrent-update); every field inside its range (ErrValidation, 422 validation-failed)
CommandPublishSourcingPolicy: PUT /sourcing-policy, the WHOLE document (an omitted field is 0, an empty body is 400), behind the Idempotency-Key middleware; GET /sourcing-policy reads the current version or the defaults with version: 0
EventSourcingPolicyPublished, analytics only, in the same transaction as the save
Not builtthe split surcharge and the single-node-beats-split preference of the first contract: this context never splits an order, because customer-ordering forms the groups and each group is assigned on its own

Read models​

These hold state but are not aggregates: they enforce no invariant of this context, they are derived only from other contexts' events, and each can be rebuilt by replaying its topics. They are local because the model forbids a synchronous call on this path.

Read modelSource events (model read_models)Used byWhy it is not an aggregate
NodeProfileViewnode-topology NodeRegistered, NodeOperationalProfileDeclared, NodeActivated, NodeSuspended, NodeRetiredcandidate search (only ACTIVE nodes with OUTBOUND), handling time and cutoffs for releaseAtnode-topology owns the node; this is a copy keyed by nodeId, newest profileRevision wins.
NetworkGraphViewnode-topology LaneOpened, LaneClosed, ServiceAreaAssigned, RegionDefined; linehaul-transportation DepartureScheduled, DepartureCapacityChanged, DepartureCancelled; last-mile-delivery DeliveryWaveScheduled, DeliveryWaveCapacityChangedcandidate paths, legs, eta, crossRegionPenaltyLanes, departures and waves belong to three other contexts; the graph is a projection, not a decision.
AvailabilityViewoffer-availability ListingCreated, ListingAvailabilityChanged, ListingSuppressed, ListingRestored, CatalogItemDiscontinuedwhich nodes can ship every line in full; the listingId per (catalogItemId, nodeId) for the releaseThe quantity is the vendor's claim, owned by offer-availability; nothing is reserved here.
ScorecardViewnode-performance NodeScorecardUpdatedscorecardPenaltyMeasured by node-performance; read only.
PromiseBookPressureViewdelivery-promise PromiseBookExhaustedbookPressurePenaltyThe book is delivery-promise's aggregate; this view only remembers which bookIds were exhausted.

Derived from: model.yaml → contexts[order-sourcing].read_models, .policies[AssignmentCost], node_types (only FULFILLMENT_CENTER has OUTBOUND).

The virtual queue is not a separate store: it is the set of FulfillmentAssignment rows in QUEUED, ordered by releaseAt (see Entity Relationship).